Heim  >  Artikel  >  php教程  >  常用的PHP代码

常用的PHP代码

WBOY
WBOYOriginal
2016-06-06 19:42:191080Durchsuche

1. PHP可阅读随机字符串 此代码将创建一个可阅读的字符串,使其更接近词典中的单词,实用且具有密码验证功能。 /* ************* *@length - length of random string (must be a multiple of 2) ************* */ function readable_random_string( $length

1. PHP可阅读随机字符串

  此代码将创建一个可阅读的字符串,使其更接近词典中的单词,实用且具有密码验证功能。

<span>/*</span><span>************* 

*@length - length of random string (must be a multiple of 2) 

*************</span><span>*/</span> 

<span>function</span> readable_random_string(<span>$length</span> = 6<span>){ 

    </span><span>$conso</span>=<span>array</span>("b","c","d","f","g","h","j","k","l", 

    "m","n","p","r","s","t","v","w","x","y","z"<span>); 

    </span><span>$vocal</span>=<span>array</span>("a","e","i","o","u"<span>); 

    </span><span>$password</span>=""<span>; 

    </span><span>srand</span> ((<span>double</span>)<span>microtime</span>()*1000000<span>); 

    </span><span>$max</span> = <span>$length</span>/2<span>; 

    </span><span>for</span>(<span>$i</span>=1; <span>$i</span>$max; <span>$i</span>++<span>) 

    { 

    </span><span>$password</span>.=<span>$conso</span>[<span>rand</span>(0,19<span>)]; 

    </span><span>$password</span>.=<span>$vocal</span>[<span>rand</span>(0,4<span>)]; 

    } 

    </span><span>return</span> <span>$password</span><span>; 

} </span>

 

2. PHP生成一个随机字符串

  如果不需要可阅读的字符串,使用此函数替代,即可创建一个随机字符串,作为用户的随机密码等。

<span>/*</span><span>************ 
*@l - length of random string 
</span><span>*/</span> 
<span>function</span> generate_rand(<span>$l</span><span>){ 
  </span><span>$c</span>= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"<span>; 
  </span><span>srand</span>((<span>double</span>)<span>microtime</span>()*1000000<span>); 
  </span><span>for</span>(<span>$i</span>=0; <span>$i</span>$l; <span>$i</span>++<span>) { 
      </span><span>$rand</span>.= <span>$c</span>[<span>rand</span>()%<span>strlen</span>(<span>$c</span><span>)]; 
  } 
  </span><span>return</span> <span>$rand</span><span>; 
} </span>

 

3. PHP编码电子邮件地址

  使用此代码,可以将任何电子邮件地址编码为 html 字符实体,以防止被垃圾邮件程序收集。

<span>function</span> encode_email(<span>$email</span>='info@domain.com', <span>$linkText</span>='Contact Us', <span>$attrs</span> ='class="emailencoder"'<span> ) 
{ 
    </span><span>//</span><span> remplazar aroba y puntos </span>
    <span>$email</span> = <span>str_replace</span>('@', '@', <span>$email</span><span>); 
    </span><span>$email</span> = <span>str_replace</span>('.', '.', <span>$email</span><span>); 
    </span><span>$email</span> = <span>str_split</span>(<span>$email</span>, 5<span>);   
 
    </span><span>$linkText</span> = <span>str_replace</span>('@', '@', <span>$linkText</span><span>); 
    </span><span>$linkText</span> = <span>str_replace</span>('.', '.', <span>$linkText</span><span>); 
    </span><span>$linkText</span> = <span>str_split</span>(<span>$linkText</span>, 5<span>);   
 
    </span><span>$part1</span> = '<a href="ma'<span>;%20%0A%20%20%20%20</span><span>%24part2</span>%20=%20'ilto:'<span>;%20%0A%20%20%20%20</span><span>%24part3</span>%20=%20'">$attrs .' >'<span>; 
    </span><span>$part4</span> = '</a>'<span>;   
 
    </span><span>$encoded</span> = '<script type="text/javascript">'<span>; 
    <span>$encoded .= "document.write('<span>$part1');"<span>; 
    <span>$encoded .= "document.write('<span>$part2');"<span>; 
    <span>foreach(<span>$email <span>as <span>$e<span>) 
    { 
            <span>$encoded .= "document.write('<span>$e');"<span>; 
    } 
    <span>$encoded .= "document.write('<span>$part3');"<span>; 
    <span>foreach(<span>$linkText <span>as <span>$l<span>) 
    { 
            <span>$encoded .= "document.write('<span>$l');"<span>; 
    } 
    <span>$encoded .= "document.write('<span>$part4');"<span>; 
    <span>$encoded .= '</script>'<span>;   
 
    </span><span>return</span> <span>$encoded</span><span>; 
} </span>

 

4. PHP验证邮件地址

  电子邮件验证也许是中最常用的网页表单验证,此代码除了验证电子邮件地址,也可以选择检查邮件域所属 DNS 中的 MX 记录,使邮件验证功能更加强大。

<span>function</span> is_valid_email(<span>$email</span>, <span>$test_mx</span> = <span>false</span><span>) 
{ 
    </span><span>if</span>(<span>eregi</span>("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", <span>$email</span><span>)) 
        </span><span>if</span>(<span>$test_mx</span><span>) 
        { 
            </span><span>list</span>(<span>$username</span>, <span>$domain</span>) = <span>split</span>("@", <span>$email</span><span>); 
            </span><span>return</span> getmxrr(<span>$domain</span>, <span>$mxrecords</span><span>); 
        } 
        </span><span>else</span> 
            <span>return</span> <span>true</span><span>; 
    </span><span>else</span> 
        <span>return</span> <span>false</span><span>; 
} </span>

 

5. PHP列出目录内容

<span>function</span> list_files(<span>$dir</span><span>) 
{ 
    </span><span>if</span>(<span>is_dir</span>(<span>$dir</span><span>)) 
    { 
        </span><span>if</span>(<span>$handle</span> = <span>opendir</span>(<span>$dir</span><span>)) 
        { 
            </span><span>while</span>((<span>$file</span> = <span>readdir</span>(<span>$handle</span>)) !== <span>false</span><span>) 
            { 
                </span><span>if</span>(<span>$file</span> != "." && <span>$file</span> != ".." && <span>$file</span> != "Thumbs.db"<span>) 
                { 
                    </span><span>echo</span> '<a target="_blank" href="'.<span>%24dir</span>.<span>%24file</span>.'">'.<span>$file</span>.'</a><br>'."\n"<span>; 
                } 
            } 
            </span><span>closedir</span>(<span>$handle</span><span>); 
        } 
    } 
} </span>

 

6. PHP销毁目录

  删除一个目录,包括它的内容。

<span>/*</span><span>**** 
*@dir - Directory to destroy 
*@virtual[optional]- whether a virtual directory 
</span><span>*/</span> 
<span>function</span> destroyDir(<span>$dir</span>, <span>$virtual</span> = <span>false</span><span>) 
{ 
    </span><span>$ds</span> =<span> DIRECTORY_SEPARATOR; 
    </span><span>$dir</span> = <span>$virtual</span> ? <span>realpath</span>(<span>$dir</span>) : <span>$dir</span><span>; 
    </span><span>$dir</span> = <span>substr</span>(<span>$dir</span>, -1) == <span>$ds</span> ? <span>substr</span>(<span>$dir</span>, 0, -1) : <span>$dir</span><span>; 
    </span><span>if</span> (<span>is_dir</span>(<span>$dir</span>) && <span>$handle</span> = <span>opendir</span>(<span>$dir</span><span>)) 
    { 
        </span><span>while</span> (<span>$file</span> = <span>readdir</span>(<span>$handle</span><span>)) 
        { 
            </span><span>if</span> (<span>$file</span> == '.' || <span>$file</span> == '..'<span>) 
            { 
                </span><span>continue</span><span>; 
            } 
            </span><span>elseif</span> (<span>is_dir</span>(<span>$dir</span>.<span>$ds</span>.<span>$file</span><span>)) 
            { 
                destroyDir(</span><span>$dir</span>.<span>$ds</span>.<span>$file</span><span>); 
            } 
            </span><span>else</span><span> 
            { 
                </span><span>unlink</span>(<span>$dir</span>.<span>$ds</span>.<span>$file</span><span>); 
            } 
        } 
        </span><span>closedir</span>(<span>$handle</span><span>); 
        </span><span>rmdir</span>(<span>$dir</span><span>); 
        </span><span>return</span> <span>true</span><span>; 
    } 
    </span><span>else</span><span> 
    { 
        </span><span>return</span> <span>false</span><span>; 
    } 
} </span>

 

7. PHP解析 JSON 数据

  与大多数流行的 Web 服务如 twitter 通过开放 API 来提供数据一样,它总是能够知道如何解析 API 数据的各种传送格式,包括 JSON,XML 等等。

<span>$json_string</span>='{"id":1,"name":"foo","email":"foo@foobar.com","interest":["wordpress","php"]} '<span>; 
</span><span>$obj</span>=json_decode(<span>$json_string</span><span>); 
</span><span>echo</span> <span>$obj</span>->name; <span>//</span><span>prints foo </span>
<span>echo</span> <span>$obj</span>->interest[1]; <span>//</span><span>prints php </span>

 

8. PHP解析 XML 数据

<span>//</span><span>xml string </span>
<span>$xml_string</span>="<span><?xml version='1.0'?> 
<users> 
<user id="398"> 
<name>Foo</name> 
<email>foo@bar.com 
</email></user> 
<user id="867"> 
<name>Foobar</name> 
<email>foobar@foo.com 
</email></user> 
</users></span>"<span>;  
 
</span><span>//</span><span>load the xml string using simplexml </span>
<span>$xml</span> = <span>simplexml_load_string</span>(<span>$xml_string</span><span>);  
 
</span><span>//</span><span>loop through the each node of user </span>
<span>foreach</span> (<span>$xml</span>->user <span>as</span> <span>$user</span><span>) 
{ 
</span><span>//</span><span>access attribute </span>
<span>echo</span> <span>$user</span>['id'], ' '<span>; 
</span><span>//</span><span>subnodes are accessed by -> operator </span>
<span>echo</span> <span>$user</span>->name, ' '<span>; 
</span><span>echo</span> <span>$user</span>->email, '<br>'<span>; 
} </span>

 

9. PHP创建日志缩略名

  创建用户友好的日志缩略名。

<span>function</span> create_slug(<span>$string</span><span>){ 
</span><span>$slug</span>=<span>preg_replace</span>('/[^A-Za-z0-9-]+/', '-', <span>$string</span><span>); 
</span><span>return</span> <span>$slug</span><span>; 
} </span>

 

10. PHP获取客户端真实 IP 地址

  该函数将获取用户的真实 IP 地址,即便他使用代理服务器。

<span>function</span><span> getRealIpAddr() 
{ 
    </span><span>if</span> (!emptyempty(<span>$_SERVER</span>['HTTP_CLIENT_IP'<span>])) 
    { 
        </span><span>$ip</span>=<span>$_SERVER</span>['HTTP_CLIENT_IP'<span>]; 
    } 
    </span><span>elseif</span> (!emptyempty(<span>$_SERVER</span>['HTTP_X_FORWARDED_FOR'<span>])) 
    </span><span>//</span><span>to check ip is pass from proxy </span>
<span>    { 
        </span><span>$ip</span>=<span>$_SERVER</span>['HTTP_X_FORWARDED_FOR'<span>]; 
    } 
    </span><span>else</span><span> 
    { 
        </span><span>$ip</span>=<span>$_SERVER</span>['REMOTE_ADDR'<span>]; 
    } 
    </span><span>return</span> <span>$ip</span><span>; 
} </span>

 

11. PHP强制性文件下载

  为用户提供强制性的文件下载功能。

<span>/*</span><span>******************* 
*@file - path to file 
</span><span>*/</span> 
<span>function</span> force_download(<span>$file</span><span>) 
{ 
</span><span>if</span> ((<span>isset</span>(<span>$file</span>))&&(<span>file_exists</span>(<span>$file</span><span>))) { 
</span><span>header</span>("Content-length: ".<span>filesize</span>(<span>$file</span><span>)); 
</span><span>header</span>('Content-Type: application/octet-stream'<span>); 
</span><span>header</span>('Content-Disposition: attachment; filename="' . <span>$file</span> . '"'<span>); 
</span><span>readfile</span>("<span>$file</span>"<span>); 
} </span><span>else</span><span> { 
</span><span>echo</span> "No file selected"<span>; 
} 
} </span>

 

<span>function</span> getCloud( <span>$data</span> = <span>array</span>(), <span>$minFontSize</span> = 12, <span>$maxFontSize</span> = 30<span> ) 
{ 
</span><span>$minimumCount</span> = <span>min</span>( <span>array_values</span>( <span>$data</span><span> ) ); 
</span><span>$maximumCount</span> = <span>max</span>( <span>array_values</span>( <span>$data</span><span> ) ); 
</span><span>$spread</span> = <span>$maximumCount</span> - <span>$minimumCount</span><span>; 
</span><span>$cloudHTML</span> = ''<span>; 
</span> = <span>array</span><span>();  
 
</span><span>$spread</span> == 0 && <span>$spread</span> = 1<span>;  
 
</span><span>foreach</span>( <span>$data</span> <span>as</span> <span>$tag</span> => <span>$count</span><span> ) 
{ 
</span><span>$size</span> = <span>$minFontSize</span> + ( <span>$count</span> - <span>$minimumCount</span><span> ) 
</span>* ( <span>$maxFontSize</span> - <span>$minFontSize</span> ) / <span>$spread</span><span>; 
</span>[] = '<a style="font-size: ' . <span>floor</span>( <span>$size</span> ) . 'px' 
. '" href="#" title="\'' . <span>$tag</span> . 
'\' returned a count of ' . <span>$count</span> . '">' 
. <span>htmlspecialchars</span>( <span>stripslashes</span>( <span>$tag</span> ) ) . '</a>'<span>; 
}  
 
</span><span>return</span> <span>join</span>( "\n",  ) . "\n"<span>; 
} 
</span><span>/*</span><span>************************* 
**** Sample usage **</span><span>*/</span> 
<span>$arr</span> = <span>Array</span>('Actionscript' => 35, 'Adobe' => 22, 'Array' => 44, 'Background' => 43, 
'Blur' => 18, 'Canvas' => 33, 'Class' => 15, 'Color Palette' => 11, 'Crop' => 42, 
'Delimiter' => 13, 'Depth' => 34, 'Design' => 8, 'Encode' => 12, 'Encryption' => 30, 
'Extract' => 28, 'Filters' => 42<span>); 
</span><span>echo</span> getCloud(<span>$arr</span>, 12, 36); 

 

13. PHP寻找两个字符串的相似性

  PHP 提供了一个极少使用的 similar_text 函数,但此函数非常有用,用于比较两个字符串并返回相似程度的百分比。

<span>similar_text</span>(<span>$string1</span>, <span>$string2</span>, <span>$percent</span><span>); 
</span><span>//</span><span>$percent will have the percentage of similarity </span>

 

14. PHP在应用程序中使用 Gravatar 通用头像

  随着 WordPress 越来越普及,Gravatar 也随之流行。由于 Gravatar 提供了易于使用的 API,将其纳入应用程序也变得十分方便。

<span>/*</span><span>***************** 
*@email - Email address to show gravatar for 
*@size - size of gravatar 
*@default - URL of default gravatar to use 
*@rating - rating of Gravatar(G, PG, R, X) 
</span><span>*/</span> 
<span>function</span> show_gravatar(<span>$email</span>, <span>$size</span>, <span>$default</span>, <span>$rating</span><span>) 
{ 
</span><span>echo</span> '<img  src="http://www.gravatar.com/avatar.php?gravatar_id='.<span>md5</span>(<span>%24email</span>).%20%0A'&default='.<span>%24default</span>.'&size='.<span>%24size</span>.'&rating='.<span>%24rating</span>.'"    style="max-width:90%".<span>$size</span>.'<span>px" height="</span>'.<span>$size</span>.'px" alt="常用的PHP代码" >'<span>; 
} </span>

 

15. PHP在字符断点处截断文字

  所谓断字 (word break),即一个单词可在转行时断开的地方。这一函数将在断字处截断字符串。

<span>//</span><span> Original PHP code by Chirp Internet: www.chirp.com.au 
// Please acknowledge use of this code by including this header. </span>
<span>function</span> myTruncate(<span>$string</span>, <span>$limit</span>, <span>$break</span>=".", <span>$pad</span>="..."<span>) { 
</span><span>//</span><span> return with no change if string is shorter than $limit </span>
<span>if</span>(<span>strlen</span>(<span>$string</span>) $limit<span>) 
</span><span>return</span> <span>$string</span><span>;  
 
</span><span>//</span><span> is $break present between $limit and the end of the string? </span>
<span>if</span>(<span>false</span> !== (<span>$breakpoint</span> = <span>strpos</span>(<span>$string</span>, <span>$break</span>, <span>$limit</span><span>))) { 
</span><span>if</span>(<span>$breakpoint</span> strlen(<span>$string</span>) - 1<span>) { 
</span><span>$string</span> = <span>substr</span>(<span>$string</span>, 0, <span>$breakpoint</span>) . <span>$pad</span><span>; 
} 
} 
</span><span>return</span> <span>$string</span><span>; 
} 
</span><span>/*</span><span>**** Example ***</span><span>*/</span> 
<span>$short_string</span>=myTruncate(<span>$long_string</span>, 100, ' '); 

 

16. PHP文件 Zip 压缩

<span>/*</span><span> creates a compressed zip file </span><span>*/</span> 
<span>function</span> create_zip(<span>$files</span> = <span>array</span>(),<span>$destination</span> = '',<span>$overwrite</span> = <span>false</span><span>) { 
</span><span>//</span><span>if the zip file already exists and overwrite is false, return false </span>
<span>if</span>(<span>file_exists</span>(<span>$destination</span>) && !<span>$overwrite</span>) { <span>return</span> <span>false</span><span>; } 
</span><span>//</span><span>vars </span>
<span>$valid_files</span> = <span>array</span><span>(); 
</span><span>//</span><span>if files were passed in... </span>
<span>if</span>(<span>is_array</span>(<span>$files</span><span>)) { 
</span><span>//</span><span>cycle through each file </span>
<span>foreach</span>(<span>$files</span> <span>as</span> <span>$file</span><span>) { 
</span><span>//</span><span>make sure the file exists </span>
<span>if</span>(<span>file_exists</span>(<span>$file</span><span>)) { 
</span><span>$valid_files</span>[] = <span>$file</span><span>; 
} 
} 
} 
</span><span>//</span><span>if we have good files... </span>
<span>if</span>(<span>count</span>(<span>$valid_files</span><span>)) { 
</span><span>//</span><span>create the archive </span>
<span>$zip</span> = <span>new</span><span> ZipArchive(); 
</span><span>if</span>(<span>$zip</span>->open(<span>$destination</span>,<span>$overwrite</span> ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== <span>true</span><span>) { 
</span><span>return</span> <span>false</span><span>; 
} 
</span><span>//</span><span>add the files </span>
<span>foreach</span>(<span>$valid_files</span> <span>as</span> <span>$file</span><span>) { 
</span><span>$zip</span>->addFile(<span>$file</span>,<span>$file</span><span>); 
} 
</span><span>//</span><span>debug 
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;  
 
//close the zip -- done! </span>
<span>$zip</span>-><span>close();  
 
</span><span>//</span><span>check to make sure the file exists </span>
<span>return</span> <span>file_exists</span>(<span>$destination</span><span>); 
} 
</span><span>else</span><span> 
{ 
</span><span>return</span> <span>false</span><span>; 
} 
} 
</span><span>/*</span><span>**** Example Usage **</span><span>*/</span> 
<span>$files</span>=<span>array</span>('file1.jpg', 'file2.jpg', 'file3.gif'<span>); 
create_zip(</span><span>$files</span>, 'myzipfile.zip', <span>true</span>); 

 

17. PHP解压缩 Zip 文件

<span>/*</span><span>********************* 
*@file - path to zip file 
*@destination - destination directory for unzipped files 
</span><span>*/</span> 
<span>function</span> unzip_file(<span>$file</span>, <span>$destination</span><span>){ 
</span><span>//</span><span> create object </span>
<span>$zip</span> = <span>new</span><span> ZipArchive() ; 
</span><span>//</span><span> open archive </span>
<span>if</span> (<span>$zip</span>->open(<span>$file</span>) !== <span>TRUE</span><span>) { 
</span><span>die</span><span> (’Could not open archive’); 
} 
</span><span>//</span><span> extract contents to destination directory </span>
<span>$zip</span>->extractTo(<span>$destination</span><span>); 
</span><span>//</span><span> close archive </span>
<span>$zip</span>-><span>close(); 
</span><span>echo</span> 'Archive extracted to directory'<span>; 
} </span>

 

18. PHP为 URL 地址预设 http 字符串

 有时需要接受一些表单中的网址输入,但用户很少添加 http:// 字段,此代码将为网址添加该字段。

<span>if</span> (!<span>preg_match</span>("/^(http|ftp):/", <span>$_POST</span>['url'<span>])) { 
   </span><span>$_POST</span>['url'] = 'http://'.<span>$_POST</span>['url'<span>]; 
} </span>

 

19. PHP将网址字符串转换成超级链接

  该函数将 URL 和 E-mail 地址字符串转换为可点击的超级链接。

<span>function</span> makeClickableLinks(<span>$text</span><span>) { 
</span><span>$text</span> = <span>eregi_replace</span>('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)', 
'<a href="%5C1">\1</a>', <span>$text</span><span>); 
</span><span>$text</span> = <span>eregi_replace</span>('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)', 
'\1<a href="http://%5C2">\2</a>', <span>$text</span><span>); 
</span><span>$text</span> = <span>eregi_replace</span>('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})', 
'<a href="mailto:%5C1">\1</a>', <span>$text</span><span>);  
 
</span><span>return</span> <span>$text</span><span>; 
} </span>

 

20. PHP调整图像尺寸

  创建图像缩略图需要许多时间,此代码将有助于了解缩略图的逻辑。

<span>/*</span><span>********************* 
*@filename - path to the image 
*@tmpname - temporary path to thumbnail 
*@xmax - max width 
*@ymax - max height 
</span><span>*/</span> 
<span>function</span> resize_image(<span>$filename</span>, <span>$tmpname</span>, <span>$xmax</span>, <span>$ymax</span><span>) 
{ 
    </span><span>$ext</span> = <span>explode</span>(".", <span>$filename</span><span>); 
    </span><span>$ext</span> = <span>$ext</span>[<span>count</span>(<span>$ext</span>)-1<span>];   
 
    </span><span>if</span>(<span>$ext</span> == "jpg" || <span>$ext</span> == "jpeg"<span>) 
        </span><span>$im</span> = imagecreatefromjpeg(<span>$tmpname</span><span>); 
    </span><span>elseif</span>(<span>$ext</span> == "png"<span>) 
        </span><span>$im</span> = imagecreatefrompng(<span>$tmpname</span><span>); 
    </span><span>elseif</span>(<span>$ext</span> == "gif"<span>) 
        </span><span>$im</span> = imagecreatefromgif(<span>$tmpname</span><span>);   
 
    </span><span>$x</span> = imagesx(<span>$im</span><span>); 
    </span><span>$y</span> = imagesy(<span>$im</span><span>);   
 
    </span><span>if</span>(<span>$x</span> $xmax && <span>$y</span> $ymax<span>) 
        </span><span>return</span> <span>$im</span><span>;   
 
    </span><span>if</span>(<span>$x</span> >= <span>$y</span><span>) { 
        </span><span>$newx</span> = <span>$xmax</span><span>; 
        </span><span>$newy</span> = <span>$newx</span> * <span>$y</span> / <span>$x</span><span>; 
    } 
    </span><span>else</span><span> { 
        </span><span>$newy</span> = <span>$ymax</span><span>; 
        </span><span>$newx</span> = <span>$x</span> / <span>$y</span> * <span>$newy</span><span>; 
    }   
 
    </span><span>$im2</span> = imagecreatetruecolor(<span>$newx</span>, <span>$newy</span><span>); 
    imagecopyresized(</span><span>$im2</span>, <span>$im</span>, 0, 0, 0, 0, <span>floor</span>(<span>$newx</span>), <span>floor</span>(<span>$newy</span>), <span>$x</span>, <span>$y</span><span>); 
    </span><span>return</span> <span>$im2</span><span>; 
} </span>

 

21. PHP检测 ajax 请求

  大多数的 JavaScript 框架如 jquery,Mootools 等,在发出 Ajax 请求时,都会发送额外的 HTTP_X_REQUESTED_WITH 头部信息,头当他们一个ajax请求,因此你可以在服务器端侦测到 Ajax 请求。

<span>if</span>(!emptyempty(<span>$_SERVER</span>['HTTP_X_REQUESTED_WITH']) && <span>strtolower</span>(<span>$_SERVER</span>['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'<span>){ 
    </span><span>//</span><span>If AJAX Request Then </span>
}<span>else</span><span>{ 
</span><span>//</span><span>something else </span>
} 

 

22.关键词高亮

<span>function</span> highlight(<span>$sString</span>, <span>$aWords</span><span>) { 
    </span><span>if</span> (!<span>is_array</span> (<span>$aWords</span>) || emptyempty (<span>$aWords</span>) || !<span>is_string</span> (<span>$sString</span><span>)) { 
        </span><span>return</span> <span>false</span><span>; 
    } 
 
    </span><span>$sWords</span> = <span>implode</span> ('|', <span>$aWords</span><span>); 
    </span><span>return</span> <span>preg_replace</span> ('@\b('.<span>$sWords</span>.')\b@si', '<strong style="background-color:yellow">$1</strong>', <span>$sString</span><span>); 
} </span>

 

23.获取你的Feedburner的用户

<span>function</span> get_average_readers(<span>$feed_id</span>,<span>$interval</span> = 7<span>){ 
    </span><span>$today</span> = <span>date</span>('Y-m-d', <span>strtotime</span>("now"<span>)); 
    </span><span>$ago</span> = <span>date</span>('Y-m-d', <span>strtotime</span>("-".<span>$interval</span>." days"<span>)); 
    </span><span>$feed_url</span>="https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=".<span>$feed_id</span>."&dates=".<span>$ago</span>.",".<span>$today</span><span>; 
    </span><span>$ch</span> =<span> curl_init(); 
    curl_setopt(</span><span>$ch</span>, CURLOPT_RETURNTRANSFER, 1<span>); 
    curl_setopt(</span><span>$ch</span>, CURLOPT_URL, <span>$feed_url</span><span>); 
    </span><span>$data</span> = curl_exec(<span>$ch</span><span>); 
    curl_close(</span><span>$ch</span><span>); 
    </span><span>$xml</span> = <span>new</span> SimpleXMLElement(<span>$data</span><span>); 
    </span><span>$fb</span> = <span>$xml</span>->feed->entry['circulation'<span>]; 
 
    </span><span>$nb</span> = 0<span>; 
    </span><span>foreach</span>(<span>$xml</span>->feed->children() <span>as</span> <span>$circ</span><span>){ 
        </span><span>$nb</span> += <span>$circ</span>['circulation'<span>]; 
    } 
 
    </span><span>return</span> <span>round</span>(<span>$nb</span>/<span>$interval</span><span>); 
} </span>

 

24.自动生成密码

<span>function</span> generatePassword(<span>$length</span>=9, <span>$strength</span>=0<span>) { 
    </span><span>$vowels</span> = 'aeuy'<span>; 
    </span><span>$consonants</span> = 'bdghjmnpqrstvz'<span>; 
    </span><span>if</span> (<span>$strength</span> >= 1<span>) { 
        </span><span>$consonants</span> .= 'BDGHJLMNPQRSTVWXZ'<span>; 
    } 
    </span><span>if</span> (<span>$strength</span> >= 2<span>) { 
        </span><span>$vowels</span> .= "AEUY"<span>; 
    } 
    </span><span>if</span> (<span>$strength</span> >= 4<span>) { 
        </span><span>$consonants</span> .= '23456789'<span>; 
    } 
    </span><span>if</span> (<span>$strength</span> >= 8<span> ) { 
        </span><span>$vowels</span> .= '@#$%'<span>; 
    } 
 
    </span><span>$password</span> = ''<span>; 
    </span><span>$alt</span> = <span>time</span>() % 2<span>; 
    </span><span>for</span> (<span>$i</span> = 0; <span>$i</span> $length; <span>$i</span>++<span>) { 
        </span><span>if</span> (<span>$alt</span> == 1<span>) { 
            </span><span>$password</span> .= <span>$consonants</span>[(<span>rand</span>() % <span>strlen</span>(<span>$consonants</span><span>))]; 
            </span><span>$alt</span> = 0<span>; 
        } </span><span>else</span><span> { 
            </span><span>$password</span> .= <span>$vowels</span>[(<span>rand</span>() % <span>strlen</span>(<span>$vowels</span><span>))]; 
            </span><span>$alt</span> = 1<span>; 
        } 
    } 
    </span><span>return</span> <span>$password</span><span>; 
} </span>

 

25.压缩多个CSS文件

<span>header</span>('Content-type: text/css'<span>); 
</span><span>ob_start</span>("compress"<span>); 
</span><span>function</span> compress(<span>$buffer</span><span>) { 
  </span><span>/*</span><span> remove comments </span><span>*/</span> 
  <span>$buffer</span> = <span>preg_replace</span>('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', <span>$buffer</span><span>); 
  </span><span>/*</span><span> remove tabs, spaces, newlines, etc. </span><span>*/</span> 
  <span>$buffer</span> = <span>str_replace</span>(<span>array</span>("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', <span>$buffer</span><span>); 
  </span><span>return</span> <span>$buffer</span><span>; 
} 
 
</span><span>/*</span><span> your css files </span><span>*/</span> 
<span>include</span>('master.css'<span>); 
</span><span>include</span>('typography.css'<span>); 
</span><span>include</span>('grid.css'<span>); 
</span><span>include</span>('print.css'<span>); 
</span><span>include</span>('handheld.css'<span>); 
 
</span><span>ob_end_flush</span>(); 

 

26.获取短网址

<span>function</span> getTinyUrl(<span>$url</span><span>) { 
    </span><span>return</span> <span>file_get_contents</span>("http://tinyurl.com/api-create.php?url=".<span>$url</span><span>); 
} </span>

 

27.根据生日计算年龄

<span>function</span> age(<span>$date</span><span>){ 
    </span><span>$year_diff</span> = ''<span>; 
    </span><span>$time</span> = <span>strtotime</span>(<span>$date</span><span>); 
    </span><span>if</span>(<span>FALSE</span> === <span>$time</span><span>){ 
        </span><span>return</span> ''<span>; 
    } 
 
    </span><span>$date</span> = <span>date</span>('Y-m-d', <span>$time</span><span>); 
    </span><span>list</span>(<span>$year</span>,<span>$month</span>,<span>$day</span>) = <span>explode</span>("-",<span>$date</span><span>); 
    </span><span>$year_diff</span> = <span>date</span>("Y") – <span>$year</span><span>; 
    </span><span>$month_diff</span> = <span>date</span>("m") – <span>$month</span><span>; 
    </span><span>$day_diff</span> = <span>date</span>("d") – <span>$day</span><span>; 
    </span><span>if</span> (<span>$day_diff</span> $month_diff $year_diff<span>–; 
 
    </span><span>return</span> <span>$year_diff</span><span>; 
} </span>

 

28.计算执行时间

<span>//</span><span>Create a variable for start time </span>
<span>$time_start</span> = <span>microtime</span>(<span>true</span><span>); 
 
</span><span>//</span><span> Place your PHP/HTML/JavaScript/CSS/Etc. Here 
 
//Create a variable for end time </span>
<span>$time_end</span> = <span>microtime</span>(<span>true</span><span>); 
</span><span>//</span><span>Subtract the two times to get seconds </span>
<span>$time</span> = <span>$time_end</span> - <span>$time_start</span><span>; 
 
</span><span>echo</span> 'Script took '.<span>$time</span>.' seconds to execute'; 

 

29.PHP的维护模式

<span>function</span> maintenance(<span>$mode</span> = <span>FALSE</span><span>){ 
    </span><span>if</span>(<span>$mode</span><span>){ 
        </span><span>if</span>(<span>basename</span>(<span>$_SERVER</span>['SCRIPT_FILENAME']) != 'maintenance.php'<span>){ 
            </span><span>header</span>("Location: http://example.com/maintenance.php"<span>); 
            </span><span>exit</span><span>; 
        } 
    }</span><span>else</span><span>{ 
        </span><span>if</span>(<span>basename</span>(<span>$_SERVER</span>['SCRIPT_FILENAME']) == 'maintenance.php'<span>){ 
            </span><span>header</span>("Location: http://example.com/"<span>); 
            </span><span>exit</span><span>; 
        } 
    } 
} </span>

 

30.阻止CSS样式被缓存

<link href="/stylesheet.css?<?php%20echo%20time();%20?>" rel="stylesheet" type="text/css"> 

 

31.为数字增加 st\nd\rd 等

<span>function</span> make_ranked(<span>$rank</span><span>) { 
    </span><span>$last</span> = <span>substr</span>( <span>$rank</span>, -1<span> ); 
    </span><span>$seclast</span> = <span>substr</span>( <span>$rank</span>, -2, -1<span> ); 
    </span><span>if</span>( <span>$last</span> > 3 || <span>$last</span> == 0 ) <span>$ext</span> = 'th'<span>; 
    </span><span>else</span> <span>if</span>( <span>$last</span> == 3 ) <span>$ext</span> = 'rd'<span>; 
    </span><span>else</span> <span>if</span>( <span>$last</span> == 2 ) <span>$ext</span> = 'nd'<span>; 
    </span><span>else</span> <span>$ext</span> = 'st'<span>;  
 
    </span><span>if</span>( <span>$last</span> == 1 && <span>$seclast</span> == 1) <span>$ext</span> = 'th'<span>; 
    </span><span>if</span>( <span>$last</span> == 2 && <span>$seclast</span> == 1) <span>$ext</span> = 'th'<span>; 
    </span><span>if</span>( <span>$last</span> == 3 && <span>$seclast</span> == 1) <span>$ext</span> = 'th'<span>;  
 
    </span><span>return</span> <span>$rank</span>.<span>$ext</span><span>; 
} </span>

 

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:php学习笔记(一)Nächster Artikel:html中的php代码不执行