Developer News, More

Top 10 PHP Code Snippets for Web Developers

PHP-code-snippets

Every web developer should keep useful code snippets in a personal library for future reference.In this post we will show you some useful code snippets of PHP which will help you for your future projects.

Top 10 PHP Code Snippets for Web Developers

See More: Top 8 JavaScript Code Snippets for Web Projects

See More: 30 Useful PHP Libraries for Developers

See More: Best PHP Development Tools of 2015

See More: Best PHP Frameworks For Web Developers

See More: Best PHP Debugging Tools

Convert URLs within String into hyperlinks

top-12-code-snippets-of-php

[button url=”http://snipplr.com/view/18516/” postid=”” style=”btn-primary” size=”btn-default” target=”_blank” fullwidth=”false”]Sourch[/button]

 

GET INFO ABOUT YOUR MEMORY USAGE

Using this code can help you know about the users RAM ( memory) on your server.

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
*/

 

Get all tweets of a specific hashtag

function getTweets($hash_tag) {

    $url = 'http://search.twitter.com/search.atom?q='.urlencode($hash_tag) ;
    echo "<p>Connecting to <strong>$url</strong> ...</p>";
    $ch = curl_init($url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $xml = curl_exec ($ch);
    curl_close ($ch);

    //If you want to see the response from Twitter, uncomment this next part out:
    //echo "<p>Response:</p>";
    //echo "<pre>".htmlspecialchars($xml)."</pre>";

    $affected = 0;
    $twelement = new SimpleXMLElement($xml);
    foreach ($twelement->entry as $entry) {
        $text = trim($entry->title);
        $author = trim($entry->author->name);
        $time = strtotime($entry->published);
        $id = $entry->id;
        echo "<p>Tweet from ".$author.": <strong>".$text."</strong>  <em>Posted ".date('n/j/y g:i a',$time)."</em></p>";
    }

    return true ;
}

getTweets('#cats');

[button url=”http://www.inkplant.com/code/get-twitter-posts-by-hashtag.php” postid=”” style=”btn-primary” size=”btn-default” target=”_blank” fullwidth=”false”]Sourch[/button]

 

Random password generator

top-12-code-snippets-of-php2

[button url=”https://dzone.com/articles/random-password-generator-php” postid=”” style=”btn-primary” size=”btn-default” target=”_blank” fullwidth=”false”]Sourch[/button]

 

CHECK IF SERVER IS HTTPS

if ($_SERVER['HTTPS'] != "on") { 
	echo "This is not HTTPS";
}else{
	echo "This is HTTPS";
}

 

Parse XML Data

top-12-code-snippets-of-php3

[button url=”http://us2.php.net/simplexml” postid=”” style=”btn-primary” size=”btn-default” target=”_blank” fullwidth=”false”]Sourch[/button]

 

Detect browser language

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;
}

[button url=”http://snipplr.com/view/12631/detect-browser-language/php-detect-browser-language” postid=”” style=”btn-primary” size=”btn-default” target=”_blank” fullwidth=”false”]Sourch[/button]

 

Calculate distance between two points

function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2) {
    $theta = $longitude1 - $longitude2;
    $miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
    $miles = acos($miles);
    $miles = rad2deg($miles);
    $miles = $miles * 60 * 1.1515;
    $feet = $miles * 5280;
    $yards = $feet / 3;
    $kilometers = $miles * 1.609344;
    $meters = $kilometers * 1000;
    return compact('miles','feet','yards','kilometers','meters'); 
}

Example:

$point1 = array('lat' => 40.770623, 'long' => -73.964367);
$point2 = array('lat' => 40.758224, 'long' => -73.917404);
$distance = getDistanceBetweenPointsNew($point1['lat'], $point1['long'], $point2['lat'], $point2['long']);
foreach ($distance as $unit => $value) {
    echo $unit.': '.number_format($value,4).'<br />';
}

[button url=”http://www.inkplant.com/code/calculate-the-distance-between-two-points.php” postid=”” style=”btn-primary” size=”btn-default” target=”_blank” fullwidth=”false”]Sourch[/button]

 

How to block multiple IP adresses

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
if ( !file_exists('blocked_ips.txt') ) {
 $deny_ips = array(
  '127.0.0.1',
  '192.168.1.1',
  '83.76.27.9',
  '192.168.1.163'
 );
} else {
 $deny_ips = file('blocked_ips.txt');
}
// read user ip adress:
$ip = isset($_SERVER['REMOTE_ADDR']) ? trim($_SERVER['REMOTE_ADDR']) : '';
 
// search current IP in $deny_ips array
if ( (array_search($ip, $deny_ips))!== FALSE ) {
 // address is blocked:
 echo 'Your IP adress ('.$ip.') was blocked!';
 exit;
}

[button url=”http://www.hashbangcode.com/blog/blocking-multiple-ip-addresses-php” postid=”” style=”btn-primary” size=”btn-default” target=”_blank” fullwidth=”false”]Sourch[/button]

 

GENERATE CSV FILE FROM A PHP ARRAY

This function helps to generate a .csv file from PHP array. Get the script below-

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;
}

 

You Might Also Like

One comment

Leave a Reply