Useful PHP Snippets
PHP is the most widely used language when it comes to server-side programming. If you are a beginner or an advanced programmer and you use it in your work – our article will be very useful for you. Because today I want to bring to your attention a small collection of quite interesting and useful php snippets. They are designed as finished functions, and you can easily transfer them in a class or a library file for later use in your projects.
Calculate the distance between two coordinates
When we need to measure the distance between two points, we may use one of the following formulas: Haversine formula or Vincenty’s formula. There are two appropriately named functions:
function haversineGreatCircleDistance($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371000) { // convert from degrees to radians $latFrom = deg2rad($latitudeFrom); $lonFrom = deg2rad($longitudeFrom); $latTo = deg2rad($latitudeTo); $lonTo = deg2rad($longitudeTo); $latDelta = $latTo - $latFrom; $lonDelta = $lonTo - $lonFrom; $angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) + cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2))); return $angle * $earthRadius; } public static function vincentyGreatCircleDistance($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371000) { // convert from degrees to radians $latFrom = deg2rad($latitudeFrom); $lonFrom = deg2rad($longitudeFrom); $latTo = deg2rad($latitudeTo); $lonTo = deg2rad($longitudeTo); $lonDelta = $lonTo - $lonFrom; $a = pow(cos($latTo) * sin($lonDelta), 2) + pow(cos($latFrom) * sin($latTo) - sin($latFrom) * cos($latTo) * cos($lonDelta), 2); $b = sin($latFrom) * sin($latTo) + cos($latFrom) * cos($latTo) * cos($lonDelta); $angle = atan2(sqrt($a), $b); return $angle * $earthRadius; }
Both functions use the following parameters:
- float $latitudeFrom – Latitude of start point in [deg decimal]
- float $longitudeFrom – Longitude of start point in [deg decimal]
- float $latitudeTo – Latitude of target point in [deg decimal]
- float $longitudeTo – Longitude of target point in [deg decimal]
- float $earthRadius – Mean earth radius in miles
Functions return – (float) Distance between points in miles (same as earthRadius)
Email debug PHP errors
function errorHandler($sMessage = '', $aVars = array()) { $sScript = $_SERVER['PHP_SELF']; $sParams = print_r($_REQUEST, true); $sVars = print_r($aVars, true); $aBackTrace = debug_backtrace(); unset($aBackTrace[0]); $sBackTrace = print_r($aBackTrace, true); $sExplanation = <<<EOF <p>Additional explanation: {$sMessage}</p> <p>Additional variables: <pre>{$sVars}</pre></p><hr /> <p>Called script: {$sScript}</p> <p>Request parameters: <pre>{$sParams}</pre></p><hr /> <p>Debug backtrace:</p> <pre>{$sBackTrace}</pre> EOF; $sHeader = "Subject: Error occurred\r\nContent-type: text/html; charset=UTF-8\r\n"; error_log($sExplanation, 1, '[email protected]', $sHeader); }
This function is to email you about all occured errors on your website (this is much better instead of displaying it to the public). There are only two optional params:
- string $sMessage – Custom message
- array $aVars – Additional array to be sent by email
Convert PDF to JPG
function pdfToJpg($pdf, $jpg) { $im = new Imagick(); $im->setResolution(300,300); $im->readimage($pdf); $im->setImageFormat('jpeg'); $im->writeImage($jpg); $im->clear(); $im->destroy(); }
This function is to convert PDF files into image file. It takes two params:
- string $pdf – Path to the initial PDF file
- string $jpg – Path to the image file
Get age by birth date
function getAge($birthdate = '0000-00-00') { if ($birthdate == '0000-00-00') return 'Unknown'; $bits = explode('-', $birthdate); $age = date('Y') - $bits[0] - 1; $arr[1] = 'm'; $arr[2] = 'd'; for ($i = 1; $arr[$i]; $i++) { $n = date($arr[$i]); if ($n < $bits[$i]) break; if ($n > $bits[$i]) { ++$age; break; } } return $age; }
This function is to get age by given birthday (format: YYYY-MM-DD).
Extract files from ZIP archive
function unzipArchive($file, $destinationFolder){ // create ZipArchive object $zip = new ZipArchive() ; // open archive if ($zip->open($file) !== TRUE) { die ('Could not open archive'); } // extract it's content to destination folder $zip->extractTo($destinationFolder); // close archive $zip->close(); }
This function takes two parameters:
- string $file – Path to the initial ZIP file
- string $destinationFolder – Path to the destination folder for files
Conclusion
Today is all, thank you for your attention, do not forget to visit us from time to time.
if pdf file pages are more than one will imagemagick render them as 1 image. or how can we create each PDF page to new image.
Hi John,
You may try to use writeImages instead of writeImage
How about:
function getAge($birthday) {
return intval((new DateTime($birthday))->diff(new DateTime("now"), true)->format("%y"));
}
Hi Viktoras,
Indeed, it may also work.