preface

I remember clearly who said in my ear: “PHP is the best in the world language”, anyway, I didn’t say that ha (not straight gas still zhuang), I have heard this speech, after all, I am timid, where dare say such things in public, about “who is the best language speech”, long before, is the IT industry in too much of a bloody fruitless debate, we don’t do things, honestly moved brick…

Ok, shrimping is finished, start to talk about business, I will continue to write some PHP development in some practical custom functions, convenient to use friends, can quickly develop and use.

Return formatting time

In the development process, we always encounter some problems in displaying the time, sometimes need to display the year – month – day, sometimes need to display the year – month – day. $date($time, ‘y-m-d H: I :s’); $time ($time,’ y-m-d H: I :s’); $time ($time, ‘y-m-d H: I :s’); Call time_format($time) to pass in the timestamp.

/** * returns the formatting time * @param int$timeTimestamp * @param string$formatTime format * @return bool|string
 */
function time_format($time = 0, $format = ' ') {// Default time formatif (empty($format)) {
        $format = 'Y-m-d H:i:s';
    }
    $format_time = date($format.$time);
    return $format_time;
}
Copy the code

Formatted number

When dealing with the format of numbers, I think we have not encountered less, and even because some data shows the number is not formatted and has been tested for bugs? Anyway, I was caught in a test and had to change it, like: $number_format($number, 2, ‘.’, ‘,’); $number ($number, 2, ‘.’, ‘,’); $number = number_format_plus($number)

/** * returns a formatted number * @param int$numberThe number to be formatted * @param int$decimalsKeep decimal digits, default 2 * @param string$dec_pointInteger and decimal separator * @param string$thousands_sepThe integer part reads the delimiter * @ every three digitsreturn string
 */
function number_format_plus($number = 0, $decimals = 2, $dec_point = '. '.$thousands_sep = ', ')
{
    $format_num = '0.00';
    if (is_numeric($number)) {
        $format_num = number_format($number.$decimals.$dec_point.$thousands_sep);
    }
    return $format_num;
}
Copy the code

Change the number of RMB from lowercase to uppercase

RMB transfer to uppercase, this kind of general contract files will encounter more, because I have come into contact with some contract files in my previous work, so I have been using this function, good things have to share, of course, in case you also just need it

/** * switch from lowercase to uppercase * @param string$numberValue of RMB * @param string$int_unitCurrency unit, default"Yuan", some requirements may be"Circle"
 * @param bool $is_roundWhether decimals are rounded * @param bool$is_extra_zeroWhether to append zeros to integers that end in zeros, such as 1960.30 * @return string
 */
function rmb_format($money = 0, $int_unit = '元'.$is_round = true.$is_extra_zero = false) {// Non-numeric, return as-isif(! is_numeric($money)) {
        return $money; } // Cut the number into two pieces$parts = explode('. '.$money, 2);
    $int = isset($parts[0])? strval($parts[0]) : '0';
    $dec = isset($parts[1])? strval($parts[1]) : ' '; // If there are more than 2 decimal places after the decimal point, it is cut without rounding, otherwise it is processed$dec_len = strlen($dec);
    if (isset($parts&& [1])$dec_len > 2) {
        $dec = $is_round ? substr(strrchr(strval(round(floatval("0." . $dec), 2)), '. '), 1) : substr($parts[1], 0, 2); } // When number is 0.001, the amount after the decimal point is 0if (empty($int) && empty($dec)) {
        return 'zero'; } / / definition$chs = ['0'.'one'.'. '.'叁'.'boss'.'wu'.'land'.'pure'.'捌'.'nine'];
    $uni = [' '.'pick up'.'or'.'仟'];
    $dec_uni = ['Angle'.'points'];
    $exp = [' '.'万'];
    $res = ' '; // The integer part is found from right to leftfor ($i = strlen($int) - 1, $k = 0; $i> = 0;$k{+ +)$str = ' '; // I is always subtractingfor ($j = 0; $j < 4 && $i> = 0;$j+ +,$i--) {// add units after non-zero numbers$u = $int{$i} > 0?$uni [$j] : ' ';
            $str = $chs [$int{$i}].$u . $str; } // remove the trailing 0$str = rtrim($str.'0'); // Replace multiple consecutive zeros$str = preg_replace("/ /" 0 +."Zero".$str);
        if(! isset($exp [$k])) {// Build units$exp [$k] = $exp [$k- 2).'亿';
        }
        $u2 = $str! =' ' ? $exp [$k] : ' ';
        $res = $str . $u2 . $res; } // If the decimal part is not 00, you need to do something about it$dec = rtrim($dec.'0'); // Find the decimal part from left to rightif(! empty($dec)) {
        $res. =$int_unit; // Whether to append 0 to a number ending in 0 in the integer part. Some systems require thisif ($is_extra_zero) {
            if (substr($int, 1) = = ='0') {
                $res. ='zero'; }}for ($i = 0, $cnt = strlen($dec); $i < $cnt; $i++) {// Add units after non-zero numbers$u = $dec{$i} > 0?$dec_uni [$i] : ' ';
            $res. =$chs [$dec{$i}].$u;
            if ($cnt= = 1)$res. ='the whole'; } // remove the trailing 0$res = rtrim($res.'0'); // Replace multiple consecutive zeros$res = preg_replace("/ /" 0 +."Zero".$res);
    } else {
        $res. =$int_unit . 'the whole';
    }
    return $res;
}
Copy the code

Generating short urls

Domestic also have a lot of short url generation interface, but found that the short URL interface provided by tinyurl.com abroad is very convenient to use, directly need to pass into a URL can generate a short link, as for the safety and speed performance of what, it said, I before, also have written an article about sina short URL generation, If you are interested, you can take a look at the article entry – Sina Weibo API to generate short links

