Fork me on GitHub
RSS
 

Top 10 PHP Tips, Functions and Techniques You Need to Know

19 Oct

This is a rundown of my top 10 PHP functions and techniques that I use on a daily basis (pretty-much) and thought I’d share them with you. Hopefully there’s some gems in there that you have never heard of (or used), that will change the way you code.

#10 – print_r()

print_r() is probably my most used function. This allows you to recursively print an array, multi-dimensional array or even an object. It’s great for getting a useful visual representation of one of the aforementioned data types. Here’s a quick example:

$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);

Will print:

Array
(
    [a] => apple
    [b] => banana
     => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)

I find this immensely useful for debugging arrays, so I think you’ll find this one of those top tips you keep coming back to. You can pass a second boolean parameter if you just need to return the result of print_r to a variable. This is useful for sending debug data in emails and things like that.

#9 – Variable variables (double-dollar $$)

This is a good little tip – Imagine you had a variable called $fruit, declared like the following:

$fruit = "apple";

Now what if we wanted to use the value of the variable $fruit to create a new variable, which is named as the value – we’d simply use:

$$fruit = "juicy";

This has now created two variables:

$fruit = "apple";
$apple = "juicy";

What this has done, is shown us how to create a variable variable. The basic thing to note with variable variables (double dollar / $$) is that we can create a variable which is named as per the value of another variable.

#8 – Ternary Operators

Ternary operators are a cleaner way of doing an if … else statement. Look at the following example, and I’ll explain it below:

echo ($myBoolean) ? 'True' : 'False';

We could write this as:

if($myBoolean){
  echo 'True';
}else{
  echo 'False';
}

But as you can see, it’s much cleaner. What happens is we have a test case, then what happens if it’s true, then what happens if it’s false:

(TESTCASE) ? TRUE_ACTION : FALSE_ACTION;

You can “chain” ternary operators, take a look at the one from the PHP documentation:

echo (true?'true':false?'t':'f');

Which outputs ‘t’. It does this, because the statement is evaluated from left to right – so in the above example, we have true, which makes the first ternary operator return true, so the second part (after the second question mark) returns the true part ‘t’.

#7 – glob()

Glob is my preferred method for listing files within a directory (as opposed to readdir(), and other long-winded methods). It’s great for getting a list of images (for example) within a directory. To do this, you would use something like:

$images = glob("/path/to/images/*.{jpg,gif,png}", GLOB_BRACE);

Which would return an array of images (with their path names). We’re using GLOB_BRACE here, which allows us to use a braced expression – {jpg,gif,png} – so glob will search for all files ending with either of those extensions. A much more simple glob example would be as follows:

$phpFiles = glob("*.php");

Which would return an array of php files, and stick the array into the $phpFiles variable.

#6 – json_encode()

I use this function for two main things. Firstly, if I’m doing an AJAX call, I use this to return a JSON object back to the calling JavaScript as it’s a nice, clean way of accessing objectified data. Secondly, and much less commonly, I use this function over PHP’s serialize() function, to store an array of data, or even an object, in a database table.

You can simple pass any value (except a resource) to be encoded. I generally just use arrays, or objects. The example (which is more than suffice) I’ll us, is the one from the PHP documentation:

$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);

Which gives us:

{"a":1,"b":2,"c":3,"d":4,"e":5}

#5 – ob_gzhandler()

Thanks to using Google’s page speed analyzer – I now use ob_gzhandler() at the start of all of my pages. I usually include this in a header config file, so that it naturally gets included across the entire site. What this does is it checks to see if the requesting browser supports gz encoded data, and if it does, it will compress the entire page and push a much smaller file to the browser, therefore helping to speed up your pages. You simply just need to call the following, and it works automagically:

ob_start("ob_gzhandler");

#4 – mysql_real_escape_string()

There’s a good chance that you might already know this one – but if you don’t, you really should. This function will ensure that any variables passed into your queries for execution against a MySQL database are safe. An example of how to use this would be:

$query = 'SELECT * FROM customers WHERE name = "' . mysql_real_escape_string($name) . '"';
mysql_query($query);

Generally speaking, $name will be safe (i.e. not have any nasty SQL injections in) but if this was a user-submitted form, and the user was malicious – they might enter something like ” OR 1=1– which is a MySQL injection string. Without using mysql_real_escape_string() – our query would look like:

