Facebook

Thursday, November 5, 2015

PHP Tips and Tricks - Handy


1. ini_set('memory_limit', '-1');
Usage: To temporarily set memory limit to unlimited

2. ini_set('memory_limit', '512M');
Usage: How to temporarily set memory limit to 512MB

3. set_time_limit(0);

4. ini_set('max_execution_time', 0);
Usage: How to temporarily set max execution time to infinite

5. error_reporting(E_ALL);
Usage: Report all PHP errors

6. error_reporting(0);
Usage: Turn off all error reporting

7. ini_set("display_errors", 1);
Usage: Run-time configuration

8.
function getClientIp()
{
    $ip = '';
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }

    return $ip;
}
Usage: Get user ip

/*
 *9.Generate accented seo friendly url
 */

function accented_seo_url($str) {
    mb_internal_encoding('UTF-8');
    $str = utf8_encode($str);

    $new_string = preg_replace('~[^\\pL\d]+~u', "-", ltrim(rtrim(($str))));

    return mb_strtolower($new_string);
}
Usage: Generate accented seo friendly url

10. header('Content-Type: text/html; charset=utf-8');
Usage: Set utf8 in header

11.
/*
* Get 2nd monday of the month
*/

//First monday of the month
$dt = new DateTime('first Monday of jan 2017');

//Second monday of the month
$interval = new DateInterval('P1W');
$next_week = $dt->add($interval);
echo $next_week->format('Y-m-d');
Usage: Get 2nd monday of the month. Example https://eval.in/716901
12.
/*
* Get 3rd tuesday of the month
*/

//First tuesday of the month
$dt = new DateTime('first Tuesday of jan 2017');

//Third Tuesday of the month
$interval = new DateInterval('P2W');
$next_week = $dt->add($interval);
echo $next_week->format('Y-m-d');
Usage: Get 3rd Tuesday of the month. Example https://eval.in/716901

No comments:

Post a Comment