/** * get the short url * @param string$urlOriginal url * @return string
 */
function get_short_url($url = ' ') {// Directly request the address of the third-party interface to obtain the short URL$api_url = 'http://tinyurl.com/api-create.php?url=';
    $short_url = file_get_contents($api_url . $url);
    return $short_url;
}
Copy the code

Obtain the real IP address of the user

In need to analyze the user behavior and operation log, will certainly encounter need to get the IP address of the user’s demand, because in the Internet, can locate the users, the most direct the most effective is the IP address, of course, also some people use a proxy or other ways to modify IP address, cause so that to obtain IP address may not be accurate, but normal, This method is sufficient to obtain the user’s IP address.

/** * Obtain the real IP address of the user * @return mixed
 */
function get_real_ip()
{
    if(! empty($_SERVER['HTTP_CLIENT_IP']) {$ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (! empty($_SERVER['HTTP_X_FORWARDED_FOR']) {$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
Copy the code

Export excel table data

We commonly used to export Excel table library class has PHPExcel and so on, but do not want to use any library class, can directly export Excel table data, of course, there is a way, that is to directly use HTML table to generate table data and export.

/** * Export excel table data * @param array$dataTable data, a two-dimensional array * @param array$titleFirst line title, one-dimensional array * @param String$filenameDownload file name */function export_excel($data= [].$title= [].$filename = ' ') {// The default file name is timestampif (empty($filename)) {
        $filename= time(); } // Define output header information header("Content-type:application/octet-stream; charset=GBK");
    header("Accept-Ranges:bytes");
    header("Content-type:application/vnd.ms-excel");
    header("Content-Disposition:attachment; filename=" . $filename . ".xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    ob_start();
    echo "
       
      
       \n"
      
; // To start exporting XLS, write the header firstif(! empty($title)) { foreach ($title as $k= >$v) { $title[$k] = iconv("UTF-8"."GBK//IGNORE".$v); } $title = "<td>" . implode("</td>\t<td>".$title)."</td>"; echo "<tr>$title</tr>\n"; } // write table data againif(! empty($data)) { foreach ($data as $key= >$val) { foreach ($val as $ck= >$cv) { if (is_numeric($cv) && strlen($cv) < 12) { $data[$key] [$ck] = '<td>' . mb_convert_encoding($cv."GBK"."UTF-8")."</td>"; } else { $data[$key] [$ck] = ' ' . iconv("UTF-8"."GBK//IGNORE".$cv)."</td>"; }}$data[$key] = "<tr>" . implode("\t".$data[$key])."</tr>"; } echo implode("\n".$data); } echo "</table>"; ob_flush(); exit; } Copy the code

Download files (support resumable breakpoint)

There are times when we download files from the Internet, but sometimes to download a large file, download all of a sudden to half or finishing, suddenly to a network failure, lead to download suspended interrupted, if later network restored, you will start to download, have to ‘criticisms that kind of, but, if the network back, You can continue to the location of the interrupt before continue to download from the network, is happy, of course, we all hope so, but some “dirty” developers, might, won’t make you happy, so, do you want to be when I do not make people happy “dirty” developers or do a good man, urge everyone to do a good man, ha, ha, ha

/** * support breakpoint continuation, download file * @param string$fileDownload the full file path */function download_file_resume($file) {// Check if the file existsif(! is_file($file)) {
        die("Illegal file download!"); } // Open the file$fp = fopen("$file"."rb"); // Get the file size$size = filesize($file); // Get the file name$filename = basename($file); // Get the file extension$file_extension = strtolower(substr(strrchr($filename."."), 1)); // Specify the output browser format according to the extension switch ($file_extension) {
        case "exe":
            $ctype = "application/octet-stream";
            break;
        case "zip":
            $ctype = "application/zip";
            break;
        case "mp3":
            $ctype = "audio/mpeg";
            break;
        case "mpg":
            $ctype = "video/mpeg";
            break;
        case "avi":
            $ctype = "video/x-msvideo";
            break;
        default:
            $ctype = "application/force-download"; } // Common header information header("Cache-Control:");
    header("Cache-Control: public");
    header("Content-Type: $ctype");
    header("Content-Disposition: attachment; filename=$filename");
    header("Accept-Ranges: bytes"); / / if you have$_SERVER['HTTP_RANGE'] parameterif (isset($_SERVER['HTTP_RANGE'])) {// Connect again after breakpoint$_SERVER['HTTP_RANGE'] the value of the list ($a.$range) = explode("=".$_SERVER['HTTP_RANGE']);
        str_replace($range."-".$range); // Total bytes of the file$size2 = $size- 1; // Get the length of the next download$new_length = $size2 - $range;
        header("HTTP / 1.1 206 Partial Content"); // Enter the length header("Content-Length: $new_length");
        header("Content-Range: bytes $range$size2/$size"); // set pointer position fseek($fp.$range);
    } else{// First connection download$size2 = $size - 1;
        header("Content-Range: bytes 0-$size2/$size"); // Output length header("Content-Length: " . $size); } // Unreal outputwhile(! feof($fp) {// Set the maximum file execution time set_time_limit(0); // Output fileprint(fread($fp, 1024 * 8)); // Output buffer flush(); ob_flush(); } fclose($fp);
    exit;
}
Copy the code

The last

Well, I will share these functions in the first chapter, and I will update other practical functions gradually. If you have other interesting and useful functions, you are welcome to share them, and we can learn and communicate together. By the way, if there is something wrong or wrong, please point it out and I will try to improve it. Thank you.