SELECT * FROM customers WHERE name = "" OR 1=1--;

Which would get all results, as we’re using an OR clause that will always return true. The double dash just tells MySQL to ignore everything after it (same as a comment in PHP really). This could be potentially used to get all sorts of data from a database. So, use mysql_real_escape_string() and you can sleep at night, in the knowledge that some uber leet skript kiddie won’t be gaining access through your tables!

#3 – Forcing File Downloads

Sometimes, it’s much nicer to have your users download a file, rather than simply display it on the page. For example, let’s say we have an image gallery which allows users to purchase selected images. When they purchase, it would be nicer to provide them with a download dialog box, rather than display the image and expect them to right-click save-as. To do this, you’d simply use:

header("Content-type: application/octet-stream");
header("Content-Length: " . filesize('image.jpg'));
header('Content-Disposition: attachment; filename="image.jpg"');
readfile('image.jpg');

Replace ‘image.jpg’ with the file you wish to allow them to download. It’s important to note, here, that you should not send any other output to the browser – as this will mess the headers up. You can run extra PHP bits and bobs (such as logging how many times the image has been downloaded etc…). I generally put this code into it’s own file, named something like download.php and link to it from a gallery.

Protip! You can force downloads of any type of file, not just images.

#2 – Sorting a Multidimensional Array

Sorting standard, or singular-dimensional arrays is simple business. If you have an array like so:

$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

You can use asort to sort by the values of the array:

asort($fruits);

Which would give you a nicely sorted array like so:

c = apple
b = banana
d = lemon
a = orange

But what if we had a multi-dimensional array? Let’s take the following array for this example:

$students[0]['name'] 	= 'Ed Rackham';
$students[0]['age'] 	= 25;

$students[1]['name'] 	= 'Joe Rackham';
$students[1]['age'] 	= 27;

$students[2]['name'] 	= 'Sarah Cockburn';
$students[2]['age'] 	= 25;

$students[3]['name'] 	= 'Luke Newnham';
$students[3]['age'] 	= 25;

$students[4]['name'] 	= 'Mart Dingley';
$students[4]['age'] 	= 28;

$students[5]['name'] 	= 'Skript Kiddie';
$students[5]['age'] 	= 16;

If we run a print_r() on our $students array, we will get the following:

Array
(
    [0] => Array
        (
            [name] => Ed Rackham
            [age] => 25
        )

    [1] => Array
        (
            [name] => Joe Rackham
            [age] => 27
        )

    [2] => Array
        (
            [name] => Sarah Cockburn
            [age] => 25
        )

    [3] => Array
        (
            [name] => Luke Newnham
            [age] => 25
        )

    [4] => Array
        (
            [name] => Mart Dingley
            [age] => 28
        )

    [5] => Array
        (
            [name] => Skript Kiddie
            [age] => 16
        )
)

But what if we wanted to sort the array based on the age of the student? Well, we’d simply use usort which allows us to sort an array by values using a custom sorting function – in this example our custom sorting function is called customSort. Firstly, we need to add our custom sorting function, which is really simple – it looks like the following:

function customSort($a, $b){
	return strcmp($a['age'], $b['age']);
}

Which, as you can see returns the result of strcmp based on array[DIMENSION] by array[DIMENSION]. We want to sort by the ‘age’ dimension, so we simply sort by this array dimension. We could use a variable here to make this custom sorting function a little more flexible.

Next, we need to add the usort() function after we have declared our array, so we can actually sort it:

usort($students, 'customSort'); 

This takes two parameters, our array we want to sort, and the name of the custom sorting function that we want to use for the sorting. Once we have run this, we can do a print_r() on our array and we now get the following:

Array
(
    [0] => Array
        (
            [name] => Skript Kiddie
            [age] => 16
        )

    [1] => Array
        (
            [name] => Luke Newnham
            [age] => 25
        )

    [2] => Array
        (
            [name] => Sarah Cockburn
            [age] => 25
        )

    [3] => Array
        (
            [name] => Ed Rackham
            [age] => 25
        )

    [4] => Array
        (
            [name] => Joe Rackham
            [age] => 27
        )

    [5] => Array
        (
            [name] => Mart Dingley
            [age] => 28
        )
)

Awesome hey? There’s so many uses for this, and I’m sure – during your PHP careers – you’ll find many uses for this bad boy.

#1 – Require, Include and _once

