[GET]List of PHP snippets for making your coding life easier - Continuously updated!

Gogol

Administrator
Staff member
Moderator
Executive VIP
Jr. VIP
Joined
Sep 10, 2010
Messages
11,807
Reaction score
26,660
Hi all!

I made this thread for the PHP coders. I will keep updating this thread with code snippets that do various jobs. I have collected these snippets from various sources and use them for my own projects. You can make utility classes to use them, or can simple use this in your project as functions. So let me begin by sharing these:

P.S. If you need to do some task and searching for a snippet, then post here. I will provide you with one :)


Encryption Decryption function for security:

Code:
function encrypt($decrypted, $password = 'dasdasdasdasd', $salt = '!kQm*fdasdssdasda28932893s9d9sdm%9') {
        // Build a 256-bit $key which is a SHA256 hash of $salt and $password.
        $key = hash('SHA256', $salt . $password, true);
        // Build $iv and $iv_base64.  We use a block size of 128 bits (AES compliant) and CBC mode.  (Note: ECB mode is inadequate as IV is not used.)
        srand();
        $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
        if (strlen($iv_base64 = rtrim(base64_encode($iv), '=')) != 22)
            return false;
        // Encrypt $decrypted and an MD5 of $decrypted using $key.  MD5 is fine to use here because it's just to verify successful decryption.
        $encrypted = base64_encode(@mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $decrypted . md5($decrypted), MCRYPT_MODE_CBC, $iv));
        // We're done!
        $iv = base64_encode($iv_base64 . $encrypted);
        return $iv;
    }

    function decrypt($encrypted, $password = 'dasdasdasdasd', $salt = '!kQm*fdasdssdasda28932893s9d9sdm%9') {
        // Build a 256-bit $key which is a SHA256 hash of $salt and $password.
        $encrypted = base64_decode($encrypted);
        $key = hash('SHA256', $salt . $password, true);
        // Retrieve $iv which is the first 22 characters plus ==, base64_decoded.
        $iv = base64_decode(substr($encrypted, 0, 22) . '==');
        // Remove $iv from $encrypted.
        $encrypted = substr($encrypted, 22);
        // Decrypt the data.  rtrim won't corrupt the data because the last 32 characters are the md5 hash; thus any \0 character has to be padding.
        $decrypted = rtrim(@mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($encrypted), MCRYPT_MODE_CBC, $iv), "\0\4");
        // Retrieve $hash which is the last 32 characters of $decrypted.
        $hash = substr($decrypted, -32);
        // Remove the last 32 characters from $decrypted.
        $decrypted = substr($decrypted, 0, -32);
        // Integrity check.  If this fails, either the data is corrupted, or the password/salt was incorrect.
        if (md5($decrypted) != $hash)
            return false;
        // Yay!
        return $decrypted;
    }

Make random Strings of specified length


Code:
    function randomString($max = 10) {
        $i = 0; //Reset the counter.
        $possible_keys = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $keys_length = strlen($possible_keys);
        $str = ""; //Let's declare the string, to add later.
        while ($i < $max) {
            $rand = mt_rand(1, $keys_length - 1);
            $str.= $possible_keys[$rand];
            $i++;
        }
        return $str;
    }

Make seo friendly slug like Wordpress, from any string


Code:
    function sluggify($string) {
        $slug = preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
        return trim($slug , '-');
    }

Write text over image, with Border (imagettftext alternative)(needs GD library enabled):

