вторник, 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
    */

    
    

    четверг, 14 февраля 2013 г.

    [PHP] Заменить 2+ пробелов на "пусто"

    Просто записка:
    $string=preg_replace('/ {2,}/','',$string);
            /*  |          | ||     |   |_в $string
                |          | ||     |_на пустую строку
                |          | ||_и более раз
                |          | |_встреченный 2 
                |          |_пробел (только пробел, для табов и пр символов - \s
                |_заменить 
            */
    

    понедельник, 11 февраля 2013 г.

    Installing LessCSS on Gentoo Linux

    Here’s a short HOWTO on installing lesscss on Gentoo. As root, execute:
    emerge --sync (or skip this if you know you are relatively up-to-date)
    emerge rubygems
    gem install less
    gem install therubyracer 
    That’s all.

    понедельник, 10 декабря 2012 г.

    [STAT] Collectd - Установка, настройка, использование.

    Что это такое?

    Collectd - это небольшой демон, который каждые 10 секунд собирает статистку об использовании ресурсов системы. Есть возможность сбора статистики для нескольких хостов и отсылка её на сервер, который занимается отрисовкой красивых графиков.
    Основное отличие этого сборщика в том, что он работает по принципу push, а не poll/pull. Т.е. он "висит" и слушает, а сервера ему сами статистику присылают. :)

    Что мы будем делать?

    Что я хочу описать в этом посте:
    • Установка.
    • Настройка общая.
    • Настройка отдельных плагинов.
    • Настройка slave серверов, которые будут слать нам на главный сервер свою статистику работы.
    • Настройка нотификаций по email.
    По поводу последнего пункта -- это будет только то, что мне подходит и интересно, все представленные интерфейсы я рассматривать не буду.

    вторник, 27 ноября 2012 г.

    [apache] Изменяем маску созаваемых файлов и директорий под апачем

    Вот столкнулся с такой проблемой. Необходимо, чтобы скрипт при создании файла или директории делал ей права и на группу тоже. По умолчанию в апаче нельзя выставить umask, для этого надо поставить мод для апача отдельно:


    emerge www-apache/mod_umask
    

    Ну и потом в /etc/apache2/modules.d/mod_umask.conf раскомментируем нужную строчку. И конечно же перезапустим апач.

    Вот и все.

    четверг, 8 ноября 2012 г.

    Как отобразить на сайте содержимое DOC, RTF, PDF или ODT файла

    Google Docs оказывается позволяет встраивать свой вьювер на любую страницу вашего сайта в качестве iframe
    Пример просмотра файла http://example.com/file.pdf
    <iframe 
      src="http://docs.google.com/gview?url=http://example.com/file.pdf&embedded=true"
      style="width:600px; height:500px;" 
      frameborder="0" >
    </iframe>
    Поддерживаются форматы PDF, DOC, RTF и PDF

    среда, 7 ноября 2012 г.

    [JAVA] Аналог PHP функции implode для String collection

    Такая полезная функция как implode отсутствует в java.
    Исправим:

    import org.apache.commons.lang.StringUtils;
    
    public static String implodeArray(String[] inputArray, String glueString) {
    
        /** Output variable */
        String output = "";
        output = StringUtils.join( inputArray, glueString );
        return output;
    }