Finally, you probably already use one of the following as you code your PHP scripts:

  • include()
  • require()
  • include_once()
  • require_once()

But do you know the difference? The differences are important, so let me explain:

  • include() will attempt to include the file, but if it fails PHP will just produce a warning, and continue to execute the script (as best it can) regardless. This is safer if you nonchalantly include files regardless of whether they are actually needed / exist.
  • require() will attempt to include the file, but fail with a fatal error should it have a problem when trying to get the file. I like this method, as the PHP will stop executing immediately and bug out if the file is not loaded correctly (for whatever reason).
  • include_once() / require_once() you should really try to avoid using. The benefits of using the _once method is that you know, for sure, that you’re not including the same file twice. However – this is much much slower than just writing semantic code and not relying on the fact you might have included the file more than once.

Basically, using require() is probably the best practise, as it is faster than the _once methods, and you should be writing clean, semantic, code these days that don’t rely on PHP fallbacks such as include().

 
26 Comments

Posted in PHP

 

Leave a Reply

 

 
  1. Feras

    November 1, 2010 at 11:03 am

    great tips

     
  2. Dave

    November 18, 2010 at 8:34 am

    Good list, I use print_r many times a day very useful.

    Ternary Operators may look cleaner but it’s also not as clear where one segment of code ends and another begins if using a few of these together in my opinion.

     
  3. KRO

    December 28, 2010 at 1:56 pm

    thanks, ternary operators – its something you want to know but dont know the name of to search for ! thx

     
  4. Robin

    December 31, 2010 at 10:35 am

    Nice tips, especially the ternary operators and variably variables will be usefull too.

     
  5. kamran

    January 25, 2011 at 7:16 am

    great tips thanks

     
  6. mp3lemon

    January 29, 2011 at 1:44 am

    .Hopefully there’s some gems in there that you have never heard of (or used), that will change the way you code?

     
  7. csabi

    February 2, 2011 at 1:33 pm

    Hi! You have lot`s of great tutorials!
    Congratulations!
    I`we just started a tutorial indexing website and I would like to ask you to submit some tutorials :D
    You can submit tutorials without registering, but if you register you will get gift points for each tutorial and you can use these points to buy ads.

    Please visit it: http://www.tutorialswindow.com
    Thanks

     
  8. David

    April 18, 2011 at 6:35 pm

    To complete your list: sometimes var_dump is a good alternative to print_r .

    Thanks for sharing.

     
  9. Priatm

    June 16, 2011 at 6:18 am

    thnx for help me…thnk u very much

     
  10. Bogdan

    August 19, 2011 at 11:46 am

    Very nice tips.

    Instead of using mysql_real_escape_string($string)
    you could use addslashes($string) , so the ‘malicious users’
    couldn’t make you any problems….

    Thank for sharing ..

     
  11. Deepak

    September 6, 2012 at 5:04 am

    Nice Article. Very recently started learning PHP (I’m a .NET guy otherwise) and found this consolidated 10 points quite panoptic view of PHP .

     
  12. hermes s singapore

    May 26, 2013 at 12:08 pm

    Your article Top 10 PHP Tips, Functions and Techniques You Need to Know | edrackham write very well, thank you share!

     
  13. find out more

    December 1, 2013 at 8:54 pm

    We are a gaggle of volunteers and starting a
    brand new scheme in our community. Your web site offered us with helpful info to work on.
    You’ve done a formidable process and our whole group will
    be thankful to you.

     
  14. best exercise for removing cellulite

    December 6, 2013 at 7:38 pm

    I need to to thank you for this very good read!!
    I absolutely loved every bit of it. I have got you book
    marked to check out new stuff you post…

     
  15. Leigh

    December 7, 2013 at 12:20 am

    Hello there I am so excitged I found your site, I really
    found you by mistake, while I was searching on Google for sometthing
    else, Regardless I am here noow and would juat like to say thanks a lot
    for a fantastic post and a all roound thrilling blog (I also love
    the theme/design), I don’t have time to read through it all
    at the minute but I have book-marked it and also included your RSS feeds,
    so when I have time I will be back to read a great deal
    more, Please do keep up the superb job.

     
  16. instagram followers free

    December 9, 2013 at 2:38 pm

    Intagram Followers! Instagram has above one hundred Million users, which is naturally a lot!
    Now don’t you wish that a number of countless numbers of the a hundred+ Million users would stick to you??
    It cant be that tough to accomplish this contemplating the mass quantity of users that use Instagram.

    That’s why I am teaching you all how to get
    limitless Instagram followers! I have created this exclusive device
    which will permit you to obtain a mass quantity of followers in a limited amount of time.

    I will be offering this to the community out there for everyone to use!!
    To get your Instagram Followers, you will need to have to obtain the system from the
    link underneath (virus scan is offered underneath)
    As soon as you have downloaded it, you will just need to have to follow the short tutorial I have made below!

    After you have carried out that, you will be 1 action closer to obtaining 1000′s of Followers!!

     
  17. Chelsea

    December 9, 2013 at 7:44 pm

    Hello there, just became aware of your blog through Google, and found that it’s really informative.
    I’m gonna watch out for brussels. I will appreciate if you continue this in
    future. Lots of people will be beenefited from your writing.
    Cheers!

     
  18. how to get free instagram followers

    December 10, 2013 at 7:17 pm

    Intagram Followers! Instagram has more than 100 Million consumers, which is naturally a whole
    lot! Now don’t you wish that a couple of thousands of the 100+ Million
    users would comply with you?? It cant be that tough to accomplish this taking into consideration the mass sum of end users that use Instagram.

    That’s why I am instructing you all how to get unrestricted Instagram followers!
    I have developed this distinctive device which will enable you to get a mass quantity of followers in a
    short volume of time.

    I will be giving this to the community out there for every person to use!!
    To get your Instagram Followers, you will need to download the program from the website link underneath
    (virus scan is provided below)
    Once you have downloaded it, you will just require to stick to the quick tutorial
    I have created beneath!
    After you have done that, you will be 1 stage
    closer to receiving Hundreds of Followers!!

     
  19. smoothie recipes nutrition

    January 20, 2014 at 3:42 pm

    Water often is used as a base for your favourite low carb smoothie; it owns the minimum
    amount of carbs of most -infact zero. ‘ Natural cleanser;
    blood, colon; strengthens gall bladder and liver.
    They keep the immune system healthy and strong as they ward off infections and
    heal cuts and wounds.

     
  20. Henri

    February 8, 2014 at 3:00 am

    hi nice blog! follow me plz: http://instagram.com/gr4bb3n

     
  21. age reviver with ginkgo biloba

    February 20, 2014 at 9:38 am

    There is certainly a great deal to know about this
    issue. I really like all the points you made.

     
  22. пиреос банк кредити

    March 3, 2014 at 5:36 am

    Бързи заеми и всички видове бързи кредити
    Сайт за бързи заеми и потребителски кредити в България
    Пари назаем до 24 часа с бърз кредит
    В този уеб сайт ще намерите списък на фирми предлагащи бърз заем,
    в които получавате парите до 24 часа, предложения
    за бърз потребителски кредит над 399 лв,
    както и актуални промоции , списък с офисите
    на компаниите по градове, микрокредити за малкия бизнес,
    удобен филтър за бързо намиране на най-добрата оферта,
    калкулатор, услуги с изцяло онлайн процес за кандидатстване и взимане на парите, полезна информация.

     
  23. free converter

    March 6, 2014 at 5:17 am

    My programmer is trying to persuade mee to move too
    .net from PHP. I have always disliked the idea because of tthe expenses.
    But he’s tryiong none the less. I’ve been using WordPress on a variety of websites
    for about a year and am anxious about witching to another platform.
    I have heard great things about blogengine.net.
    Is there a way I can import all my wordpress content into it?
    Any kind of help would be greatly appreciated!

     
  24. Gangstar vegas Hack

    March 24, 2014 at 3:25 pm

    Howdy! I could have sworn I’ve been to this website
    before but after reading through some of the post I realized it’s new to me.
    Anyhow, I’m definitely glad I found it and I’ll be book-marking and checking back often!

     
  25. abubasil

    April 18, 2014 at 4:08 pm

    very useful tips, thank you for this.
    I think this
    usort($students, ‘customSort’);

    should be

    usort($students, customSort());

     
  26. http://www.23hq.com/hortonweis/story/15578153

    April 18, 2014 at 8:58 pm

    Thank you for the auspicious writeup. It in reality was once a amusement account it.
    Look complex to more introduced agreeable from you!
    By the way, how can we communicate?