有用PHP代码段

Useful PHP Snippets
Useful PHP Snippets

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.

有用PHP代码段 PHP是服务器端编程中使用最广泛的语言。 如果您是初学者或高级程序员,并且在工作中使用它-我们的文章对您非常有用。 因为今天我想引起您的注意,其中包括一些非常有趣和有用的php代码片段。 它们被设计为完成函数,您可以轻松地将它们转移到类或库文件中,以供以后在项目中使用。

计算两个坐标之间的距离 (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:

当我们需要测量两点之间的距离时,可以使用以下公式之一: Haversine公式Vincenty公式 。 有两个适当命名的函数:


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;
}

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 $ latitudeFrom –起点的纬度,以[度十进制为单位]
  • float $longitudeFrom – Longitude of start point in [deg decimal]

    float $ longitudeFrom –起点的经度,以[度十进制为单位]
  • float $latitudeTo – Latitude of target point in [deg decimal]

    float $ latitudeTo-目标点的纬度,以[度十进制为单位]
  • float $longitudeTo – Longitude of target point in [deg decimal]

    float $ longitudeTo –目标点的经度,以[度十进制为单位]
  • float $earthRadius – Mean earth radius in miles

    float $ earthRadius –平均地球半径(以英里为单位)

Functions return – (float) Distance between points in miles (same as earthRadius)

函数返回-(浮动)点之间的距离(以英里为单位)(与earthRadius相同)

电子邮件调试PHP错误 (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, 'admin@example.com', $sHeader);
}

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, 'admin@example.com', $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

    字符串$ sMessage –自定义消息
  • array $aVars – Additional array to be sent by email

    数组$ aVars –通过电子邮件发送的附加数组
将PDF转换成JPG (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();
}

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:

此功能是将PDF文件转换为图像文件。 它需要两个参数:

  • string $pdf – Path to the initial PDF file

    字符串$ pdf –初始PDF文件的路径
  • string $jpg – Path to the image file

    字符串$ jpg –图像文件的路径
通过出生日期获取年龄 (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;
}

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).

此功能用于按给定的生日获取年龄(格式:YYYY-MM-DD)。

从ZIP存档中提取文件 (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();
}

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

    字符串$ file –初始ZIP文件的路径
  • string $destinationFolder – Path to the destination folder for files

    字符串$ destinationFolder –文件目标文件夹的路径

结论 (Conclusion)

Today is all, thank you for your attention, do not forget to visit us from time to time.

今天就是一切,谢谢您的关注,不要忘了不时访问我们。

翻译自: https://www.script-tutorials.com/useful-php-snippets/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值