Code:
function imagettfborder($im, $size, $angle, $x, $y, $color,$color1, $font, $text, $width) {
    // top
    imagettftext($im, $size, $angle, $x-$width, $y-$width, $color1, $font, $text);
    imagettftext($im, $size, $angle, $x, $y-$width, $color1, $font, $text);
    imagettftext($im, $size, $angle, $x+$width, $y-$width, $color1, $font, $text);
    // bottom
    imagettftext($im, $size, $angle, $x-$width, $y+$width, $color1, $font, $text);
    imagettftext($im, $size, $angle, $x, $y+$width, $color1, $font, $text);
    imagettftext($im, $size, $angle, $x-$width, $y+$width, $color, $font, $text);
    // left
    imagettftext($im, $size, $angle, $x-$width, $y, $color1, $font, $text);
    // right
    imagettftext($im, $size, $angle, $x+$width, $y, $color, $font, $text);
    for ($i = 1; $i < $width; $i++) {
        // top line
        imagettftext($im, $size, $angle, $x-$i, $y-$width, $color1, $font, $text);
        imagettftext($im, $size, $angle, $x+$i, $y-$width, $color, $font, $text);
        // bottom line
        imagettftext($im, $size, $angle, $x-$i, $y+$width, $color1, $font, $text);
        imagettftext($im, $size, $angle, $x+$i, $y+$width, $color, $font, $text);
        // left line
        imagettftext($im, $size, $angle, $x-$width, $y-$i, $color1, $font, $text);
        imagettftext($im, $size, $angle, $x-$width, $y+$i, $color, $font, $text);
        // right line
        imagettftext($im, $size, $angle, $x+$width, $y-$i, $color1, $font, $text);
        imagettftext($im, $size, $angle, $x+$width, $y+$i, $color, $font, $text);
    }
}

Easy Object to Array transformation:
Code:
function obj2arr($obj = null)
{
    if($obj === null)
        return false;
    $temp = json_encode($obj);
    return json_decode($temp , true);
}

String to boolean (try to guess if a word means yes or no)
Code:
function str_to_bool( $string, $default = FALSE )
        {
            $yes_words = 'affirmative|all right|aye|indubitably|most assuredly|ok|of course|okay|sure thing|y|yes+|yea|yep|sure|yeah|true|t|on|1';
            $no_words = 'no*|no way|nope|nah|na|never|absolutely not|by no means|negative|never ever|false|f|off|0';

            if ( preg_match( '/^(' . $yes_words . ')$/i', $string ) ) {
                return TRUE;
            } else if ( preg_match( '/^(' . $no_words . ')$/i', $string ) ) {
                return FALSE;
            } else {
                return $default;
            }
        }

Quick Debug function:
Code:
function debug($input , $stopCodeExecution = false)
{
    echo '<pre>';
    var_dump($input);
    echo '</pre>';
    if($stopCodeExecution)
        exit();
}

Get the sum of numbers passed into a function

Code:
function Summit() {
    $sum = 0;
    foreach (func_get_args() as $arg) {
        $sum += $arg;
    }
    return $sum;
}

use it e.g.:
$result = Summit(1,13,3.4,58000,45 );

Check if current url has https
Code:
function is_https()
        {
            if ( isset( $_SERVER['HTTPS'] ) && ! empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] != 'off' ) {
                return TRUE;
            } else {
                return FALSE;
            }
        }

Validate any youtube url
Code:
class Youtube {
///// Put together by Sugato


////////// $video_id is the youtube video ID /////////////////////////
public $video_id = null;

///////// the Constructer ////////////////////////////////////////
public function __construct($url)
{
    if (preg_match('/youtube\.com\/watch\?v=([^\&\?\/]+)/', $url, $id)) {
          $this->video_id = $id[1];
    } else if (preg_match('/youtube\.com\/embed\/([^\&\?\/]+)/', $url, $id)) {
          $this->video_id = $id[1];
    } else if (preg_match('/youtube\.com\/v\/([^\&\?\/]+)/', $url, $id)) {
          $this->video_id = $id[1];
    } else if (preg_match('/youtu\.be\/([^\&\?\/]+)/', $url, $id)) {
          $this->video_id = $id[1];
    } else {   
          $this->video_id  = NULL;
    }

}
/////////// validates if a youtube video actually exists //////////////
function validate()
{
    if(empty($this->video_id))
    {
        return false;
    }
    else {
            $curl = curl_init("http://gdata.youtube.com/feeds/api/videos/" . $this->video_id);
            curl_setopt($curl, CURLOPT_HEADER, true);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_exec($curl);
            $request = curl_getinfo($curl);
            curl_close($curl);
            $result = explode(";", $request["content_type"]);
            if($result[0] == "application/atom+xml")
            {
                return true;
            } else {
                return false;
            }
    }
}
}

