>  기사  >  백엔드 개발  >  꼭 모아야 할 아주 유용한 PHP 코드 10가지 상세 소개

꼭 모아야 할 아주 유용한 PHP 코드 10가지 상세 소개

黄舟
黄舟원래의
2017-03-07 09:13:082339검색

일반 프로그래머로서 여러 언어를 아는 것은 매우 정상적입니다. 대부분의 프로그래머도 몇 가지 PHP 프로그램을 작성할 수 있다고 생각합니다. 웹 프로그래머라면 PHP를 사용해 본 적이 없더라도 필수입니다. 대규모 소프트웨어 프로젝트의 경우 해당 구문도 어느 정도 이해해야 합니다.

PHP는 종종 비판을 받고, 경시되고, 농담으로 취급되지만, 사실은 PHP가 전 세계 웹 사이트 개발에서 가장 일반적으로 사용되는 프로그래밍 언어라는 것을 입증했습니다. PHP의 가장 큰 단점은 너무 단순하고 구문이 엄격하지 않으며 프레임워크 시스템이 매우 약하다는 것입니다. 그러나 이것은 프로그래밍 배경이 약간 있는 일반 사람도 단번에 웹 애플리케이션 개발을 시작할 수 있다는 점입니다. 반나절 동안 PHP를 배웠습니다.

인터넷의 누군가가 여러 프로그래밍 언어의 특징을 요약했는데, 내 생각에는 이 말이 맞는 것 같습니다.

PHP는 빠르고 복잡합니다
자바는 아름다움과 느림
루비는 빠르고 아름다워요
Python은 빠르고 간단합니다

PHP가 대중화되는 동안 많은 실용적인 PHP 코드 조각이 인터넷에 요약되어 있습니다. 비슷한 문제가 발생하면 이러한 코드 조각을 붙여넣어 사용할 수 있습니다. 매우 효율적이며 시간과 노력을 절약할 수 있습니다. 선배 프로그래머들이 정리한 우수한 코드를 자신의 지식베이스에 집어넣는 것은 학습을 잘하는 프로그래머의 좋은 습관이다.

1. 블랙리스트 필터링

rrreerrree

2. 무작위 색상 생성기

아아아아

3. 인터넷에서 파일 다운로드

function is_spam($text, $file, $split = ':', $regex = false){ 
    $handle = fopen($file, 'rb'); 
    $contents = fread($handle, filesize($file)); 
    fclose($handle); 
    $lines = explode("n", $contents); 
    $arr = array(); 
    foreach($lines as $line){ 
        list($word, $count) = explode($split, $line); 
        if($regex) 
            $arr[$word] = $count; 
        else 
            $arr[preg_quote($word)] = $count; 
    } 
    preg_match_all("~".implode('|', array_keys($arr))."~", $text, $matches); 
    $temp = array(); 
    foreach($matches[0] as $match){ 
        if(!in_array($match, $temp)){ 
            $temp[$match] = $temp[$match] + 1; 
            if($temp[$match] >= $arr[$word]) 
                return true; 
        } 
    } 
    return false; 
} 

$file = 'spam.txt'; 
$str = 'This string has cat, dog word'; 
if(is_spam($str, $file)) 
    echo 'this is spam'; 
else 
    echo 'this is not spam';

4. 알렉사/구글 페이지 순위

아아아아

5. 파일 강제 다운로드

ab:3
dog:3
cat:2
monkey:2

6. 이메일을 통해 사용자의 Gravatar 아바타를 표시

function randomColor() { 
    $str = '#'; 
    for($i = 0 ; $i < 6 ; $i++) { 
        $randNum = rand(0 , 15); 
        switch ($randNum) { 
            case 10: $randNum = &#39;A&#39;; break; 
            case 11: $randNum = &#39;B&#39;; break; 
            case 12: $randNum = &#39;C&#39;; break; 
            case 13: $randNum = &#39;D&#39;; break; 
            case 14: $randNum = &#39;E&#39;; break; 
            case 15: $randNum = &#39;F&#39;; break; 
        } 
        $str .= $randNum; 
    } 
    return $str; 
} 
$color = randomColor();

7. cURL

set_time_limit(0); 
// Supports all file types 
// URL Here: 
$url = &#39;http://somsite.com/some_video.flv&#39;; 
$pi = pathinfo($url); 
$ext = $pi[&#39;extension&#39;]; 
$name = $pi[&#39;filename&#39;]; 

// create a new cURL resource 
$ch = curl_init(); 

// set URL and other appropriate options 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_HEADER, false); 
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); 
curl_setopt($ch, CURLOPT_AUTOREFERER, true); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

// grab URL and pass it to the browser 
$opt = curl_exec($ch); 

// close cURL resource, and free up system resources 
curl_close($ch); 

$saveFile = $name.&#39;.&#39;.$ext; 
if(preg_match("/[^0-9a-z._-]/i", $saveFile)) 
    $saveFile = md5(microtime(true)).&#39;.&#39;.$ext; 

$handle = fopen($saveFile, &#39;wb&#39;); 
fwrite($handle, $opt); 
fclose($handle);

를 통해 RSS 구독 수를 알아보세요. 8. 시차 계산 기능

function page_rank($page, $type = &#39;alexa&#39;){ 
    switch($type){ 
        case &#39;alexa&#39;: 
            $url = &#39;http://alexa.com/siteinfo/&#39;; 
            $handle = fopen($url.$page, &#39;r&#39;); 
        break; 
        case &#39;google&#39;: 
            $url = &#39;http://google.com/search?client=navclient-auto&ch=6-1484155081&features=Rank&q=info:&#39;; 
            $handle = fopen($url.&#39;http://&#39;.$page, &#39;r&#39;); 
        break; 
    } 
    $content = stream_get_contents($handle); 
    fclose($handle); 
    $content = preg_replace("~(n|t|ss+)~",&#39;&#39;, $content); 
    switch($type){ 
        case &#39;alexa&#39;: 
            if(preg_match(&#39;~<p class="data (down|up)"><img.+?>(.+?) </p>~im&#39;,$content,$matches)){ 
                return $matches[2]; 
            }else{ 
                return FALSE; 
            } 
        break; 
        case &#39;google&#39;: 
            $rank = explode(&#39;:&#39;,$content); 
            if($rank[2] != &#39;&#39;) 
                return $rank[2]; 
            else 
                return FALSE; 
        break; 
        default: 
            return FALSE; 
        break; 
    } 
} 
// Alexa Page Rank: 
echo &#39;Alexa Rank: &#39;.page_rank(&#39;techug.com&#39;); 
echo &#39;
&#39;; 
// Google Page Rank 
echo &#39;Google Rank: &#39;.page_rank(&#39;techug.com&#39;, &#39;google&#39;);

9. 사진 자르기

아아아아

10. 웹사이트 다운 여부 확인

아아아아

                                                                                           >                                                  .cn)!


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