PHP 12 functions of common functions

demo1.php

<?php
header('Content-Type: text/html; charset=utf-8');
//PHP encryption and decryption
function encryptDecrypt($key, $string, $decrypt){
    if($decrypt){
        $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "12");
        return $decrypted;
    }else{
        $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
        return $encrypted;
    }
}
//encryption:
echo encryptDecrypt('demo', '网址:onestopweb.iteye.com',0),'<br>';
// decrypt:
echo encryptDecrypt('demo', 'lONfy9/i2RmCh31P/cKFfM6Jd90ijfg0rhJr1GihF+o=',1);

/* output effect:
 * lONfy9/i2RmCh31P/cKFfM6Jd90ijfg0rhJr1GihF+o=
 * URL: onestopweb.iteye.com
 * */

 

demo2.php

<?php
//PHP generates random string
function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}
echo generateRandomString(20);

/* output effect:
 * 4e7ficXJk0jMvDQcCgZ8
 * */

 

demo3.php

<?php
//PHP gets the file extension (suffix)
function getExtension($filename){
    $myext = substr($filename, strrpos($filename, '.'));
    return str_replace('.','',$myext);
}
$filename = 'xxx.dd.gif';
echo getExtension($filename);

/* output effect:
 * gif
 * */

 

demo4.php

<?php
//PHP get file size and format
function formatSize($size) {
    $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
    if ($size == 0) {
        return('n/a');
    } else {
        return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]);
    }
}
$thefile = filesize('demo.rar');
echo formatSize($thefile);

/* output effect:
 * 114.14 KB
 * */

 

demo5.php

<?php
header('Content-Type: text/html; charset=utf-8');
//PHP replace label characters
function stringParser($string,$replacer){
    $result = str_replace(array_keys($replacer), array_values($replacer),$string);
    return $result;
}
$string = 'Who asks you to read, the fragrance floats when the water falls. ';
$replace_array = array('Read' => 'Watch', 'Jun' => 'You', 'Float' => 'Sink');

echo stringParser($string,$replace_array);

/* output effect:
 * See who asks you to chant, the water falls and the fragrance fades away.
 * */

 

demo6.php

<?php
//PHP lists the file names in the directory
function listDirFiles($DirPath){
    if($dir = opendir($DirPath)){
        while(($file = readdir($dir))!== false){
            if(!is_dir($DirPath.$file))
            {
                echo "filename: $file<br />";
            }
        }
    }
}
listDirFiles('aaa');

/* output effect:
 * filename: bbb
 * filename: ccc
 * */

 

demo7.php

<?php
//PHP gets the current page URL
//The following function can get the URL of the current page, whether it is http or https.
function curPageURL() {
    $ pageURL = 'http';
    if (!isset($_SERVER['HTTPS'])) {$pageURL .= "s";}
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    }
    return $ pageURL;
}
echo curPageURL();

/* output effect:
 * http://192.168.0.180:84/demo7.php
 * */

 

demo8.php

<?php
//PHP force download file
//Sometimes we don't want the browser to open the file directly, such as PDF file, but to download the file directly
//Then the following function can force the download of the file, the application/octet-stream header type is used in the function.
function download($filename){
    if ((isset($filename))&&(file_exists($filename))){
        header("Content-length: ".filesize($filename));
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        readfile("$filename");
    } else {
        echo "Looks like file does not exist!";
    }
}
download('demo.rar');

/* output effect:
 * Directly download the specified file
 * */

 

demo9.php