Call it like:
$yt = new Youtube($your_video_link_here);
    $exist  = $yt->validate();

    if($exist) 
    {
       echo "Yaaaayyyyyy!";
    } else
    {
       echo "nAAAAyyyy!!!";
    }

True email validation in PHP
Code:
function CheckAndValidateEmail($mail) {
        if (filter_var($mail, FILTER_VALIDATE_EMAIL)) {
            // ok
            list($user, $domaine) = split("@", $mail, 2);
            if (!checkdnsrr($domaine, "MX") && !checkdnsrr($domaine, "A")) {
                return false;
            } else {
                return true;
            }
        } else {
            //no
            return false;
        }
    }

Import and display Tweets through PHP

Code:
function twitter_feed($username) {
    $feed_url = "http://search.twitter.com/search.atom?q=from:".$username."&rpp=2";
    $feed = file_get_contents($feed_url);
    $stepOne = explode('<content type="html">', $feed);
    $stepTwo = explode('</content>', $stepOne[1]);
    $tweet = $stepTwo[0];
    $tweet = str_replace("<", "<", $tweet);
    $tweet = str_replace(">", ">", $tweet);
    return $tweet;
}
echo twitter_feed('lolmyball');

Echo multiple strings in new lines
Code:
function multiecho() {   
    $args = func_get_args();  
    foreach ($args as $k => $v) {  
        echo "$v\r\n";  
    }  
  
}  
call it like:
multiecho("I am" , "a" , "program");
multiecho("Bye!");

Check if a string is utf
Code:
function seems_utf8( $string )
        {
            if ( function_exists( 'mb_check_encoding' ) ) {
                // If mbstring is available, this is significantly faster than
                // using PHP regexps.
                return mb_check_encoding( $string, 'UTF-8' );
            }

            $regex = '/(
| [\xF8-\xFF] # Invalid UTF-8 Bytes
| [\xC0-\xDF](?![\x80-\xBF]) # Invalid UTF-8 Sequence Start
| [\xE0-\xEF](?![\x80-\xBF]{2}) # Invalid UTF-8 Sequence Start
| [\xF0-\xF7](?![\x80-\xBF]{3}) # Invalid UTF-8 Sequence Start
| (?<=[\x0-\x7F\xF8-\xFF])[\x80-\xBF] # Invalid UTF-8 Sequence Middle
| (?<![\xC0-\xDF]|[\xE0-\xEF]|[\xE0-\xEF][\x80-\xBF]|[\xF0-\xF7]|[\xF0-\xF7][\x80-\xBF]|[\xF0-\xF7][\x80-\xBF]{2})[\x80-\xBF] # Overlong Sequence
| (?<=[\xE0-\xEF])[\x80-\xBF](?![\x80-\xBF]) # Short 3 byte sequence
| (?<=[\xF0-\xF7])[\x80-\xBF](?![\x80-\xBF]{2}) # Short 4 byte sequence
| (?<=[\xF0-\xF7][\x80-\xBF])[\x80-\xBF](?![\x80-\xBF]) # Short 4 byte sequence (2)
)/x';

            return ! preg_match( $regex, $string );
        }


Check if data is serialized
Code:
function is_serialized( $data )
        {
            // If it isn't a string, it isn't serialized
            if ( ! is_string( $data ) ) {
                return FALSE;
            }

            $data = trim( $data );

            if ( 'N;' == $data ) {
                return TRUE;
            }

            $length = strlen( $data );

            if ( $length < 4 ) {
                return FALSE;
            }

            if ( ':' !== $data[1] ) {
                return FALSE;
            }

            $lastc = $data[$length - 1];

            if ( ';' !== $lastc && '}' !== $lastc ) {
                return FALSE;
            }

            $token = $data[0];

            switch ( $token ) {
                case 's' :
                    if ( '"' !== $data[$length-2] ) {
                        return FALSE;
                    }
                case 'a' :
                case 'O' :
                    return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
                case 'b' :
                case 'i' :
                case 'd' :
                    return (bool) preg_match( "/^{$token}:[0-9.E-]+;\$/", $data );
            }

            return FALSE;
        }

"x" "time" ago - Return twitter / facebook like time difference of a post

