How to parse JSON using PHP

In this example, we will learn how to parse or read a JSON object using PHP built-in function. JSON Let’s create a separate file for the JSON. Copy-paste the following line of the code and save the file as “test.json” {"a":"apple","b":"banana","c":"carrot"} PHP PHP provides two variants of json_decode to parse or read the JSON. Parse... » read more

Linear Search in PHP

The following function searches for an element $x from an array called $arr by going through each element of the array, one by one. If the element is found in the array, the function returns the index of the element, otherwise, it returns -1. Linear Search function using PHP <?php function search($arr, $x) { for($i... » read more

Copy Directory Content into Sub Directory using PHP

The code below copies a folder content ( or directory) into a newly created subfolder( or subdirectory). <?php $myDir = opendir('/myDir'); mkdir('/myDir/newDir'); while (false !== ($file = readdir($myDir))) { if (($file != '.') && ($file != '..')) { if (is_dir('/myDir/' . $file)) { $this->recurseCopy('/myDir/' . $file, '/myDir/newDir/' . $file); } else { copy('/myDir/' . $file,... » read more

Validate Email Address using PHP

Below is a PHP function that validates an email address and returns the result as a boolean. This function uses the PHP built-in function filter_var and the filter FILTER_VALIDATE_EMAIL <?php //php 7.0.8 function ValidateEmail($email) { $email = ''; $isValid = filter_var($email, FILTER_VALIDATE_EMAIL); if ($isValid) { return true; } else { return false; } } ?> Easy isn’t?... » read more

Get Local IP Address using PHP

A function that will return the local IP address. <?php function GetIPAddress() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ipAddress = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ipAddress = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ipAddress = $_SERVER['REMOTE_ADDR']; } echo "You IP address is $ipAddress"; } ?> Related Snippets

Get Current Page URL using PHP

A PHP function to return the current page URL. <?php function getCurrentURL() { $CurrentURL = @( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"]; $CurrentURL .= ( $_SERVER["SERVER_PORT"] !== 80 ) ? ":".$_SERVER["SERVER_PORT"] : ""; $CurrentURL .= $_SERVER["REQUEST_URI"]; return $url; } ?> Happy Coding!!! Related Snippets

Get Image Height and Width using PHP

A snippet to get an image height and width using PHP built-in function getimagesize  and list: <?php list($width, $height) = getimagesize("myImage.png"); echo "Image width is " . $width; echo "<br>"; echo "Image height is " . $height; ?> Happy Coding! Related Snippets