46 useful PHP code Snippets that can help you with your PHP projects

46 PHP Code Snippets

Its always good to have a magic hat while writing code. Below I have compiled 40+ PHP code snippets that can help you with your PHP Projects.

These PHP code snippets can come handy even if you are just beginning to learn PHP. So, let’s get started.

1. Sending sms

While working on web or mobile applications, you often face a situation where you need to send an SMS to your user either for login purposes or providing them with some information. The below PHP function would help you with it.

For sending SMS using any language, you’d need an SMS gateway. Most of the SMS providers these days provide with an API. For the below PHP snippet, I am using MSG91 as SMS gateway.

You’d see that I have highlighted two lines. On the first highlighted line you need to enter your passkey and on the second you need to enter your senderID. While entering mobile number you need to specify the country code (For example, USA’s country code is 1. India’s country code is 91).

Syntax:

2. SENDIng email WITH mandrill

Mandrill is a powerful SMTP provider. Developers tend to use a third party SMTP provider for better inbox deliveries.

For the below function you would have to put a file “Mandrill.php” in the same folder as the PHP file you would be using to send emails.

In the above code you would have to specify your own api key that you get from your Mandrill account.

Syntax

For best deliveries, I would recommend you to configure DNS settings as guided by Mandrill.

3. PHP function to help prevent sql injection

SQL injection or SQLi is a common technique used to hack into a website. Using the below code can help you prevent it.

Syntax

Had we not used the clean function above, the page would have popped up an alert box.

4. detect location of the user

Using the below function you can check the city from which the user is visiting your website.

Syntax

5. get the source code of a webpage

Using the function below you would be able to get the HTML code of any webpage.

Syntax

6. show number of people who have liked YOUR facebook page

Syntax

7. determine dominant color of any image

8. whois query

Using the below function you would be able to get complete details regarding the owner of any domain.

Syntax

9. validate email address

Sometimes, while filling forms on your website, a user can mistype his email address. Using the below function you can check if the email provided by user is in correct format.

Syntax

10. get real ip address of user

Syntax

11. Convert url in a string to hyperlinks

If you are working with forums, blogs or even a normal form submission, many times you end us asking user for a website. Using the function, the URL string would automatically convert to a hyperlink.

Syntax

12. block multiple ip from accessing your website

This snippet can come in handy if you want to restrict your website from a certain location or from certain users.

13. forceful downloading of file

If you want certain files to download instead of opening in new tab, you can use the below snippet.

Syntax

14. CREATING json data

Using below PHP snippet you can create JSON data. This will come handy when you are creating web services for mobile apps.

15. zipping a file

Using the below PHP snippet you would be able to zip files instantly.

Syntax

16. unzipping a file

Using the below PHP snippet you would be able to unzip a file on the fly.

Syntax

17. php snippet to resize image

Sometimes client can upload a large image and you might want to resize it. Below PHP snippet would enable you to do that.

18. send email using mail()

Above we have discussed how you can send email using Mandrill, but in case you do not want to use a third party service, you can use the below snippet.

Syntax

19. CONVERT seconds to days, hours and minutes

Syntax

20. php code snippet for database connection

To store data, you would need a database. In this case we would be using MySQL database.

In the highlighted lines above, you would have to specify your own server database details.

You can save the above file as config.php and you would have to include that file in all pages where you need database connectivity.

21. php snippet for directory listing

Using the below PHP code snippet you would be able to list all files and folders in a directory.

Syntax

22. detect USER language

Using the below PHP snippet you would be able to detect the language of your user’s browser.

23. reading a csv file

Syntax

24. creating a csv file from php array

Syntax

25. parsing xml data

Below PHP snippet will help you explain how you can parse XML data in PHP.

26. PARSING JSON DATA

27. get current page url

This PHP snippet comes handy when post login you have to redirect user to the same page which he was browsing earlier.

Syntax

28. get latest tweet from ANY twitter account

Syntax

29. number of retweets

Using this PHP snippet you can check the number of times your page URL was retweeted.

Syntax

30. calculate difference in 2 dates

31. php snippet to delete a folder with content

Syntax

32. search and highlight keywords in a string

It becomes convenient for user, when he searches something and in the result he can see his keyword highlighted.

Syntax

33. php snippet to write to a file

34. download image from url

Most of the websites now give you an option to either upload image or download it from a URL. Ever wondered how they copy that image from that URL? Here is how

Syntax

35. check if a url is valid

Syntax

36. generate qr code

Syntax

37. calculate distance between two map coordinates

Syntax

38. get all tweets of a specific hashtag

39. Add th,st,nd or rd to the end of a number

Friday the 13th

Syntax

40. file download with speed limit

If you are planning to create a file sharing website then you would already know that bandwidth is the key. Here is how you can limit the speed at which the file will download.

41. convert text to image

42. get remote file size

Syntax

43. pdf to image converter with imagebrick

44. URL SHORTENER using tinyurl

Syntax

45. youtube download link generator

Using the below PHP snippet you can offer your users the ability to download youtube videos.

46. Facebook style timestamp

Ever noticed how your post/comment time is shown on Facebook (x mins age, y hours ago etc). Below is a simple PHP snippet which you can use that will do the same thing.

Syntax

 

This completes my first blog post. Most of the PHP snippets that I have mentioned above are not mine. I have gathered them over years hence I am unable to add proper credits.

These snippets can help you save a lot of time while you get down to code something amazing.

You can download the entire post with the codes here:

This is my first blog post here. Took me a few hours to compile. Hope you guys would like it.

Do comment below and let me know if you liked(or disliked) my first post. Comments and suggestions are welcome. Let me know how you feel about this post by tweeting to @TheMohitMadan