Code:
function human_time_diff( $from, $to = '', $as_text = FALSE, $suffix = ' ago' )
        {
            if ( $to == '' ) {
                $to = time();
            }

            $from = new DateTime( date( 'Y-m-d H:i:s', $from ) );
            $to = new DateTime( date( 'Y-m-d H:i:s', $to ) );
            $diff = $from->diff( $to );

            if ( $diff->y > 1 ) {
                $text = $diff->y . ' years';
            } else if ( $diff->y == 1 ) {
                $text = '1 year';
            } else if ( $diff->m > 1 ) {
                $text = $diff->m . ' months';
            } else if ( $diff->m == 1 ) {
                $text = '1 month';
            } else if ( $diff->d > 7 ) {
                $text = ceil( $diff->d / 7 ) . ' weeks';
            } else if ( $diff->d == 7 ) {
                $text = '1 week';
            } else if ( $diff->d > 1 ) {
                $text = $diff->d . ' days';
            } else if ( $diff->d == 1 ) {
                $text = '1 day';
            } else if ( $diff->h > 1 ) {
                $text = $diff->h . ' hours';
            } else if ( $diff->h == 1 ) {
                $text = ' 1 hour';
            } else if ( $diff->i > 1 ) {
                $text = $diff->i . ' minutes';
            } else if ( $diff->i == 1 ) {
                $text = '1 minute';
            } else if ( $diff->s > 1 ) {
                $text = $diff->s . ' seconds';
            } else {
                $text = '1 second';
            }

            if ( $as_text ) {
                $text = explode( ' ', $text, 2 );
                $text = self::number_to_word( $text[0] ) . ' ' . $text[1];
            }

            return trim( $text ) . $suffix;
        }

Prevent caching of a page by calling this function
Code:
function nocache_headers()
        {
            if ( ! headers_sent() ) {
                header( 'Expires: Wed, 11 Jan 1984 05:00:00 GMT' );
                header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
                header( 'Cache-Control: no-cache, must-revalidate, max-age=0' );
                header( 'Pragma: no-cache' );

                return TRUE;
            } else {
                return FALSE;
            }
        }

Get gravatar url of an email
Code:
function get_gravatar( $email, $size = 32 )
    {

$url = 'http://www.gravatar.com/';
            $url .= 'avatar/' . md5( $email ) . '?s=' . (int) abs( $size );
return $url;
}

Updates coming soon....
 
Great share.

Always good to have frequently needed functions collected in a single thread.
 
Subscribing!
I'll use it (the information) later for my PHP exercise(s).
 
Utility class for using Google translation in PHP (reply here if you are having trouble to implement it):
Code:
/*

class Translate 
created by n3curatu
author website :http://www.rowebdesign.info
author email [email protected];
*/


class translate {


    ///language from what we translate
    var $translate_from;


    ////language in what we whant to translate
    var $translate_into;

    ///debug the code
    var $debug;




    function __construct($from , $to){

        /*

        this function is for debuging code

        */

        $this->debug = 0;


        ini_set("display_errors",$this->debug);


        if(!$from){

            $this->translate_from = "en";

        }else{

            $this->translate_from = $from;

        }
        
        if(!$to){

            $this->translate_into = "it";


        }else{
            
            $this->translate_into = $to;

        }

    }


    function TranslateUrl($word){
        if(!$word){
            die("you need to adda a translate word");
        }
        ///we need to encode the word that we want to translate

        $word = urlencode($word);

        $url = "http://translate.google.com/?sl=". $this->translate_from ."&tl=". $this->translate_into ."&js=n&prev=_t&hl=it&ie=UTF-8&eotf=1&text=". $word ."";

        return $url;

    }
    function get($word){
        $dom  = new DOMDocument();     
        $html =  $this->curl_download($this->TranslateUrl($word));
        $dom->loadHTML($html);
        $xpath = new DOMXPath($dom);       
        $tags = $xpath->query('//*[@id="result_box"]');
        foreach ($tags as $tag) {         
            $var = trim($tag->nodeValue);
            if(!$var){
                die("Problem with Google translate Word")
            }else{
                return ($var);
            }                            
        }

    }

