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.

best macro and I still use this code today
<?php
print '’;
print_r($myvariable);
print ”;
die;
Another great source to learn php: http://www.phpro.org/
This is one of my old login.php files which includes the processing of a form that has submitted data and is passing data from the form to this file.
—————————————————————————————————–
stripslashes
$client_username = stripslashes($client_username);
$client_password = stripslashes($client_password);
$client_displayname = stripslashes($client_displayname);
$client_firstname = stripslashes($client_firstname);
$client_lastname = stripslashes($client_lastname);
$client_address = stripslashes($client_address);
$client_surburb = stripslashes($client_address);
$client_postcode = stripslashes($client_postcode);
$client_ph = stripslashes($client_ph);
$client_emailaddress = stripslashes($client_emailaddress);
$client_secretquestion = stripslashes($client_secretquestion);
$client_secretanswer = stripslashes($client_secretanswer);
// -> mysql_real_escape_string
$client_username = mysql_real_escape_string($client_username);
$client_password = mysql_real_escape_string($client_password);
$client_displayname = mysql_real_escape_string($client_displayname);
$client_firstname = mysql_real_escape_string($client_firstname);
$client_lastname = mysql_real_escape_string($client_lastname);
$client_address = mysql_real_escape_string($client_address);
$client_surburb = mysql_real_escape_string($client_surburb);
$client_postcode = mysql_real_escape_string($client_postcode);
$client_ph = mysql_real_escape_string($client_ph);
$client_emailaddress = mysql_real_escape_string($client_emailaddress);
$client_secretquestion = mysql_real_escape_string($client_secretquestion);
$client_secretanswer = mysql_real_escape_string($client_secretanswer);
// Sql Query
$sql=”SELECT * FROM clients WHERE Client_UserName=’$client_username’ and Client_Password=’$client_password’ and Client_emailaddress=’$client_emailaddress’”;
$result = mysql_query($sql);
// Mysql_num_row is couting the table row
$count=mysql_num_rows($result);
// if results match, table row must be 1 row or so.
if($count==1){
//If theres a match
echo “Hello $client_username”;
}
else{
echo “Wrong username or Password.”;
}
if (!mysql_query($sql,$con))
{
die(‘Error: ‘ . mysql_error());
}
// Close MySQL Connection
mysql_close($con)
?>
When building a new site, I like to use a framework I was taught, which is a bit of a play on the whole MVC foundation. One class I use, I call the “Path Class.” It’s simply an array of paths to pages, directories, pictures, scripts, etc all across the site, like so:
$paths = array ( ‘homePage’ => ‘index.php’, ‘aboutPage’ => ‘about/index.php’ );
Just the usual ‘key’ => ‘value’ structure, except much longer, even for a small site. From this point, two helper functions can be called, anywhere the path class is being used: getPath(string x); and getWebPath(string x);
These two functions will take the string passed in and PREPEND ‘/var/www/siteDir/’ or ‘http://www.yoursite.com/‘ to it, allowing it to return the URL or directory path of anything in the site. getPath() is used mostly for file includes and getWebPath() is perfect for IMG SRC’s, HREF’s, or just general links.
It seems like a lot of work for just that, but the beauty comes when you move a page, or change servers. All you have to do is edit the proper entries in the Path Class, and all the links across your entire site will change. You’re welcome =)
When you’re ready to go live, set your error reporting to 0.
error_reporting(0);
This book is right for me.
It may seem obvious, but as a beginner, the most useful thing for me was the official PHP documentation (http://www.php.net/manual/en/). It is well-written, thorough and almost all of the comments are insightful and helpful in some way. That’s hard to come by for most programming languages, and I think a lot of people tend to take it for granted.
The best way to learn PHP, indeed any language, is by using it for real-world applications.
Find an app you like, or a CMS style, or a even simple login system, and try and replicate it.
This forces you to think about the design of a complex system, application of language specific techniques, and about the myriad of insanely useful functions built into PHP.
This is the same with any language, API or library. Use it. jQuery to C++, you have to build stuff.
Use descriptive names for everything!
One thing that i’ve learned the most is how much it sucks to come back to code and not knowing how it works (even if I wrote good comments).
Take this for example.
$d_r_uinfo;
At the time of writing that, I could be farily confident that its a Database Result of User Info.
Coming back a few months later, I would have no idea what the “d” and the “r ” stand for.
Instead if I wrote it like this:
$databaseResultUserInfo;
Its obvious from the name exactly what the variable contains.
This same principle applies to function names and class names too. If its not obvious right away what the function or class does, rename it.
Another thing that helped me was to choose a naming convention and stick too it.
For a while I was using the _ character to separate words (ex: the_variable_name), But I later chose to use the CamelCase naming convention. There are a couple tricks you can use with this one to help you keep track of what is what.
If you are naming a variable or a function, start the first word as lowercase and every subsequent word starts as uppercase.
$myVariableName;
myFunctionName();
For class names, every word starts uppercase.
MyClassName
This way quickly see the difference between a regular function and a class.
Hope this helps, it definitely helped me keep things straight while I was learning.
Create a constant for your most used paths. ie
define(‘DOC_ROOT’,'/var/www/htdocs/’)
define(‘IMG_DIR’, DOC_ROOT . ‘/images/’);
Then when spitting out an image in your markup, instead of
src=”/var/www/htdocs/images/test.gif”
you could do this:
test.gif
and of course, when your images move, the path still works when you update your constant :)
lol – this is the most resourceful comment thread ever!
lets try that again…
<=IMG_DIR;?>test.gif
While not quite a PHP tip itself, as a PHP developer, I have found this extremely useful. If you are working with a PHP function that you are either unfamiliar with, or need a reminder for its purpose or syntax, you can get a quick reference by pointing your browser to http://php.net and adding a slash function name.
http://php.net/date
php.net will rewrite your URI to match their server and provide the reference on that particular function. This saves digging through the content list to find that quick reference that you need to continue on your way.
Grab a good book on PHP, install a local server on your PC/Mac, and experiment.
Once you’ve mastered the basics, don’t be afraid to recycle code, build yourself custom classes that will be useful in multiple projects and incorporate them, reinventing the wheel is useless.
Don’t be afraid to learn a framework like CodeIgniter–they can get a lot done!
And finally: ask for help when you get stuck! Jeffery Way is very good at replying to questions either directly or in tutorial form, and find a local guru, they’re out there!
You don’t want to preinvent the wheel, working with library’s is way easier and faster!
I use a MVC PHP library in combination with Smarty template engine so all of my code
is sepeterate and very organised. Makes working with multiple colleagues a lot easier!
I often need to shorten text so i created my function for this:
function ShortenText($str, $max=30, $rep = ”) {
if(strlen($str) > $max) {
$leave = $max – strlen($rep);
return substr_replace($str, $rep, $leave);
} else {
return $str;
}
}
as you will see its quite flexible, it allows you to change the length and what you want the result to be concatenated with.
When you want to print HTML code from PHP you can use the heredoc syntax for echo function, which allows yo to write the plain HTML, just like that:
<?php
echo <<<EOF
EOF;
?>
Greetings to all!
Use commas to concatenate echo strings instead of periods as it’s faster.
Example
echo ‘Hello ‘ , $yourname , ‘! Welcome back’;
PHP is simple and you can learn it just take action and never stop to learn
The most important tip is to go slow and practice each step. i was in many classes where i went too fast in the beginning wanting to get to the “cool” stuff only to realize that i was missing foundational knowledge.
Tip (don’t laugh): If you’re dumb enough to get sucked in (EVER) to programming something nasty with nested upon nested HTML frames and you’re having trouble passing simple variables – the tip is that you need to pass the variables through the frames. While it’s not obvious as such… it can be the difference between shooting yourself and just being sorry your Computer Science professor put that into an assignment as a practical joke (aka test).
Tip #2: Never do this unless you have been instructed by a computer science professor.
When coding ensure that your code is neat and tidy.
Ensure that you comment on all aspects of your code, this will come in useful later on. When doing functions, indent them, they are easier to diagnose if something goes wrong.
When coding in JavaScript, if you get stuck, use ‘alert($variable)’, it will help you get an insight into what is happening with your code.
If you get completely stuck, remember, Google is your friend.
Another tip: Always sanitize your data going in and going out… you can never be too careful or too persnickety about the quality of data.
When I was starting with PHP, as a way of debugging my code when working with arrays, I was using something like this:
echo “”;
print_r($myArray);
echo “”;
Another thing would be utilizing very useful funtcions: 1) serialize http://php.net/serialize and 2) unserialize http://php.net/unserialize – it saved me a lot of time, many times.
WP is eating up my code. In both echos, between double quotes, should be PRE tags (opening in first and closing in the second).
You can use PHP to build dynamic CSS files by adding this line to the top of a php file:
header(‘Content-Type: text/css; charset: UTF-8′);
Then just make sure the file outputs valid css code.
Then in your html page, just link to the php file like you’re linking a stylesheet.
<link href=”pathToPHPFile” rel=”stylesheet” type=”text/css” media=”print” />
While not specific to PHP, a text entry application like TextExpander can make your life a lot easier.
If you have to print long blocks of html or etc it is better to do as following;
$text=<<<EOF
blablabla
$someData
blablabla
EOF;
here’s a goodie:
/* Strip CDATA from a given String */
function strip_cdata($string){
preg_match_all(‘//is’, $string, $matches);
return str_replace($matches[0], $matches[1], $string);
}
another tip.. or helper function:
/* Most effective way to clean a String */
function cleanString($string) {
$detagged = strip_tags($string);
if(get_magic_quotes_gpc()) {
$stripped = stripslashes($detagged);
$escaped = mysql_real_escape_string($stripped);
} else {
$escaped = mysql_real_escape_string($detagged);
}
return $escaped;
}
:) have fun!
Why would you award someone who supplies a good PHP tip with a beginner PHP book?
However I am glad that Jason Lengstorf was kind enough to give copies to tuts to hand out.
Tip:
PHP is an interpreted language which can cause a great deal of confusion for programmers with a background in compiled languages. When I was learning PHP, I found myself commenting the type of variables near declarations or some usage to provide myself with strict typing which I was use to.
Tip #2:
Use echo statements sparsely. Its better to concatenate an output value rather than flood your code with echo statements which are resource intensive (or at least that was the case for a large PHP application that I had worked).
Sorry if my tips are old, haven’t touched PHP in a while now.
HI,
Relating back to the other post about OOP for beginners, global getters and setters can really speed up access and build time.
private $user = array( ‘id’ => ”,
‘unique_id’ => ”,
‘first_name’ => ”,
‘last_name’ => ”,
‘name’ => ”,
‘email’ => ”,
‘address’ => ”,
‘city’ => ”,
‘state’ => ”,
‘postcode’ => ”,
‘country’ => ”,
‘phone’ => ”,
‘mobile’ => ”,
‘username’ => ”,
‘password’ =>”,
‘status’ => ”,
‘type’ => 0,
‘session’ => ”,
‘init’ => 0,
public function __set($key,$val){
if (array_key_exists($key,$this->user)){
$this->user[$key] = $val;
}
}
public function __get($key){
if (array_key_exists($key,$this->user)){
return $this->user[$key];
}
}
Enjoy :)
If you’re ever using multi-dimensional arrays then this is a handy function to search through them…
// Function to array_search multi-dimensional arrays
function multiarray_search($array, $key, $val){
while(isset($array[key($array)])){
if($array[key($array)][$key] == $val){
return key($array);
}
next($array);
}
return -1;
}
Besides it’s been hashly argued on many communities, I still follow this rule;
do not use double quotes, when you don’t need them, as we can see:
print “Hello ” . “world”;
But this is faster: (single quotes instead of double ones)
print ‘Hello ‘ . ‘world’;
And this, is even faster: (echo instead of print)
echo ‘Hello ‘ . ‘world’;
Yet, even faster: (comma instead of period)
echo ‘Hello ‘, ‘world’;
Just note that replacing period with comma only works with “echo” because this function accept n arguments, like parts of the final string.
One isolated case makes no difference, but when you have in your whole web application, almost a thousand outputs, enabling output buffer and making the corrections I mentioned above could save a lot of response delay.
This code will output any posted content and is great for bug testing.
<?php
echo "”;
print_r($_POST);
echo “”;
?>
Dangit! No Preview and auto scrubbing of html tags. That makes things difficult.
Those echoes should contain opening and closing PRE tags. \ \
What helped me with php? My tip don’t be afraid of the php online manual, and be sure to come here often :)
How about a word limiter :)
function word_limiter($str, $limit = 100, $end_char = ‘…’)
{
if (trim($str) == ”)
{
return $str;
}
preg_match(‘/^\s*+(?:\S++\s*+){1,’.(int) $limit.’}/’, $str, $matches);
if (strlen($str) == strlen($matches[0]))
{
$end_char = ”;
}
return rtrim($matches[0]).$end_char;
}
* Learn to utilize built-in PHP functions to build calendar tools and photo galleries.
* Learn how jQuery can be used for Ajax, animation, client-side validation, and more.
* Learn jQuery UI and how to create drag-and-drop features easily.
This book looks like have great articles that can help me energize my OS CMS and take it to next level competing with others out there.
Keep reusable chunks of code in seperate files that can later be easily included in your projects. Since I do a lot of work creating custom WordPress set-ups, I will use code similar to the following in my functions.php to include these chunks.
define(‘Library’, TEMPLATEPATH . ‘/library’);
// Load additional functions
require_once(Library . ‘/releases.php’);
require_once(Library . ‘/events.php’);
require_once(Library . ‘/featured-songs.php’);
Why is the UK amazon price roughly double the price of the US amazon price?
Instead of using code like:
if (!defined('BASEPATH') { die('LOL!'); }To exit file which you only want to include, why not use:
if (!defined('BASEPATH') { return; }This allows the file which makes the request have control if it fails, and also.. You don’t get a nasty die or exit text!
always visit net.tutsplus.com
function pretty($someArray){
echo '';
print_r($someArray);
echo '';
}
I typed pre tags between echo quotes.
the PHP withe the ease of codeigniter library is the best in my opinion.
load->helper(array(‘form’, ‘url’));
$this->load->library(‘form_validation’);
$this->form_validation->set_rules(‘username’, ‘Username’, ‘required’);
$this->form_validation->set_rules(‘password’, ‘Password’, ‘required’);
$this->form_validation->set_rules(‘passconf’, ‘Password Confirmation’, ‘required’);
$this->form_validation->set_rules(‘email’, ‘Email’, ‘required’);
if ($this->form_validation->run() == FALSE)
{
$this->load->view(‘myform’);
}
else
{
$this->load->view(‘formsuccess’);
}
}
}
?>
I am more of a front end developer who is trying to learn more about WordPress/PHP/jQuery so my tip is probably not nearly as good as most developer’s here. I am learning PHP on the go through wordpress themeing and plugins so basically if you’re new try learning more about wordpress than just skinning. Hope that helps other novices like myself.
This may be cheating but the best thing I did to learn PHP was plan out everything I wanted in my site then worry about learning to code it. During that trial and error you will create a bunch of sloppy and redundant code, but that is ok when you’re learning.
Also a quick and easy email checker
Granted I know this isn’t the most perfect method, but it gets the job done for something as simple as a newsletter subscription. Its still possible to beat it, but why would anyone wanting to subscribe throw a fake email on purpose?
$emailcheck = explode(“@”, $_POST['email']);
$domaincheck = explode(“.”, $emailcheck[1]);
if ((strlen($emailcheck[0]) >=1 && strlen($emailcheck[1]) >=1 && !isset($emailcheck[2])) && (isset($domaincheck[0]) && isset($domaincheck[1]) {
//Continue with php code dependent on valid email
} else {
// Throw Error asking for email address
}
As a web designer every one needs Pro PHP and jQuery book, hoped I have it too :)
PHP redirects is the first thing I learned :P
Are you getting an error for a reason that escapes all logic??
Your probably missing a F#%$ING semi-colon.
I love your idea of sharing a PHP tip to enter to win!
Here’s my tip:
What helped me to learn PHP the most?
Drupal. Seriously. The community there is great as well as the extensive functionality through modules. Once I got a grasp on the PHP language (my favorite points of learning and reference are http://www.php.net/ , http://www.w3schools.com/PHP/ , and net.tutsplus.com of course), Drupal helped inspire me to keep learning with all the possibilities (without shelling out lots of $$, since it’s opensource, and without spending lots of time to “reinvent the wheel” so to speak) I know CodeIgnitor and CakePHP are great ways to avoid reinventing the wheel as well, but check out Drupal. I’ve experienced people there on the forums to be helpful as well, as long as you’re appreciative of all the work they do. Check out http://www.drupal.com and http://www.drupal.org (PS- wordpress is great too! see http://www.wordpress.org).
Also another quick tip- I’d say MOST of my PHP errors are a result of:
- a missing ; on some line
- a missing closing ) or }
- an un-escaped ” or ‘ within a string or variable or EOT
- sometimes even extra white space at the beginning or end of a PHP document – e.g. before MAKE SURE there are NO characters there, not even line breaks or spaces. This is especially (and usually only) a possible occurrence with more complicated PHP software like Drupal or WordPress.
Thanks for the opportunity!
The best way to get your hands dirty stress free and allow smooth transition from DEV to LIVE is download and install XAMPP. It has helped me enormously when learning how to change the likes of .htaccess, php.ini and code functionality without ever worrying im going to break something. I’d love a copy of this book, good luck everyone.
Regards