Useful PHP Snippets

# Useful PHP Snippets

4 46685  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
\$latDelta = \$latTo - \$latFrom;
\$lonDelta = \$lonTo - \$lonFrom;
\$angle = 2 * asin(sqrt(pow(sin(\$latDelta / 2), 2) +
cos(\$latFrom) * cos(\$latTo) * pow(sin(\$lonDelta / 2), 2)));
}
public static function vincentyGreatCircleDistance(\$latitudeFrom, \$longitudeFrom, \$latitudeTo, \$longitudeTo, \$earthRadius = 6371000) {
// convert from degrees to radians
\$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);
}
```

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]

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);
\$sBackTrace = print_r(\$aBackTrace, true);
\$sExplanation = <<<EOF
<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";
}
```

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->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 - 1;
\$arr = 'm';
\$arr = '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.

### 9 Best PHP Frameworks to Build Awesome Responsive Websites

0 23940

1. John Falling

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.

• Andrey

Hi John,
You may try to use writeImages instead of writeImage

2. Viktoras

` function getAge(\$birthday) { return intval((new DateTime(\$birthday))->diff(new DateTime("now"), true)->format("%y")); } `
• Andrey