    /*
        function for downloading the gooogle page content for translating 
    */

    function curl_download($Url){
     
        // is cURL installed yet?
        if (!function_exists('curl_init')){
           
            if (function_exists('file_get_contents')){

                return file_get_contents($Url);

            }else{

                die("Your server dosen't support curl or file get contents");

            }

        }
     
        // OK cool - then let's create a new cURL resource handle
        $ch = curl_init();
        // Now set some options (most are optional)
        // Set URL to download
        curl_setopt($ch, CURLOPT_URL, $Url);
     
        // Set a referer
     
        // User agent
        curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
     
        // Include header in result? (0 = yes, 1 = no)
        curl_setopt($ch, CURLOPT_HEADER, 0);
     
        // Should cURL return or print out the data? (true = return, false = print)
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     
        // Timeout in seconds
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
     
        // Download the given URL, and return output
        $output = curl_exec($ch);
     
        // Close the cURL resource, and free system resources
        curl_close($ch);
     
        return $output;
    }


}

Find out where a function is defined (very handy in big projects where you have forgotten where the function was defined and you need to change the function.)
Code:
function printFnLoc($functionName = "")
{    
    if(empty($functionName))
        echo "function name can't be empty";
    $reflFunc = new ReflectionFunction($functionName);
    print $reflFunc->getFileName() . ':' . $reflFunc->getStartLine();
}

Wordpress like excerpt generation for your custom application

Code:
/*Excact string length version. Might cut words*/
function make_excerpt($string, $maxStrLen = 160){
    $numChars = strlen($string);
    if($numChars>$maxStrLen){
        $string = substr($string, 0, $maxStrLen) . "...";
    }
    
    //return cut string
    return $string;
} 
/*Nearest string length version. Will return full word.*/
function truncate($text, $length)
{
   $length = abs((int)$length);
   if(strlen($text) > $length)
   {
      $text = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $text);
   }
   return($text);