<?php
header('Content-Type: text/html; charset=utf-8');
//PHP intercepts the length of the string
//How many characters are exceeded, the length of the excess is represented by ...
function cutStr($string, $sublen, $start = 0, $code = 'UTF-8'){
    if($code == 'UTF-8'){
        $ pa = "/ [\ x01- \ x7f] | [\ xc2- \ xdf] [\ x80- \ xbf] | \ xe0 [\ xa0- \ xbf] [\ x80- \ xbf] | [\ xe1- \ xef] [\ x80- \ xbf] [\ x80- \ xbf] | \ xf0 [\ x90- \ xbf] [\ x80- \ xbf] [\ x80- \ xbf] | [\ xf1- \ xf7] [\ x80- \ xbf] [\ x80- \ xbf] [\ x80- \ xbf] / ";
        preg_match_all($pa, $string, $t_string);

        if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."...";
        return join('', array_slice($t_string[0], $start, $sublen));
    }else{
        $start = $start*2;
        $sublen = $sublen*2;
        $strlen = strlen($string);
        $tmpstr = '';

        for($i=0; $i<$strlen; $i++){
            if($i>=$start && $i<($start+$sublen)){
                if(ord(substr($string, $i, 1))>129){
                    $tmpstr.= substr($string, $i, 2);
                }else{
                    $tmpstr.= substr($string, $i, 1);
                }
            }
            if(ord(substr($string, $i, 1))>129) $i++;
        }
        if(strlen($tmpstr)<$strlen ) $tmpstr.= "...";
        return $tmpstr;
    }
}
$str = "Who is reading to ask the king to recite, the water will fall and the fragrance will float.";
echo cutStr($str,10);

/* output effect:
 * Read who asks you to recite, the fragrance of water falls...
 * */

 

demo10.php

<?php
//PHP gets the real IP of the client
function getIp() {
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
        $ip = getenv("HTTP_CLIENT_IP");
        else
            if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
                $ip = getenv("HTTP_X_FORWARDED_FOR");
                else
                    if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
                        $ip = getenv("REMOTE_ADDR");
                        else
                            if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
                                $ip = $_SERVER['REMOTE_ADDR'];
                                else
                                    $ip = "unknown";
                                    return ($ip);
}
echo getIp();

/* output effect:
 * 192.168.0.180
 * */

 

demo11.php

<?php
header('Content-Type: text/html; charset=utf-8');
//PHP page prompts and jumps
function message($msgTitle,$message,$jumpUrl){
    $str = '<!DOCTYPE HTML>';
    $str .= '<html>';
    $str .= '<head>';
    $str .= '<meta charset="utf-8">';
    $str .= '<title>Page Tips</title>';
    $str .= '<style type="text/css">';
    $str .= '*{margin:0; padding:0}a{color:#369; text-decoration:none;}a:hover{text-decoration:underline}body{height:100%; font:12px/18px Tahoma, Arial,  sans-serif; color:#424242; background:#fff}.message{width:450px; height:120px; margin:16% auto; border:1px solid #99b1c4; background:#ecf7fb}.message h3{height:28px; line-height:28px; background:#2c91c6; text-align:center; color:#fff; font-size:14px}.msg_txt{padding:10px; margin-top:8px}.msg_txt h4{line-height:26px; font-size:14px}.msg_txt h4.red{color:#f30}.msg_txt p{line-height:22px}';
    $str .= '</style>';
    $str .= '</head>';
    $str .= '<body>';
    $str .= '<div>';
    $str .= '<h3>'.$msgTitle.'</h3>';
    $str .= '<div>';
    $str .= '<h4>'.$message.'</h4>';
    $str .= '<p>The system will automatically jump after <span style="color:blue;font-weight:bold">3</span> seconds, if you don't want to wait, just click <a href="{ $jumpUrl}">here</a> jump</p>';
    $str .= "<script>setTimeout('location.replace(\'".$jumpUrl."\')',2000)</script>";
    $str .= '</div>';
    $str .= '</div>';
    $str .= '</body>';
    $str .= '</html>';
    echo $str;
}
message('Operation prompt', 'Operation successful!','http://onestopweb.iteye.com/');

/* output effect:
 * Operation tips
 * Successful operation!
 * The system will automatically jump after 3 seconds, if you don't want to wait, just click here to jump
 * */

 

demo12.php

<?php
//PHP calculation time
function changeTimeType($seconds) {
    if ($seconds > 3600) {
        $hours = intval($seconds / 3600);
        $minutes = $seconds % 3600;
        $time = $hours . ":" . gmstrftime('%M:%S', $minutes);
    } else {
        $time = gmstrftime('%H:%M:%S', $seconds);
    }
    return $time;
}
$seconds = 23;
echo changeTimeType($seconds);

/* output effect:
 * 00:00:23
 * */

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326788405&siteId=291194637
Recommended