вторник, 26 марта 2013 г.

[PHP] Useful code snippets

Email PHP errors instead of displaying it

By default, most servers are set to display an error message when an error occured in one of your script. For security reasons, you may want to get an email with the error, instead of displaying it to the public.
// Our custom error handler
function nettuts_error_handler($number, $message, $file, $line, $vars){
 $email = "
  An error ($number) occurred on line
  $line and in the file: $file.
  

$message 

";

 $email .= "
" . print_r($vars, 1) . "
"; $headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Email the error to someone... error_log($email, 1, 'you@youremail.com', $headers); // Make sure that you decide how to respond to errors (on the user's side) // Either echo an error message, or kill the entire project. Up to you... // The code below ensures that we only "die" if the error was more than // just a NOTICE. if ( ($number !== E_NOTICE) && ($number < 2048) ) { die("There was an error. Please try again later."); } } // We should use our custom function to handle errors. set_error_handler('nettuts_error_handler'); // Trigger an error... (var doesn't exist) echo $somevarthatdoesnotexist; 

Detect location by IP

Here is an useful code snippet to detect the location of a specific IP. The function below takes one IP as a parameter, and returns the location of the IP. If no location is found, UNKNOWN is returned.
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('{
  • City : ([^<]*)
  • }i', $content, $regs) ) { $city = $regs[1]; } if ( preg_match('{
  • State/Province : ([^<]*)
  • }i', $content, $regs) ) { $state = $regs[1]; } if( $city!='' && $state!='' ){ $location = $city . ', ' . $state; return $location; }else{ return $default; } }

    Display Facebook fans count in full text

    Want to display how many Facebook fans do you have, in full text, on your blog? It’s very easy using the following snippet:
    function fb_fan_count($facebook_name){
        // Example: https://graph.facebook.com/digimantra
        $data = json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name));
        echo $data->likes;
    }

    Get info about your memory usage

    In order to optimize your scripts, you may definitely want to know how many amount of RAM they use on your server. This snippet will check memory and then print initial, final and peak usages.
    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
    */