HSL/RGB conversion functions. very useful for a lot of applications.
Code:
function RBGtoHSL ( $R, $G, $B )
{

    $var_R = ( $R / 255 );
    $var_G = ( $G / 255 );
    $var_B = ( $B / 255 );

    $var_Min = min( $var_R, $var_G, $var_B )
    $var_Max = max( $var_R, $var_G, $var_B )
    $del_Max = $var_Max - $var_Min

    $L = ( $var_Max + $var_Min ) / 2;

    if ( $del_Max == 0 )
    {
       $H = 0
       $S = 0
    }
    else
    {
        if ( $L < 0.5 )
        {
            $S = $del_Max / ( $var_Max + $var_Min );
        }
        else
        {
            $S = $del_Max / ( 2 - $var_Max - $var_Min );
        }

        $del_R = ( ( ( $var_Max - $var_R ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
        $del_G = ( ( ( $var_Max - $var_G ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
        $del_B = ( ( ( $var_Max - $var_B ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;

        if ( $var_R == $var_Max )
        {
            $H = $del_B - $del_G;
        }
        else if ( $var_G == $var_Max )
        {
            $H = ( 1 / 3 ) + $del_R - $del_B;
        }
        else if ( $var_B == $var_Max )
        {
            $H = ( 2 / 3 ) + $del_G - $del_R;
        }

        if ( $H < 0 )
        {
            $H += 1;
        }
        if ( $H > 1 )
        {
            $H -= 1
        }

    }

    return array( $H, $S, $L );

}

function HuetoRGB( $v1, $v2, $vH )
{
    if ( $vH < 0 )
    {
        $vH += 1;
    }
    if ( $vH > 1 )
    {
        $vH -= 1;
    }
    if ( ( 6 * $vH ) < 1 )
    {
        return ( $v1 + ( $v2 - $v1 ) * 6 * $vH );
    }
    if ( ( 2 * $vH ) < 1 )
    {
        return ( $v2 );
    }
    if ( ( 3 * $vH ) < 2 )
    {
        return ( $v1 + ( $v2 - $v1 ) * ( ( 2 / 3 ) - $vH ) * 6 );
    }
    return ( $v1 )
}

function HSLtoRGB ( $H, $S, $L )
{

    if ( $S == 0 )
    {
        $R = $L * 255;
        $G = $L * 255;
        $B = $L * 255;
    }
    else
    {
        if ( $L < 0.5 )
        {
            $var_2 = $L * ( 1 + $S );
        }
        else
        {
            $var_2 = ( $L + $S ) - ( $S * $L );
        }

        $var_1 = 2 * $L - $var_2;

        $R = 255 * HuetoRGB( $var_1, $var_2, $H + ( 1 / 3 ) );
        $G = 255 * HuetoRGB( $var_1, $var_2, $H );
        $B = 255 * HuetoRGB( $var_1, $var_2, $H - ( 1 / 3 ) );
    }

    return array( $R, $G, $B );

}

function distance ( $R1, $G1, $B1, $R2, $G2, $B2 )
{
    $result = sqrt ( ( $R1 - $R2 )*( $R1 - $R2 ) + ( $G1 - $G2 )*( $G1 - $G2 ) + ( $B1 - $B2 )*( $B1 - $B2 ) );
    return ( $result );
}



Output Bmp image file!


Code:
function imagebmp ($im, $fn = false)
{
    if (!$im) return false;
           
    if ($fn === false) $fn = 'php://output';
    $f = fopen ($fn, "w");
    if (!$f) return false;
           
    //Image dimensions
    $biWidth = imagesx ($im);
    $biHeight = imagesy ($im);
    $biBPLine = $biWidth * 3;
    $biStride = ($biBPLine + 3) & ~3;
    $biSizeImage = $biStride * $biHeight;
    $bfOffBits = 54;
    $bfSize = $bfOffBits + $biSizeImage;
           
    //BITMAPFILEHEADER
    fwrite ($f, 'BM', 2);
    fwrite ($f, pack ('VvvV', $bfSize, 0, 0, $bfOffBits));
           
    //BITMAPINFO (BITMAPINFOHEADER)
    fwrite ($f, pack ('VVVvvVVVVVV', 40, $biWidth, $biHeight, 1, 24, 0, $biSizeImage, 0, 0, 0, 0));
           
    $numpad = $biStride - $biBPLine;
    for ($y = $biHeight - 1; $y >= 0; --$y)
    {
        for ($x = 0; $x < $biWidth; ++$x)
        {
            $col = imagecolorat ($im, $x, $y);
            fwrite ($f, pack ('V', $col), 3);
        }
        for ($i = 0; $i < $numpad; ++$i)
            fwrite ($f, pack ('C', 0));
    }
    fclose ($f);
    return true;
}


join() alternative. Joins multi level arrays
Code:
function joinr($join, $value, $lvl=0)
    {
        if (!is_array($join)) return joinr(array($join), $value, $lvl);
        $res = array();
        if (is_array($value)&&sizeof($value)&&is_array(current($value))) { // Is value are array of sub-arrays?
            foreach($value as $val)
                $res[] = joinr($join, $val, $lvl+1);
        }
        elseif(is_array($value)) {
            $res = $value;
        }
        else $res[] = $value;
        return join(isset($join[$lvl])?$join[$lvl]:"", $res);
    }

More coming tomorrow
 
Hi all!
Having tough time to locate thousands of snippets in my localhost LOL. Today I have managed to find some of the functions I have used in my Wordpress projects over the years.

Please note that the following functions are based on Wordpress. None of them will work without Wordpress environment.

Paste any of these functions inside your functions.php .

Load jQuery from Google CDN
Code:
// even more smart jquery inclusion :)
add_action( 'init', 'jquery_register' );

// register from google and for footer
function jquery_register() {

if ( !is_admin() ) {

    wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery', ( 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js' ), false, null, true );
    wp_enqueue_script( 'jquery' );
}
}

Change Wordpress login design.
Code:
add_filter( 'login_headerurl', 'namespace_login_headerurl' );
/**
 * Replaces the login header logo URL
 *
 * @param $url
 */
function namespace_login_headerurl( $url ) {
    $url = home_url( '/' );
    return $url;
}

add_filter( 'login_headertitle', 'namespace_login_headertitle' );
/**
 * Replaces the login header logo title
 *
 * @param $title
 */
function namespace_login_headertitle( $title ) {
    $title = get_bloginfo( 'name' );
    return $title;
}

add_action( 'login_head', 'namespace_login_style' );
/**
 * Replaces the login header logo
 */
function namespace_login_style() {
    echo '<style>.login h1 a { background-image: url( ' . get_template_directory_uri() . '/images/logo.png ) !important; }</style>';
}

Show Custom post types in search results.

Code:
function searchAll( $query ) {
 if ( $query->is_search ) { $query->set( 'post_type', array( 'site', 'plugin', 'theme', 'person' )); } 
 return $query;
}
add_filter( 'the_search_query', 'searchAll' );


Remove WP Version Information
Code:
function complete_version_removal() {
    return '';
}
add_filter('the_generator', 'complete_version_removal');


Set Max revision count to save db bloating:

Code:
if (!defined('WP_POST_REVISIONS')) define('WP_POST_REVISIONS', 5);


Reorder Admin panel menu items

Code:
 function custom_menu_order($menu_ord) {
       if (!$menu_ord) return true;
       return array(
        'index.php', // this represents the dashboard link
        'edit.php?post_type=events', // this is a custom post type menu
        'edit.php?post_type=news', 
        'edit.php?post_type=articles', 
        'edit.php?post_type=faqs', 
        'edit.php?post_type=mentors',
        'edit.php?post_type=testimonials',
        'edit.php?post_type=services',
        'edit.php?post_type=page', // this is the default page menu
        'edit.php', // this is the default POST admin menu 
    );
   }
   add_filter('custom_menu_order', 'custom_menu_order');
   add_filter('menu_order', 'custom_menu_order');

Many more coming soon...
 
Last edited:
Back to custom PHP stuffs again...



Detect Location using PHP :

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

PHP function for Whois query

Code:
function whois_query($domain) {
 
    // fix the domain name:
    $domain = strtolower(trim($domain));
    $domain = preg_replace('/^http:\/\//i', '', $domain);
    $domain = preg_replace('/^www\./i', '', $domain);
    $domain = explode('/', $domain);
    $domain = trim($domain[0]);
 
    // split the TLD from domain name
    $_domain = explode('.', $domain);
    $lst = count($_domain)-1;
    $ext = $_domain[$lst];
 
    $servers = array(
        "biz" => "whois.neulevel.biz",
        "com" => "whois.internic.net",
        "us" => "whois.nic.us",
        "coop" => "whois.nic.coop",
        "info" => "whois.nic.info",
        "name" => "whois.nic.name",
        "net" => "whois.internic.net",
        "gov" => "whois.nic.gov",
        "edu" => "whois.internic.net",
        "mil" => "rs.internic.net",
        "int" => "whois.iana.org",
        "ac" => "whois.nic.ac",
        "ae" => "whois.uaenic.ae",
        "at" => "whois.ripe.net",
        "au" => "whois.aunic.net",
        "be" => "whois.dns.be",
        "bg" => "whois.ripe.net",
        "br" => "whois.registro.br",
        "bz" => "whois.belizenic.bz",
        "ca" => "whois.cira.ca",
        "cc" => "whois.nic.cc",
        "ch" => "whois.nic.ch",
        "cl" => "whois.nic.cl",
        "cn" => "whois.cnnic.net.cn",
        "cz" => "whois.nic.cz",
        "de" => "whois.nic.de",
        "fr" => "whois.nic.fr",
        "hu" => "whois.nic.hu",
        "ie" => "whois.domainregistry.ie",
        "il" => "whois.isoc.org.il",
        "in" => "whois.ncst.ernet.in",
        "ir" => "whois.nic.ir",
        "mc" => "whois.ripe.net",
        "to" => "whois.tonic.to",
        "tv" => "whois.tv",
        "ru" => "whois.ripn.net",
        "org" => "whois.pir.org",
        "aero" => "whois.information.aero",
        "nl" => "whois.domain-registry.nl"
    );
 
    if (!isset($servers[$ext])){
        die('Error: No matching nic server found!');
    }
 
    $nic_server = $servers[$ext];
 
    $output = '';
 
    // connect to whois server:
    if ($conn = fsockopen ($nic_server, 43)) {
        fputs($conn, $domain."\r\n");
        while(!feof($conn)) {
            $output .= fgets($conn,128);
        }
        fclose($conn);
    }
    else { die('Error: Could not connect to ' . $nic_server . '!'); }
 
    return $output;
}

Encode email in your website so that it doesn't get crawled by bots
Code:
    function encode_email($email='[email protected]', $linkText='Contact Us', $attrs ='class="emailencoder"' )  
    {  
        // remplazar aroba y puntos  
        $email = str_replace('@', '@', $email);  
        $email = str_replace('.', '.', $email);  
        $email = str_split($email, 5);  
      
        $linkText = str_replace('@', '@', $linkText);  
        $linkText = str_replace('.', '.', $linkText);  
        $linkText = str_split($linkText, 5);  
          
        $part1 = '<a href="ma';  
        $part2 = 'ilto:';  
        $part3 = '" '. $attrs .' >';  
        $part4 = '</a>';  
      
        $encoded = '<script type="text/javascript">';  
        $encoded .= "document.write('$part1');";  
        $encoded .= "document.write('$part2');";  
        foreach($email as $e)  
        {  
                $encoded .= "document.write('$e');";  
        }  
        $encoded .= "document.write('$part3');";  
        foreach($linkText as $l)  
        {  
                $encoded .= "document.write('$l');";  
        }  
        $encoded .= "document.write('$part4');";  
        $encoded .= '</script>';  
      
        return $encoded;  
    }

Force file download through PHP - instead of getting opened inside the browser, the file gets downloaded as attachment


Code:
function force_download($file)  
{  
    if ((isset($file))&&(file_exists($file))) {  
       header("Content-length: ".filesize($file));  
       header('Content-Type: application/octet-stream');  
       header('Content-Disposition: attachment; filename="' . $file . '"');  
       readfile("$file");  
    } else {  
       echo "No file selected";  
    }  
}


resize an Image with PHP


Code:
function resize_image($filename, $tmpname, $xmax, $ymax)  
{  
    $ext = explode(".", $filename);  
    $ext = $ext[count($ext)-1];  
  
    if($ext == "jpg" || $ext == "jpeg")  
        $im = imagecreatefromjpeg($tmpname);  
    elseif($ext == "png")  
        $im = imagecreatefrompng($tmpname);  
    elseif($ext == "gif")  
        $im = imagecreatefromgif($tmpname);  
      
    $x = imagesx($im);  
    $y = imagesy($im);  
      
    if($x <= $xmax && $y <= $ymax)  
        return $im;  
  
    if($x >= $y) {  
        $newx = $xmax;  
        $newy = $newx * $y / $x;  
    }  
    else {  
        $newy = $ymax;  
        $newx = $x / $y * $newy;  
    }  
      
    $im2 = imagecreatetruecolor($newx, $newy);  
    imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);  
    return $im2;   
}

Detect if a request has been made through AJAX ( important for secure Ajax applications)

Code:
function is_ajax(){
return empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}


A class that spins Spintax'd content
(See my post here for the full script:http://www.blackhatworld.com/blackh...ntent-generator-nested-spintax-supported.html )


Code:
class Randomizer {
 
    public function process( $text ) {
        return preg_replace_callback('/\{(((?>[^\{\}]+)|(?R))*)\}/x', array( $this, 'replace' ), $text );
    }
 
    public function replace( $text ) {
        $text = $this->process( $text[ 1 ] );
        $parts = explode( '|', $text );
        $part = $parts[ array_rand( $parts ) ];
        return $part;
    }
 
}

More coming soon...
 
Last edited:
Thanks a lot for all those functions !

I hope I will soon be able to post some of mine.
 
Couldnt leave this thread without giving it a nice bump. Awesome share. Being a PHP coder, some of the snippets you have shared will come handy, but most of the people, including me likes to code things up to our own liking unless it is complex. Arent all coders like that he heh.

String to Boolean was worth a laugh, with all those nope,nop,nah listed. :D
 
Back
Top