10 Exceptionally Reliable PHP Snippets for Developers

For PHP developers snippets come extremely handy when they have to spend long hours to code their websites and applications. These guys can swear on their advantage and the level of control and speed these snippets provide to maintain the pace of their work. PHP snippets can be valuable for any webmaster as they offer a variety of functions which can save their time and efforts when developing a site. In this post, we have compiled a list of some resourceful PHP snippets which developers can find useful to manage their coding endeavors. The snippets listed can give an edge to the skills of any serious coder. All of them are designed to perform some specific tasks within complex coding projects in the quickest possible way.

Text Messaging with PHP Using the TextMagic API

An all new dynamic API from TextMagic can help you send text messages to your clients on their cell phones faster and easier. If you are interested to use this API then you'll have to pay some amount for it. Code is mentioned below:
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
// Include the TextMagic PHP lib require('textmagic-sms-api-php/TextMagicAPI.php'); // Set the username and password information $username = 'youruser'; $password = 'yourpassword'; // Create a new instance of TM $router = new TextMagicAPI(array( 'username' => $username, 'password' => $password )); // Send a text message to '210-12345-67' $result = $router->send('Wake up!', array(2101234567), true); // result: Result is: Array ( [messages] => Array ( [19896128] => 210-12345-67) [sent_text] => Wake up! [parts_count] => 1 )

Get Info About Your Memory Usage

Use the following code to know about your memory usage on your server.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
echo "Initial: ".memory_get_usage()." bytes \n"; //prints Initial: 361400 bytes // let's use up some memory for ($i = 0; $i < 100000; $i++) { $array []= md5($i); } // let's remove half of the array for ($i = 0; $i < 100000; $i++) { unset($array[$i]); } echo "Final: ".memory_get_usage()." bytes \n"; // prints Final: 885912 bytes echo "Peak: ".memory_get_peak_usage()." bytes \n"; //prints Peak: 13687072 bytes

Detect Location by IP

