10 Useful PHP Snippets for Web Developers

London Lingo
4 min readMay 27, 2023

PHP is one of the most popular server-side languages for web development. It offers a lot of features and flexibility to create dynamic and interactive web applications. However, sometimes you may need some quick and handy code snippets to solve common problems or enhance your code. In this blog post, I will share with you 10 useful PHP snippets that you can use in your projects with minimal effort. These snippets cover topics such as MySQL, HTML, arrays, strings, JSON, and more. Let’s get started!

1. Connect to MySQL Database

The following snippet will connect to your MySQL database using the MySQL improved extension. You need to update the parameters to reflect your database credentials.

$mysqli = mysqli_connect('localhost', 'DATABASE_USERNAME', 'DATABASE_PASSWORD', 'DATABASE_NAME');
// Check and output connection errors
if (mysqli_connect_errno()) {
exit('Failed to connect to MySQL: ' . mysqli_connect_error());
}

2. Escape HTML Entities

The following snippet will escape HTML entities and quotes, which will prevent XSS attacks. This is useful when you need to output user input or other untrusted data.

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

To decode HTML entities, you can use:

html_entity_decode($text);

3. Replace Text in String

The following snippet will replace text in a string. You can use it to modify or remove unwanted characters or words.

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

To replace multiple words in a string, you can use 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. You can use it to perform conditional actions based on the presence or absence of a word.

if (strpos('My name is Sagar.', 'Sagar') !== false) {
// Do something
}

With PHP >= 8, you can do:

if (str_contains('My name is Sagar.', 'Sagar')) {
// Do something
}

5. Array Snippets

Arrays are one of the most useful data structures in PHP. Here are some snippets that will help you manipulate arrays.

Inserting new items into an array:

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

You can also do:

$names = array();
$names[] = 'Sagar';
$names[] = 'Akash';

Remove item from an array:

unset($names['David']);
unset($names[0]);

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($names);

Sort an array in reverse order:

rsort($names);

Check if an item exists in an array:

if (in_array('Sagar', $names)) {
// Do something
}

Check if key exists in an array:

if (array_key_exists('name', array('name' => 'Sagar', 'age' => 28))) {
// Do something
}

6. GET and POST Requests

The following snippets will help you handle GET and POST requests in PHP. You can use them to retrieve user input or other data from forms or URLs.

Get the value of a GET parameter:

$_GET['name'];

Get the value of a POST parameter:

$_POST['name'];

Check if a GET parameter exists:

if (isset($_GET['name'])) {
// Do something
}

Check if a POST parameter exists:

if (isset($_POST['name'])) {
// Do something
}

7. Create and Verify a Password Hash

The following snippets will help you create and verify a password hash using the PHP built-in functions. This is a secure way to store and check user passwords.

Create a password hash using the default algorithm (bcrypt):

$password_hash = password_hash($password, PASSWORD_DEFAULT);

Verify a password against a hash:

if (password_verify($password, $password_hash)) {
// Password is valid
} else {
// Password is invalid
}

8. Session Handling

The following snippets will help you handle sessions in PHP. Sessions are a way to store and access data across multiple requests.

Start a session:

session_start();

Set a session variable:

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

Get a session variable:

$_SESSION['name'];

Check if a session variable exists:

if (isset($_SESSION['name'])) {
// Do something
}

Remove a session variable:

unset($_SESSION['name']);

Destroy a session:

session_destroy();

9. Redirect URL

The following snippet will redirect the user to another URL using the PHP header function.

header('Location: https://www.google.com');
exit();

Make sure you call this function before any output is sent to the browser.

10. Create and Parse JSON Data

The following snippets will help you create and parse JSON data using the PHP built-in functions. JSON is a common format for exchanging data between web applications.

Create JSON data from an array or an object:

$json_data = json_encode($array_or_object);

Parse JSON data into an array or an object:

$array_or_object = json_decode($json_data);
// To get an associative array, use:
$array_or_object = json_decode($json_data, true);

These are some of the useful PHP snippets that I have collected and used in my web development projects. I hope you find them helpful and easy to implement. Of course, there are many more PHP snippets that you can discover and use. If you have any suggestions or feedback, please leave a comment below. Thank you for reading!

--

--