>  기사  >  백엔드 개발  >  매우 실용적인 PHP 기능 요약 및 배열

매우 실용적인 PHP 기능 요약 및 배열

伊谢尔伦
伊谢尔伦원래의
2016-11-26 16:11:26924검색

1. PHP 암호화 및 복호화

PHP 암호화 및 복호화 기능을 사용하면 일부 유용한 문자열을 암호화하여 데이터베이스에 저장할 수 있으며, 이 기능은 base64 및 MD5 암호화 및 복호화를 사용합니다. .

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

사용 방법은 다음과 같습니다.

//以下是将字符串“Helloweba欢迎您”分别加密和解密 
//加密: 
echo encryptDecrypt('password', 'Helloweba欢迎您',0); 
//解密: 
echo encryptDecrypt('password', 'z0JAx4qMwcF+db5TNbp/xwdUM84snRsXvvpXuaCa4Bk=',1);

2. PHP는 임의의 문자열을 생성합니다.

임의의 이름, 임시 비밀번호를 생성해야 합니다. 다음 함수를 사용합니다.

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

3. PHP는 파일 확장자(접미사)를 가져옵니다.

다음 기능을 사용하면 파일을 빠르게 가져올 수 있습니다. 확장자는 접미사입니다.

function getExtension($filename){ 
  $myext = substr($filename, strrpos($filename, &#39;.&#39;)); 
  return str_replace(&#39;.&#39;,&#39;&#39;,$myext); 
}

사용 방법은 다음과 같습니다.

$filename = &#39;我的文档.doc&#39;; 
echo getExtension($filename);

4. PHP는 파일 크기를 구하고 포맷합니다.

아래 함수를 사용하면 파일 크기를 구할 수 있습니다. 읽기 쉬운 KB, MB 및 기타 형식으로 변환합니다.

function formatSize($size) { 
    $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB"); 
    if ($size == 0) {  
        return(&#39;n/a&#39;);  
    } else { 
      return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]);  
    } 
}

사용 방법은 다음과 같습니다.

$thefile = filesize(&#39;test_file.mp3&#39;); 
echo formatSize($thefile);

5. PHP 태그 문자 교체

때때로 문자열과 템플릿 태그를 지정된 내용으로 교체해야 하는 경우가 있습니다. 다음 기능을 사용합니다.

function stringParser($string,$replacer){ 
    $result = str_replace(array_keys($replacer), array_values($replacer),$string); 
    return $result; 
}

사용 방법은 다음과 같습니다.

$string = &#39;The {b}anchor text{/b} is the {b}actual word{/b} or words used {br}to describe the link {br}itself&#39;; 
$replace_array = array(&#39;{b}&#39; => &#39;<b>&#39;,&#39;{/b}&#39; => &#39;</b>&#39;,&#39;{br}&#39; => &#39;<br />&#39;); 
echo stringParser($string,$replace_array);

6. PHP는 디렉터리에 파일 이름을 나열합니다.

아래의 모든 파일에 대해 다음 코드를 사용합니다.

function listDirFiles($DirPath){ 
    if($dir = opendir($DirPath)){ 
         while(($file = readdir($dir))!== false){ 
                if(!is_dir($DirPath.$file)) 
                { 
                    echo "filename: $file<br />"; 
                } 
         } 
    } 
}

사용 방법은 다음과 같습니다.

listDirFiles(&#39;home/some_folder/&#39;);

PHP는 현재 페이지 URL을 가져옵니다

다음 함수를 사용하면 http 또는 https인지 현재 페이지의 URL을 얻을 수 있습니다.

function curPageURL() { 
    $pageURL = &#39;http&#39;; 
    if (!empty($_SERVER[&#39;HTTPS&#39;])) {$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();

8. PHP는 파일을 강제로 다운로드합니다.

브라우저에서 파일을 직접 열지 않는 경우가 있습니다. , PDF 파일과 같은 파일을 직접 다운로드하려면 다음 함수를 사용하여 파일을 강제로 다운로드할 수 있습니다.

function download($filename){ 
    if ((isset($filename))&&(file_exists($filename))){ 
       header("Content-length: ".filesize($filename)); 
       header(&#39;Content-Type: application/octet-stream&#39;); 
       header(&#39;Content-Disposition: attachment; filename="&#39; . $filename . &#39;"&#39;); 
       readfile("$filename"); 
    } else { 
       echo "Looks like file does not exist!"; 
    } 
}

사용 방법은 다음과 같습니다.

download(&#39;/down/test_45f73e852.zip&#39;);

9. PHP는 문자열의 길이를 가로챕니다.

문자열의 길이를 가로채야 하는 경우가 종종 있습니다. 문자열(한자 포함) 예를 들어 제목 표시는 문자 수를 초과할 수 없으며 초과 길이는 ...로 표시됩니다. 다음 기능은 귀하의 요구를 충족시킬 수 있습니다.

/* 
 Utf-8、gb2312都支持的汉字截取函数 
 cut_str(字符串, 截取长度, 开始长度, 编码); 
 编码默认为 utf-8 
 开始长度默认为 0 
*/ 
function cutStr($string, $sublen, $start = 0, $code = &#39;UTF-8&#39;){ 
    if($code == &#39;UTF-8&#39;){ 
        $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(&#39;&#39;, array_slice($t_string[0], $start, $sublen))."..."; 
        return join(&#39;&#39;, array_slice($t_string[0], $start, $sublen)); 
    }else{ 
        $start = $start*2; 
        $sublen = $sublen*2; 
        $strlen = strlen($string); 
        $tmpstr = &#39;&#39;; 
        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 = "jQuery插件实现的加载图片和页面效果"; 
echo cutStr($str,16);

10. PHP로 클라이언트의 실제 IP를 알아냅니다.

우리는 사용자의 IP를 기록하기 위해 데이터베이스를 자주 사용합니다. . 다음 코드로 얻을 수 있습니다. 클라이언트의 실제 IP:

//获取用户真实IP 
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[&#39;REMOTE_ADDR&#39;]) && $_SERVER[&#39;REMOTE_ADDR&#39;] && strcasecmp($_SERVER[&#39;REMOTE_ADDR&#39;], "unknown")) 
                    $ip = $_SERVER[&#39;REMOTE_ADDR&#39;]; 
                else 
                    $ip = "unknown"; 
    return ($ip); 
}

사용 방법은 다음과 같습니다.

echo getIp();

11. PHP는 SQL 주입을 방지합니다

데이터베이스를 쿼리할 때 보안상의 이유로 악의적인 SQL 삽입을 방지하기 위해 일부 불법 문자를 필터링해야 합니다.

function injCheck($sql_str) {  
    $check = preg_match(&#39;/select|insert|update|delete|\&#39;|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/&#39;, $sql_str); 
    if ($check) { 
        echo &#39;非法字符!!&#39;; 
        exit; 
    } else { 
        return $sql_str; 
    } 
}

사용 방법은 다음과 같습니다.

echo injCheck(&#39;1 or 1=1&#39;);

12. PHP 페이지 프롬프트 및 점프

폼 작업을 수행할 때 친근감을 위해 사용자에게 작업 결과를 알리고 해당 페이지로 이동해야 하는 경우가 있습니다. 다음 함수는

function message($msgTitle,$message,$jumpUrl){ 
    $str = &#39;<!DOCTYPE HTML>&#39;; 
    $str .= &#39;<html>&#39;; 
    $str .= &#39;<head>&#39;; 
    $str .= &#39;<meta charset="utf-8">&#39;; 
    $str .= &#39;<title>页面提示</title>&#39;; 
    $str .= &#39;<style type="text/css">&#39;; 
    $str .= &#39;*{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}&#39;; 
    $str .= &#39;</style>&#39;; 
    $str .= &#39;</head>&#39;; 
    $str .= &#39;<body>&#39;; 
    $str .= &#39;<div>&#39;; 
    $str .= &#39;<h3>&#39;.$msgTitle.&#39;</h3>&#39;; 
    $str .= &#39;<div>&#39;; 
    $str .= &#39;<h4>&#39;.$message.&#39;</h4>&#39;; 
    $str .= &#39;<p>系统将在 <span style="color:blue;font-weight:bold">3</span> 秒后自动跳转,如果不想等待,直接点击 <a href="{$jumpUrl}">这里</a> 跳转</p>&#39;; 
    $str .= "<script>setTimeout(&#39;location.replace(\&#39;".$jumpUrl."\&#39;)&#39;,2000)</script>"; 
    $str .= &#39;</div>&#39;; 
    $str .= &#39;</div>&#39;; 
    $str .= &#39;</body>&#39;; 
    $str .= &#39;</html>&#39;; 
    echo $str; 
}

사용 방법은 다음과 같습니다.

message(&#39;操作提示&#39;,&#39;操作成功!&#39;,&#39;http://www.helloweba.com/&#39;);

13. PHP 계산 시간

처리 시간을 계산할 필요가 있습니다. 예를 들어 클라이언트 실행 시간을 계산할 때 일반적으로 hh:mm:ss로 표현됩니다.

function changeTimeType($seconds) { 
    if ($seconds > 3600) { 
        $hours = intval($seconds / 3600); 
        $minutes = $seconds % 3600; 
        $time = $hours . ":" . gmstrftime(&#39;%M:%S&#39;, $minutes); 
    } else { 
        $time = gmstrftime(&#39;%H:%M:%S&#39;, $seconds); 
    } 
    return $time; 
}

사용방법은 다음과 같습니다.

$seconds = 3712; 
echo changeTimeType($seconds);


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.