Using this code you can easily detect the location of a specific IP. It's easy to use, all you need just enter the IP address in the place of a parameter function and detect the location.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
function detect_city($ip) { $default = 'UNKNOWN'; if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost') $ip = '8.8.8.8'; $curlopt_useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)'; $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip); $ch = curl_init(); $curl_opt = array( CURLOPT_FOLLOWLOCATION => 1, CURLOPT_HEADER => 0, CURLOPT_RETURNTRANSFER => 1, CURLOPT_USERAGENT => $curlopt_useragent, CURLOPT_URL => $url, CURLOPT_TIMEOUT => 1, CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'], ); curl_setopt_array($ch, $curl_opt); $content = curl_exec($ch); if (!is_null($curl_info)) { $curl_info = curl_getinfo($ch); } curl_close($ch); if ( preg_match('{<li>City : ([^<]*)</li>}i', $content, $regs) ) { $city = $regs[1]; } if ( preg_match('{<li>State/Province : ([^<]*)</li>}i', $content, $regs) ) { $state = $regs[1]; } if( $city!='' && $state!='' ){ $location = $city . ', ' . $state; return $location; }else{ return $default; } }

Detect Browser Language

If you want to detect the language of any browser simply use the code below.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
function get_client_language($availableLanguages, $default='en'){ if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']); foreach ($langs as $value){ $choice=substr($value,0,2); if(in_array($choice, $availableLanguages)){ return $choice; } } } return $default; }

Display Source Code of a Webpage

For those developers who want to display the source code of any webpage, here is a simple code to do the trick. Simply change the URL on the second line and display the source code of any web page you want.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
// display source code $lines = file('http://google.com/'); foreach ($lines as $line_num => $line) { // loop thru each line and prepend line numbers echo "Line #{$line_num} : " . htmlspecialchars($line) . " \n"; }

Date Format Validation in PHP

This simple snippet will help you validate a date in “YYYY-MM-DD” format.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
<!--?php # This particular code will generate a random string # that is 25 charicters long 25 comes from the number # that is in the for loop $string = "abcdefghijklmnopqrstuvwxyz0123456789"; for($i=0;$i<25;$i++){ $pos = rand(0,36); $str .= $string{$pos}; } echo $str; # If you have a database you can save the string in # there, and send the user an email with the code in # it they then can click a link or copy the code # and you can then verify that that is the correct email # or verify what ever you want to verify ?-->

Creating Data uri's

Use the code below to generate the data uri's. The code is useful when it comes to integrating images into HTML/CSS and then saving it on HTTp request.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
function data_uri($file, $mime) { $contents=file_get_contents($file); $base64=base64_encode($contents); echo "data:$mime;base64,$base64"; }

Detecting the Dominant Color of an Image

If you own a photography website or love to manage image galleries then you shouldn't miss the following code snippet. Using it, you can easily detect the dominant color of an image.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
$i = imagecreatefromjpeg("image.jpg"); for ($x=0;$x<imagesx($i);$x++) { for ($y=0;$y<imagesy($i);$y++) { $rgb = imagecolorat($i,$x,$y); $r = ($rgb >> 16) & 0xFF; $g = ($rgb >> & 0xFF; $b = $rgb & 0xFF; $rTotal += $r; $gTotal += $g; $bTotal += $b; $total++; } } $rAverage = round($rTotal/$total); $gAverage = round($gTotal/$total); $bAverage = round($bTotal/$total);

Check if the Server is HTTPS

Using this code script, you can identify whether the server is HTTPS or not.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
if ($_SERVER['HTTPS'] != "on") { echo "This is not HTTPS"; }else{ echo "This is HTTPS"; }

Create CSV File from a PHP Array

Using the function below it will be easy for you to create a .csv file from a PHP array.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
function generateCsv($data, $delimiter = ',', $enclosure = '"') { $handle = fopen('php://temp', 'r+'); foreach ($data as $line) { fputcsv($handle, $line, $delimiter, $enclosure); } rewind($handle); while (!feof($handle)) { $contents .= fread($handle, 8192); } fclose($handle); return $contents; }

Wrapping Up

So here is a round up of some helpful PHP code snippets which developers must have in their kitty. Keep using them and save your time while performing complicated and lengthy tasks in the manner most effective.
  • Article written by Amanda Cline. I am Amanda Cline working as a Developer with Xicom Technologies Ltd.- Mobile Application Development Company. Apart from this I've gathered an excellent amount of expertise as an IT support personal, blogger, computer programmer, App developer, a mentor and a trainer. You can Contact me Via @amandacline111
  • In the Detecting the Dominant Color of an Image snippet, there is an omission:
    • 1
    • 2
    • 3
    • 4
    // This... $g = ($rgb >> & 0xFF; // Probably should be this: $g = ($rgb >> 8) & 0xFF;
    But, if @Kenke is correct, this is moot ;)
  • The "Detecting the Dominant Color of an Image" function dont work in the last php versions, here is another function to detect all color from an image:
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    <?php function detectColors($image, $num, $level = 5) { $level = (int)$level; $palette = array(); $size = getimagesize($image); if(!$size) { return FALSE; } switch($size['mime']) { case 'image/jpeg': $img = imagecreatefromjpeg($image); break; case 'image/png': $img = imagecreatefrompng($image); break; case 'image/gif': $img = imagecreatefromgif($image); break; default: return FALSE; } if(!$img) { return FALSE; } for($i = 0; $i < $size[0]; $i += $level) { for($j = 0; $j < $size[1]; $j += $level) { $thisColor = imagecolorat($img, $i, $j); $rgb = imagecolorsforindex($img, $thisColor); $color = sprintf('%02X%02X%02X', (round(round(($rgb['red'] / 0x33)) * 0x33)), round(round(($rgb['green'] / 0x33)) * 0x33), round(round(($rgb['blue'] / 0x33)) * 0x33)); $palette[$color] = isset($palette[$color]) ? ++$palette[$color] : 1; } } arsort($palette); return array_slice(array_keys($palette), 0, $num); } $img = 'image.jpg'; $palette = detectColors($img, 6, 1); echo '<img src="' . $img . '" />'; echo '<table>'; foreach($palette as $color) { echo '<tr><td style="background:#' . $color . '; width:36px;"></td><td>#' . $color . '</td></tr>'; } echo '</table>'; ?>
    • CREATE TABLE `data`.`tb` (`name` VARCHAR( 25 ) NOT NULL , `color` VARCHAR( 5 ) NOT NULL) ENGINE = INNODB;Using Global variable $_POST, we have to send data from HTML form into php script.Here the PHP and HTML coding is to insert the data obtained from radio button into MySQL database using PHP script.we have to give all input radio button as color (i.e., all radio buttons should have same radio button )Which Color your like most?Name: Red Green Black White
  • The Snipped "Date Format Validation in PHP" generate an string (25 chars) to validate date format you need to do
    • 1
    • 2
    • 3
    • 4
    • 5
    if(preg_match("/([0-9]{4})\-([0-9]{1,2})\-([0-9]{1,2})/i",$string,$f){ echo "Date ok"; }else{ echo "Bad format"; }
New question is currently disabled!