Need an Eye-caching Website - Contact Me Today !

20 Very Useful PHP Code Snippets For PHP Developers


20 Very Useful PHP Code Snippets For PHP Developers

  • 278
  • 0
  • 08-Sep-2022

1. MySQL Snippets

The following snippet will connect to your MySQL database using the MySQL improved extension.

$mysqli = mysqli_connect('localhost', 'DATABASE_USERNAME', 'DATABASE_PASSWORD', 'DATABASE_NAME');

However, for the above connection code to work correctly, you must update the parameters to reflect your database credentials.

Check and output connection errors:

if (mysqli_connect_errno()) {

    exit('Failed to connect to MySQL: ' . mysqli_connect_error());


Select database table and populate the results:

$result = $mysqli->query('SELECT * FROM students');

while ($row = $result->fetch_assoc()) {

    echo $row['name'] . '<br>';


Retrieve the number of rows:


Insert a new record:

$mysqli->query('INSERT INTO students (name) VALUES ("Sagar")');

Retrieve the number of affected rows:


Escape special characters in a string (which is vital if you're not using prepared statements):


Prepare statement (prevents SQL injection):

$name = 'Sagar';

$limit = 1;

// Prepare query

$stmt = $mysqli->prepare('SELECT age, address FROM students WHERE name = ? LIMIT ?');

// data types: i = integer, s = string, d = double, b = blog

$stmt->bind_param('si', $name, $limit);

// Execute query


// Bind the result

$stmt->bind_result($age, address);

Close the query and database connection:




2. Escape HTML Entities

The following snippet will escape HTML entities and quotes, which will prevent XSS attacks

htmlentities($text, ENT_QUOTES, 'UTF-8');

Decoding HTML entities:



3. Replace Text in String

The following snippet will replace text in a string.

str_replace('Apple', 'Orange', 'My favourite fruit is an Apple.');

And to replace multiple words in a string, we can declare an array of strings:

str_replace(array('fruit', 'Apple'), array('Vegetable', 'Carrot'), 'My favourite fruit is an Apple.');


4. Check if a String Contains a Specific Word

The following snippet will check if a string contains a specific word:

if (strpos('My name is Sagar.', Sagar) !== false) {

    // String contains David


With PHP >= 8, we can do:

if (str_contains('My name is Sagar.', Sagar)) {

    // String contains David



5. Array Snippets

Inserting new items into an array:

$names = array();

array_push($names, 'Sagar', 'Akash');

We can also do:

$names = array();

$names[] = 'Sagar';

$names[] = 'Akash';

Remove item from an array:


// or...


Reindex the values after you have removed an item:

$names = array_values($names);

Reverse an array:

$reversed = array_reverse($names);

Merge two or more arrays:

$merged_array = array_merge($array1, $array2);

Return only the array keys:

$keys = array_keys(array('name' => 'Sagar', 'age' => 22));

Sort an array in ascending order:


Sort an array in reverse order:


Check if an item exists in an array:

if (in_array('Sagar', $names)) {

    // item exists


Check if key exists in an array:

if (array_key_exists('name', array('name' => 'Sagar', 'age' => 28))) {

    // key exists



Count the number of items in an array:


Convert comma-separated list to array:

$array = explode(',', 'sagar,aakash,akshay,khushi');


6. GET and POST Requests

Retrieve a GET request parameter, which can be specified in the URL:

// index.php?name=sagar

echo $_GET['name'];

// index.php?name=sagar&surname=kumar

echo $_GET['surname'];

Check if request variable exists:

if (isset($_GET['name'])) {

    // exists


Process HTML form data with PHP:

<form action="login.php" method="post">

Username: <input type="text" name="username"><br>

Password: <input type="password" name="password"><br>

<input type="submit">



$user = $_POST['username'];

$pass = $_POST['password'];

echo 'Your username is '  . $user . ' and your password is ' . $pass . '.';


7. Create and Verify a Password Hash

The following snippet will create a password hash using a one-way hashing algorithm

$hash = password_hash('your_password', PASSWORD_DEFAULT);

Verify your hashed passwords:

if (password_verify('your_password', $hash)) {

    // hash is valid



8. Session Handling

In a nutshell, sessions act as cookies but are stored on the server as opposed to the client's computer. In addition, a unique ID is generated and stored as a cookie in the client's browser. It's used to associate the client with the session data.

The following snippet will create a new session.


$_SESSION['name'] = 'Sagar';

Free all the session variables associated with the client from memory:


Destroy all the session variables associated with the client:



9. Redirect URL

The following snippet will redirect to a new page:



10. Determining Client IP Address

This snippet will get the IP address of the client:

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {

    $ip = $_SERVER['HTTP_CLIENT_IP'];

} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {


} else {

    $ip = $_SERVER['REMOTE_ADDR'];


echo $ip; // outputs the IP address to screen


11. Get the Contents of a URL File

The following snippet will get the contents of a file using cURL.

$url = '';

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

curl_setopt($curl, CURLOPT_HEADER, false);

curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);

curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

$result = curl_exec($curl);


Using the PHP file_get_contents function:

$result = file_get_contents('file.json');


12. Determining Current Date

The following snippet will get the current date in string format.

$date = date('Y-m-d H:i:s');

echo $date;

Get the date from a timestamp:

$timestamp = 1641826797;

$date = date('Y-m-d H:i:s', $timestamp);

echo $date;


13. Create and Parse JSON

The following snippet will convert an PHP array to JSON.

$array = array('name' => 'Sagar', 'age' => 22);

$string = json_encode($array);

echo $string; // { "name" : "Sagar", "age" : 22 }

Parse an JSON file:

$string = file_get_contents('file.json');

$json = json_decode($string, true);

// $json['name'] etc...


14. Send Email

The following snippet will send an email.

$from    = '';

$to      = '';

$subject = 'Your Subject';

// Plain message

$message = 'Hello! How are you today?';

// HTML message

$message = '<p>Hello! How are you today?</p>';

$headers = 'From: ' . $from . "\r\n" . 'Reply-To: ' . $from . "\r\n" . 'Return-Path: ' . $from . "\r\n" . 'X-Mailer: PHP/' . phpversion() . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-Type: text/html; charset=UTF-8' . "\r\n";

mail($to, $subject, $message, $headers);


15. Display the Scripts Execution Time

The following snippet will display the scripts execution time.

$time_start = microtime(true);

// Place your scripts here...

echo 'Total execution time in seconds: ' . (microtime(true) - $time_start);


16. Get the Full URL

The following snippet will get the full URL of your website (replace HTTP with HTTPS if using SSL).

$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];


17. Format Numbers

The following snippet will format a number.

$num = number_format(1000);

echo $num; // 1,000

Format number with decimals:

$num = number_format(1000.12, 2);

echo $num; // 1,000.12


18. Unzip a File

The ZIP extension is required for this to work.

The following snippet will unzip an archive file on your server.

$zip = new ZipArchive;

$file = $zip->open('');

if ($file) {



    echo 'Archive extracted successfully!';



19. Mobile Device Detection

The following snippet will detect if the client is using a mobile device.

if (preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"])) {

    // Is mobile...



20. Check if File Exists

The following snippet will check if a file exists.

if (file_exists('example.png')) {

    // File exists



These snippets are useful if you develop PHP applications regularly or if you're a beginner programmer looking for a particular snippet. Keep the page bookmarked for future reference.

Enjoy coding!

There are 0 Comments on this post
Please login to comment

Typically replies within an hour

Hi there 👋

How can I help you?
Chat with Me