Complete website in Rs. 5,000 with Free Hosting & Domain. Offer ends in  00:00:00
Back to Blog

PHP Tips, Tricks and Code Snippets

Feb 8, 2022 Updated: Feb 8, 2022

Change memory limit in PHP

ini_set('memory_limit', '-1');

Extract the filename from a string without the file extension in PHP

$string = "path/to/file.txt";
$filename = basename($string, "." . pathinfo($string, PATHINFO_EXTENSION));

echo $filename;
/* Output:
file
*/

Capitalise first character of each word in PHP

echo ucwords(strtolower($string));

How to Convert String to Slug in PHP

Use the function below to convert string to URL friendly slug. I used this function to create filename that can be send as attachments with emails becauase filenames with spaces do not mostly send properly.

Here we are:

  1. removing spaces
  2. converting uppercase letters to lowercase letters
  3. replacing accented characters by equivalent standard characters and a bit more.
function createSlug($str, $delimiter = '-'){
    $slug = strtolower(trim(preg_replace('/[\s-]+/', $delimiter, preg_replace('/[^A-Za-z0-9-]+/', $delimiter, preg_replace('/[&]/', 'and', preg_replace('/[\']/', '', iconv('UTF-8', 'ASCII//TRANSLIT', $str))))), $delimiter));
    return $slug;
}

Convert timestap to time ago in PHP

Convert a time string to something like 2 minutes ago, 4 weeks ago, etc.

function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}

Input can be any of the supported formats for php, check the link below for more details. https://www.php.net/manual/en/datetime.formats.php

echo time_elapsed_string('2013-05-01 00:22:35');
echo time_elapsed_string('@1367367755'); # timestamp input
echo time_elapsed_string('2013-05-01 00:22:35', true);

/*
Output

4 months ago
4 months ago
4 months, 2 weeks, 3 days, 1 hour, 49 minutes, 15 seconds ago
*/

Date formating https://www.php.net/manual/en/datetime.format.php

Make text between asterisk bold

echo preg_replace('#\*{2}([^*]*)\*{2}#', '<b>$1</b>', '**Hello World** of PHP');

Local PHP Server

Source: https://stackoverflow.com/questions/1678010/php-server-on-local-machine

php -S localhost:8080

For quiet server that does not logs in console, use -q with the command.

php -S localhost:8080 -q

Two way encription

function quick_twoway_encryption($stringToHandle = "", $encryptDecrypt = 'e'){
    $output = null; // Set default output value
    // Set secret keys
    $secret_key = 'P}%-o)^3*'; // change this!
    $secret_iv = 'uY=T"4%:@'; // change this!
    $key = hash('sha256',$secret_key);
    $iv = substr(hash('sha256',$secret_iv),0,16);
    // Check whether encryption or decryption
    if($encryptDecrypt == 'e'){
        // We are encrypting
        $output = base64_encode(openssl_encrypt($stringToHandle,"AES-256-CBC",$key,0,$iv));
    }else if($encryptDecrypt == 'd'){
        // We are decrypting
        $output = openssl_decrypt(base64_decode($stringToHandle),"AES-256-CBC",$key,0,$iv);
    }
    return $output; // Return the final value
}
Contact

Got A Question For Us?

Feel free to ask anything directly on call or fill the form and we will contact back within few hours.