thumbnail

Collection of useful PHP snippets


(1) Convert myanmar numbers to english numbers
This function can convert non-english number to english numbers
function changeToEngNumber($numbers){
  return str_replace(
    ["၀", "၁", "၂", "၃", "၄", "၅", "၆", "၇", "၈", "၉"],
    ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
    $numbers);
}

Syntax :
convertToEngNumber("၂၀၁၅-၂၀၁၉"); //Result : 2015-2019 

(2) Download file from web link
function downloadFile($webLink, $filePath){
  $ch = curl_init($webLink);
  $fp = fopen($filePath, 'wb');
  curl_setopt($ch, CURLOPT_FILE, $fp);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36');
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_exec($ch);
  curl_close($ch);
  fclose($fp);

  return $filePath;
}
Syntax :
downloadFile("https://www.example.com/my-photo.jpg", "C:/Users/User/Desktop/photo.jpg"); 

(3) Human readable file size (1.20 MB, 30.00 KB)
function readableFileSize($fileSize){
  $sizes = array('B', 'KB', 'MB', 'GB', 'TB');
  $i = 0;
  while($fileSize > 1024){
   $fileSize = $fileSize / 1024;
   $i++;
  }
  return number_format($fileSize, 2) .' '. $sizes[$i];
}
Syntax :
readableFileSize(filesize("C:/Users/User/Desktop/photo.jpg"));

(4) Check string contain in another string
function containString($searchTerm, $InString){
  return strpos($searchTerm, $InString) === 0;
}
Syntax :
containString("mango", "apple, orange, mango"); //Result : TRUE

(5) Multiline string in PHP
$textStr = <<<EOD
PHP is a popular general-purpose scripting language that is especially suited to web development.
Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world.
EOD;
(6) Send an email
<?php
 $to = 'someone@test.com';
 $subject = 'Here is subject';
 $message = 'This is long message';
 $headers = 'From: userfrom@test.com' . "\r\n" . 'Reply-To: userfrom@test.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion();
 mail($to, $subject, $message, $headers);

(7) Detect mobile device
function isMobileDevice(){
 return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
}
Syntax :
isMobileDevice(); //Result : TRUE if mobile device, otherwise, FALSE

(8) Create folder if not exist
function createFolder($folderPath){
 if (!file_exists($folderPath)){
  mkdir($folderPath, 0775, true);
 }
 return $folderPath;
}
Syntax :
createFolder("C:/TestFolder");

(9) Delete a file
unlink("C:/my-photo.jpg");

(10) Pretty DateTime
function timeAgo($timeAgo){
 $timeZone = new DateTimeZone('Asia/Singapore');
 $timeAgo = (new DateTime($timeAgo, $timeZone))->getTimestamp();
 $curTime = (new DateTime('now', $timeZone))->getTimestamp();
 $timeElapsed = $curTime - $timeAgo;
 $seconds = $timeElapsed ;
 $minutes = round($timeElapsed / 60 );
 $hours = round($timeElapsed / 3600);
 $days = round($timeElapsed / 86400 );
 $weeks = round($timeElapsed / 604800);
 $months = round($timeElapsed / 2600640 );
 $years = round($timeElapsed / 31207680 );
 
 // Seconds
 if($seconds <= 60){
  return "a moment ago";
 }
 //Minutes
 else if($minutes <= 60){
  return ($minutes == 1) ? "1 minute ago" : $minutes . " minutes ago";
 }
 //Hours
 else if($hours <= 24){
  return ($hours == 1) ? "1 hour ago" : $hours . " hours ago";
 }
 //Days
 else if($days <= 7){
  return ($days == 1) ? "yesterday" : $days . " days ago";
 }
 //Weeks
 else if($weeks <= 4.3){
  return ($weeks == 1) ? "one week ago" : $weeks . " weeks ago";
 }
 //Months
 else if($months <=12){
  return ($months == 1) ? "one month ago" : $months . " months ago";
 }
 //Years
 else{
  return ($years == 1) ? "one year ago" : $years . " years ago";
 }
}
Syntax :
timeAgo('2019-07-12T15:03:01.000Z');// Result : a moment ago
timeAgo('2019-06-15T15:03:01.000Z');// Result : 4 weeks ago

(11) AES 128 Encryption and Decryption
function encrypt($plainText, $key) {
 return base64_encode(openssl_encrypt($plainText, "aes-128-ecb", $key, OPENSSL_RAW_DATA));
}

function decrypt($encryptedText, $key) {
 return openssl_decrypt(base64_decode($encryptedText), "aes-128-ecb", $key, OPENSSL_RAW_DATA);
}
Syntax :
$encrypted = encrypt("Hello World!", "This is my key"); 
$decrypted = decrypt($encrypted, "This is my key");
echo "Encrypted : $encrypted";// Encrypted : P/W3C2v5A3wSPKAJk6JhVw==
echo "Decrypted : $decrypted";// Decrypted : Hello World!

No Comments