Signing off.

Mohit Madan

GET YOUR EMAIL UPDATES

We send out our lovely email newsletter with useful tips and techniques, recent articles and upcoming events. Thousands of readers have signed up already. Get a free WordPress eBook now.
Name
Email
  • Thanks for sharing! (y) It will be really useful to so many developers!! Best part of this post is, you can get almost everything at one place.

    Keep sharing!! Greatly appreciated! (y)

    • Mohit Madan

      Thank you for your kind words. 🙂

  • Muhammad Rizwan

    Really Helpful, Although some of snippets are not yours but u have collected nice snippets and put them together in a single place..That’s also a great work….Nice

    • Mohit Madan

      Thank you. I have mentioned in the post that some snippets are not mine. 🙂

  • Kishor Jacob

    Awesome…really helpful.. expecting more of this type..

    • Mohit Madan

      Thank you. Stay tunes, more coming up soon. 🙂

  • Mahmud

    Really thoughtful selection of code. Great job! I am yet to utilize the code here. I’ll get back once I have utilized those. One code that many people look for is preventing multiple login with same id. Appreciate if you give this. Thanks!!!

    • Mohit Madan

      Thank You.
      Regarding multiple login with same id, you want that if a person is logged in, no one else should login with the same credentials from any other location?

  • Navjyot Gaonkar

    awsommeeee ….good and genuine idea…salute for this post…

    • Mohit Madan

      Thank you for your kind words 🙂

  • woooww, nice list!

    • Mohit Madan

      Thanks! Do subscribe and share 🙂

  • Sriharsha CR

    Grate work Mr. Mohit Madan;
    This post impressed me in adding up a new module to my project… 🙂
    Thank you

    • Mohit Madan

      I am so happy to hear that. Do share your project once it is complete. 🙂

  • Great Work.

    • Mohit Madan

      Thank You 🙂

  • Maruthi Prasad

    Great Work… very helpful… I loved it… 🙂

    • Mohit Madan

      Thank you 🙂

  • Mocha Dwi

    thank you very much for the author and thank you for koonk technologies for sharing this 🙂

    • Mohit Madan

      Thank you for your kind words. Do subscribe and share 🙂

  • Cryde

    No no no no no …
    mysql_connect is obsolet … (http://php.net/mysql_connect and all mysql_* stuff)
    DON’T use the clean function … There is a lot of php dedicated functions out there … damn we are in 2015 guys ! Read the doc !
    “$text = “alert(1)”;” is NOT a SQL INJECTION … Is it possibly a CSRF or XSS but NOT a SQL INJECTION. Damn you put link that you don’t even read …

    Really poor snippets
    Some are “cool” but some are really useless.

    • Mohit Madan

      Hello,

      Thank you for your honest feedback. I would be adding PDO shortly.

      • Cryde

        Your welcom !
        eregi_* are also obsolet since PHP 5.3 use preg_* instead (with i modifier)

        • David Vander Elst

          function is_validemail($email) {
          return filter_var($email,FILTER_VALIDATE_EMAIL);
          }

          do the same job

      • Cryde

        Also :
        function is_validemail($email) {
        $check = 0;
        if(filter_var($email,FILTER_VALIDATE_EMAIL)) {
        $check = 1;
        }
        return $check;
        }

        Why don’t you “just” do that (no function at all) :

        if(filter_var($email,FILTER_VALIDATE_EMAIL) !== false) {
        // ok
        } else {
        // not ok
        }

        Read : http://php.net/filter_var

        • MrJulio

          Or: return (bool)filter_var($email, FILTER_VALIDATE_EMAIL);

      • Cryde

        The “37” is really nice “calculate distance between two map coordinates”

  • Apps

    Really amazing this content in single post if it is continued like this no words……..

    • Mohit Madan

      Thank you 🙂
      More content coming soon. Do subscribe and share.

  • Harut Margaryan

    Here is some useful things which I always wanted to have. Thanks a lot. Waiting for continuation

    • Mohit Madan

      Thank you for the kind words. Do share 🙂

  • Thank you for sharing this!
    All snippets are really helpful and you list it in one place, really helpful and time saving.
    Sharing link to my facebook page!!

    • Mohit Madan

      Thanks a lot! 😀

  • David Vander Elst

    I looked this post and I cried. Is that possible to have a wrost code? I’m not sure…
    Maybe my grandma has a better one. Please stop coding, and stop share your shit! This is veryyyyyyyyyyy awful… really stop publish this kind of shit… I almost committed suicide right now ^^

    Point 3… are you f*kin serious dude?? Is that code or toilet paper? ^^

  • raphhh

    maybe your tips are good but your code is totaly deprecated… :’) I recommend you to read this book to be up-to-date: http://shop.oreilly.com/product/0636920033868.do and about your style, you should read oncle bob books like: http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882

  • Gyula Madarasz

    nice list, add it to github! 🙂

  • Danish Wadhwa

    The information you have posted is very useful. But I am using http://msgwow.com/ as SMS gateway.

  • Arpita Mishra

    Hello! I predict that you will be an incredible blogger who will engrave on the developing on the web masses. All the best for your future. Your data is one of a kind and clear. There is no unfaltering words that occupy perusers like me. Approach to go! Looking forward to more of your http://www.zopcodes.com/php-scripts

  • amit

    PDF TO IMAGE CONVERTER WITH IMAGEBRICK
    there convert exce() where is lib.not found

  • Good tips to create php codes help to improve our project. Thanks. Bollywood CDS

  • Good tips and its very helpful for me. hollywood

  • Techisha

    Thanks for given valuable information.

    Visit any MLM Software