Jason Lengstorf was nice enough to offer our community a handful of copies of his latest awesome book, Pro PHP and jQuery. Be sure to read his latest Nettuts+ tutorial, “Object-Oriented PHP for Beginners,” based on his book.
Winners Announced:
Congratulations to the following winners, who were randomly selected:
- Jonathan Stuckey
- Rick Blalock
- Matt Vickers
Each of you will be contacted shortly about arranging your free copy. Thanks again to everyone who entered!
“This book is for intermediate programmers interested in building Ajax web applications using jQuery and PHP. Along with teaching some advanced PHP techniques, it will teach you how to take your dynamic applications to the next level by adding a JavaScript layer with jQuery.”
To enter for a chance to win a hardcopy version of the book, leave a comment with a PHP tip. It can be as simple or as long as you like. Just as long as it was something that helped you to learn PHP, that will automatically enter you! On Monday morning, we’ll choose the winners!
You can also purchase “Pro PHP and jQuery” here.


RoyalSlider – Touch-Enable ... only $12.00 
DROP THOSE BRACKETS
Much like using shortcuts when writing else functions, you can also save some characters in the code by dropping the brackets in a single expression following a control structure. Evolt.org has a handy example showcasing a bracket-less structure.
view source
print?
1 if ($gollum == ‘halfling’) {
2 $height –;
3 }
This is the same as:
view source
print?
1 if ($gollum == ‘halfling’) $height –;
You can even use multiple instances:
view source
print?
1 if ($gollum == ‘halfling’) $height –;
2 else $height ++;
3
4 if ($frodo != ‘dead’)
5 echo ‘Gosh darnit, roll again Sauron’;
6
7 foreach ($kill as $count)
8 echo ‘Legolas strikes again, that makes’ . $count . ‘for me!’;
Could you not write something from your own? Or at least be smart enough to remove the extra-text caused by copying?
Comment, Comment, Comment…
Coming back to an un-commented site is absolutely miserable and can slow down the developer GREATLY.
Thanks Jason!
If you don’t know how a php function works, first go to php.net and read the documentation of the function, if you still can’t find useful information, google it. PHP is well documented.
The ternary operator is similar to an if/else statement except that it’s more streamlined. This is a traditional if/else statement:
if (empty($_POST['action'])) {
$action = ‘default’;
} else {
$action = $_POST['action'];
}
This example of a ternary operator will produce the same result as the previous example using less space. It makes use of ? and : just like if and else.
$action = (empty($_POST['action'])) ? ‘default’ : $_POST['action'];
Working with ternary operators do take a little more practice – be sure you test your work as you work through them.
One word: nettuts
Learn a framework, try out CodeIgniter.
sometimes while debugging your code it is nice to use something like this:
echo ”;
var_dump($datastructure);
echo ”;
http://php.net/manual/en/function.var-dump.php
also use php.net a lot! it is one of the greates documentation available!
post missed my echoes, there were pre tag inside of those,
pps.
also echo __FILE__ is nice sometimes!
When designing classes and functions. Make sure to think about how to make them generic and extensible. This will allow you more reuse of the classes and functions you create. This will take more time up front, but the time savings later on will be immense. Also, I would recommend using some sort of versioning system such as Subversion. It will allow you to work with other developers much easier
Comment your code! that way you won’t spend hours searching for that function that turns out to be in app/database/functions/constructors/config/config.php
and also:
while putting variables directly into double quotes can be nice, it is much more scaleable to use single quotes and put variables outside the quotes because if a function converts something to a string and then echos it and that happens to have a $ in it you’re screwed.
Make ‘helper’ functions to make it easy.
Functions, like to print debug strings based on 1 or 2 parameters are really time saving.
’19:00:01′)
foreach($cats as $cat)
$cat->setColor(‘#330000′);
?>
If all else fail, sprinkle the code with: die(“Filename: Linenumber”);
var_dump($foo) has to be one of the best quick n’ dirty debugging tools.
I want it!
My little tip:
// definition
// it’s pretty simple and can be much improved, but so easy to use
function on_page($str){
return (stripos($_SERVER["REQUEST_URI"], $str) !== false);
}
// usage example
if(on_page(‘index’)){
// do your stuff :)
}
use prepared statements for your queries instead of concatenating data to build a query for better security and cleaner code.
Know your php set up.
Simple but cool:
instead of using echo or something :)
Oooops
Disable your register_globals at your php.ini file, otherwise everytime you set a query string variable, the same, with the same name, will be created as a global variable.
For example, if you pass ‘user_id’ as a query string like http://www.yoursite.com?user_id=1 with the register_globals enabled, at this moment, a variable named $user_id will be created and will be globaly accessible from your application.
Imagine the damage that could be caused!
I enjoyed finding out that echo ‘Hello’; was quicker than echo “Hello”; Every little helps :)
Create a debug log to help you troubleshoot things or just to log information you don’t want cluttering up the error log.
error_log(“This is the message I want to log.”, 3, $_SERVER["DOCUMENT_ROOT"].”/debug.log”);
Another tip … don’t be afraid to use a framework. Up until I started my current job back in November 2009, I used my own set of classes to do common things such as connect to a database, send an email, etc. I have recently started using the CodeIgniter framework. It’s not cheating. It’s speeding up your development. Why reinvent the wheel when it’s already in place in a framework.
dates in from mysql formmat to brazilian format:
implode("/", array_reverse(explode("-", $date)))Jonathan it is much easier to use date(‘Y-m-d’, strotime($date))
This is my tip, always keep it simple.
And before you write new mega function, check if it already exists in PHP core ;-)
The most useful thing I have found in my journeys with PHP is the online documentation! What makes it even easier is the direct access to specific pages on the functions or control structures etc that you need help with. If you are looking for syntax examples or assistance with, for example, the include statement – simply visit http://www.php.net/include and you will be presented with the page all about that function! Simple but effective, and more importantly quick and concise (sometimes!) :)
most common question about sessions is how to start them. start your sessions before *any* output, including white space or document/mime types.
etc.etc. etc.
Use print_r to see whats in arrays!
pass true as a second parameter to print_r to put the contents of your array into a string, useful for passing the array contents to the die() function:
die(”.print_r($_POST,true).”);
Instead of doing:
if(isset($something) AND isset($somthingElse) AND isset($anotherThing)) {
Make a function to check an array of variables.
function array_set($array) {
$counted = 0;
foreach($array as $key => $value) {
if(isset($array[$key])) $counted++;
}
if($counted == count($array)) { return true; }
else { return false; }
}
if(array_set(array($something, $somethingElse, $anotherThing))) {
Introduced in PHP 4 there are two special operators that are not normally found in other languages:
1. ===
2. !==
These operators compare the values as well as the type of variable.
With === the variables must be identical, not just equal.
For instance,
0 == “a” is true, because the numerical value of “a” is 0.
but
0 === “a” is false, because 0 is an integer and “a” is a string.
With !== is true when the first variable is not equal to the second variable or if both variables are of a different type.
0 != 0 would be false, because 0 is equal to 0.
but
0 !== 0 would be true, because 0 is an integer and both variables are integers.
It’s complicated, but it’s an added level of security when you are expecting certain variable types.
When printing anything via PHP on a HTML template, always check whether the variable exists, else print a blank otherwise. This will save on so many PHP warnings that occur so often. Adding an extra barrier/function to prevent XSS is good too.
If you remember a php function, but do not remember the exact parameters and return values it has / accepts you can go to php.net/yourfunction (where ‘yourfunction’ is the function example: php.net/mysqli_real_escape_string and it automatically redirects you to the corresponding function @php.net)
When you make a typo or don’t know the exact name, you can enter that and it shows you a list of functions which you might mean. Click it, and you have access to its documentation.
I’m a big fan of Jason and his PHP tuts!
My tip is to use the “strip_tags()” function on variables that are inputted by a user. It’s a security measure that keeps html or php from being injected into your form fields. You can also use it to strip a string of all tags accept the ones you want.
PHP and MS SQL connection using DSN.
I work on a Windows environment hence the use of PHP and MS SQL is vital and this has helped me a lot when it comes to MS SQL connections. I still hope that one day we can move to a greener pasture, MySQL and Unix.
<?php
//connect to a DSN "myDSN"
$conn = odbc_connect('myDSN','','');
if ($conn)
{
//the SQL statement that will query the database
$query = "SELECT table_column FROM table";
//perform the query
$result=odbc_exec($conn, $query);
.
.
.
.
//Do not forget the odbc_fetch_row to get the contents
//close the connection
odbc_close ($conn);
}
parse_url($url) – for parsing urls
If you’re not sure what function to use or you need special functionality first checkout http://www.php.net which is the official documentation site of php. I’ve found some great functions there!
Use isset to check if variables have content or are null/false
if (isset($myVar)){
//do something
}
instead of
if ($myVar){
//maybe do something
}
this will avoid errors
Give your functions, classes and variables useful names, so you know what they do
And use tabs
Who should care to validate forms ??
the Font-End or the Back-End ?
the best answer… the two sides. (:
Shorthand if/else statements using ternary operators always helped me shorten my code. Rather than writing “if this == this, else this”, I could just write:
$num = 5;
$num_is_greater_than_two = ($num > 2 ? true : false);
? = if true
: = if not
The above statement, if $num is greater than 2, return true, else return false!
I’m not sure if this is already posted, but there are so many pages of comments!
Do not use “Short Open Tags” ( http://www.php.net/manual/en/ini.core.php#ini.short-open-tag ) if you’re creating a script that will be distributed to others. This will ensure compatibility with other servers, not all of them will have Short Open Tags enabled.
Also, do not rely on “Register Globals” ( http://www.php.net/manual/en/ini.core.php#ini.register-globals ). If you’re working on something that will be distributed to others, as a security measure, you can reverse the effects of Register Globals by using a snippet similar to: http://pastebin.com/JdDUF2UV
And finally, SECURITY SECURITY SECURITY! http://www.php.net/manual/en/security.php
I got three short tips for you:
##### 1. The “++-Tipp” #####
// it is very useful to know the difference between ++$var and $var++ (also works with –)
$value1 = $value2 = 6;
echo ‘value1: ‘ . $value1++ . ‘ – value2: ‘ . ++$value2;
echo ”;
echo ‘value1: ‘ . $value1 . ‘ – value2: ‘ . $value2;
// while ++$var first increases the var, $var++ is used before increasing
##### 2. The “dirname-Tipp” #####
// if you use files that are included in another script, it is helpful to use the dirname(__FILE__)
// function in includes, because it avoids trouble with paths later
// file1.php located at ../php/scripts/file1.php
// file2.php located at ../php/includes/file2.inc.php
// file3.php located at ../php/includes/file3.inc.php
// so if you use the dirname(__FILE__)-function that returns the absolute path of the current
// file, you are safe if the file is included somewhere later
##### 3. The “short-if-Tipp” #####
// if you have to do a little decision in your code, the short if can be useful
$rand = round(rand());
echo ‘$rand is: ‘ . (($rand) ? ‘one’ : ‘zero’);
// the syntax is “(condition) ? return if condition is true : return if condition is false”
Greets, Felix
One thing I like to do is give pages directory-type layout look, similar to CodeIgniter, but far easier (you would need to run your own complex stuff for things like XSS, etc):
$uri = $_SERVER[REQUEST_URI];
$uri_array = explode(‘/’, $uri);
array_shift($uri_array);
Now all the segments following the page will be in an index-based array.
$foo = array(‘bar’ => ‘doo’, ‘baz’ => ‘var’);
extract($foo, EXTR_SKIP)
echo $bar;
echo $baz;
// simple way to import variable from an array
// save alot of time than
echo $foo['bar']:
Set up a good development environment with debugging support. I use Eclipse with Xdebug. A debugger will allow you to step through the code, watching program flow and variable contents. You’ll never need to use the echo() function for debug again!
Well, right now im learning PHP,
and one of my principal tips is:
Be patient cuz, sometimes you feel that you dont want continue,
this language like all the others is not easy,
you need interest in the language.
and one of the most important things:
You are your teacher.
PD:sorry for my english xD
My PHP experience began when our legacy ASP contact forms died a horrible death and I needed a quick replacement. That’s when I found out about mail() and how easy it was. From there, I found that the following works quite well for automatic error reporting:
mail($to,$subject,$body,$headers);
if(mail){
echo “Your message was sent”; // additional information from the original form data can be inserted here
}
else{ echo “Unhandled exception: please try again”; }
The biggest helper I have is for debugging.
I use:
print_r();
exit();
a ton! Sometimes var_dump(); instead of print_r(); but it helps me see what is coming through. The exit(); helps me scroll to the end of the code, and see what I need quickly. I also use firefox to do so, because you can refresh the view source.
I’m no expert in php, but a good way to learn it is to modify some existing programs.
foreach ($_POST as $key =>value) $$key = $value;
Now you have created variables that correspond to each key of your $_POST values.
example: $_POST['name'] now is available with $name
It’s a great tip, but you have to be careful with data from the user; you should treat every user as a hacker.
Changing a submitting form to this page to include an input named _SERVER['DOCUMENT_ROOT'] you’d be able to dynamically change where you store uploads [for example].
This trick is brilliant for arrays which you know you can trust though.
A way to add prefix to variables is to use ‘extract’.
For example:
extract ($_POST, EXTR_PREFIX_ALL, ‘post’);
Now $_POST['name'] is available as $post_name.
Different condition for prefix is available at: http://us.php.net/manual/en/function.extract.php.
New to php, and just discovered that you can use filter_has_var() to check if a variable of a specified input type exist
Echo prints out text in your php