php

位置:IT落伍者 >> php >> 浏览文章

实用PHP代码二十例


发布日期:2018年03月11日
 
实用PHP代码二十例

PHP可阅读随机字符串

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

/**************
*@length length of random string (must be a multiple of )
**************/
function readable_random_string($length = ){
$conso=array("b""c""d""f""g""h""j""k""l"
"m""n""p""r""s""t""v""w""x""y""z");
$vocal=array("a""e""i""o""u");
$password="";
srand ((double)microtime()*);
$max = $length/;
for($i=; $i<=$max; $i++)
{
$password=$conso[rand()];
$password=$vocal[rand()];
}
return $password;
}

PHP生成一个随机字符串

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

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

PHP编码电子邮件地址

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

function encode_email($email=info@domaincom $linkText=Contact Us $attrs =class="emailencoder" )
{
// remplazar aroba y puntos
$email = str_replace(@ &#; $email);
$email = str_replace( &#; $email);
$email = str_split($email );

$linkText = str_replace(@ &#; $linkText);
$linkText = str_replace( &#; $linkText);
$linkText = str_split($linkText );

$part = <a href="ma;
$part = ilto&#;;
$part = " $attrs >;
$part = </a>;

$encoded = <script type="text/javascript">;
$encoded = "documentwrite($part);";
$encoded = "documentwrite($part);";
foreach($email as $e)
{
$encoded = "documentwrite($e);";
}
$encoded = "documentwrite($part);";
foreach($linkText as $l)
{
$encoded = "documentwrite($l);";
}
$encoded = "documentwrite($part);";
$encoded = </script>;

return $encoded;
}

PHP验证邮件地址

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

function is_valid_email($email $test_mx = false)
{
if(eregi("^([_az]+)([_az]+)*@([az]+)([az]+)*([az]{})$" $email))
if($test_mx)
{
list($username $domain) = split("@" $email);
return getmxrr($domain $mxrecords);
}
else
return true;
else
return false;
}

PHP列出目录内容

function list_files($dir)
{
if(is_dir($dir))
{
if($handle = opendir($dir))
{
while(($file = readdir($handle)) !== false)
{
if($file != "" && $file != "" && $file != "Thumbsdb")
{
echo <a target="_blank" href="$dir$file">$file</a><br>"n";
}
}
closedir($handle);
}
}
}

PHP销毁目录

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

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

PHP解析 JSON 数据

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

$json_string={"id":"name":"foo""email":"foo@foobarcom""interest":["wordpress""php"]} ;
$obj=json_decode($json_string);
echo $obj>name; //prints foo
echo $obj>interest[]; //prints php

PHP解析 XML 数据

//xml string
$xml_string="<?xml version=?>
<users>
<user id=>
<name>Foo</name>
<email>foo@barcom</name>
</user>
<user id=>
<name>Foobar</name>
<email>foobar@foocom</name>
</user>
</users>";

//load the xml string using simplexml
$xml = simplexml_load_string($xml_string);

//loop through the each node of user
foreach ($xml>user as $user)
{
//access attribute
echo $user[id] ;
//subnodes are accessed by > operator
echo $user>name ;
echo $user>email <br />;
}

PHP创建日志缩略名

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

function create_slug($string){
$slug=preg_replace(/[^AZaz]+/ $string);
return $slug;
}

PHP获取客户端真实 IP 地址

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

function getRealIpAddr()
{
if (!emptyempty(实用PHP代码二十一个实例 站长学院SERVER[REMOTE_ADDR];
}
return $ip;
}

PHP强制性文件下载

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

/********************
*@file path to file
*/
function force_download($file)
{
if ((isset($file))&&(file_exists($file))) {
header("Contentlength: "filesize($file));
header(ContentType: application/octetstream);
header(ContentDisposition: attachment; filename=" $file ");
readfile("$file");
} else {
echo "No file selected";
}
}

PHP创建标签云

function getCloud( $data = array() $minFontSize = $maxFontSize = )
{
$minimumCount = min( array_values( $data ) );
$maximumCount = max( array_values( $data ) );
$spread = $maximumCount $minimumCount;
$cloudHTML = ;
$cloudTags = array();

$spread == && $spread = ;

foreach( $data as $tag => $count )
{
$size = $minFontSize + ( $count $minimumCount )
* ( $maxFontSize $minFontSize ) / $spread;
$cloudTags[] = <a style="fontsize: floor( $size ) px
" href="#" title=" $tag
returned a count of $count ">
htmlspecialchars( stripslashes( $tag ) ) </a>;
}

return join( "n" $cloudTags ) "n";
}
/**************************
**** Sample usage ***/
$arr = Array(Actionscript => Adobe => Array => Background =>
Blur => Canvas => Class => Color Palette => Crop =>
Delimiter => Depth => Design => Encode => Encryption =>
Extract => Filters => );
echo getCloud($arr );

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

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

similar_text($string $string $percent);
//$percent will have the percentage of similarity

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

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

/******************
*@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)
*/
function show_gravatar($email $size $default $rating)
{
echo <img src="md($email)
&default=$default&size=$size&rating=$rating" width="$sizepx"
height="$sizepx" />;
}

PHP在字符断点处截断文字

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

// Original PHP code by Chirp Internet: wwwchirpcomau
// Please acknowledge use of this code by including this header
function myTruncate($string $limit $break="" $pad="") {
// return with no change if string is shorter than $limit
if(strlen($string) <= $limit)
return $string;

// is $break present between $limit and the end of the string?
if(false !== ($breakpoint = strpos($string $break $limit))) {
if($breakpoint < strlen($string) ) {
$string = substr($string $breakpoint) $pad;
}
}
return $string;
}
/***** Example ****/
$short_string=myTruncate($long_string );

PHP文件 Zip 压缩

/* creates a compressed zip file */
function create_zip($files = array()$destination = $overwrite = false) {
//if the zip file already exists and overwrite is false return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip>open($destination$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip>addFile($file$file);
}
//debug
//echo The zip archive contains $zip>numFiles files with a status of $zip>status;

//close the zip done!
$zip>close();

//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
/***** Example Usage ***/
$files=array(filejpg filejpg filegif);
create_zip($files myzipfilezip true);

PHP解压缩 Zip 文件

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

PHP为 URL 地址预设 http 字符串

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

if (!preg_match("/^(http|ftp):/" 实用PHP代码二十一个实例 站长学院POST[url];
}

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

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

function makeClickableLinks($text) { $text = eregi_replace((((f|ht){}tp://)[azAZ@:%_+~#?&//=]+) <a href=""></a> $text); $text = eregi_replace(([[:space:]()[{}])(www[azAZ@:%_+~#?&//=]+) <a href=">http://> $text); $text = eregi_replace(([_az]+@([az][az]+)+[az]{}) <a href="mailto:"></a> $text); return $text;}

PHP调整图像尺寸

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

/**********************
*@filename path to the image
*@tmpname temporary path to thumbnail
*@xmax max width
*@ymax max height
*/
function resize_image($filename $tmpname $xmax $ymax)
{
$ext = explode("" $filename);
$ext = $ext[count($ext)];

if($ext == "jpg" || $ext == "jpeg")
$im = imagecreatefromjpeg($tmpname);
elseif($ext == "png")
$im = imagecreatefrompng($tmpname);
elseif($ext == "gif")
$im = imagecreatefromgif($tmpname);

$x = imagesx($im);
$y = imagesy($im);

if($x <= $xmax && $y <= $ymax)
return $im;

if($x >= $y) {
$newx = $xmax;
$newy = $newx * $y / $x;
}
else {
$newy = $ymax;
$newx = $x / $y * $newy;
}

$im = imagecreatetruecolor($newx $newy);
imagecopyresized($im $im floor($newx) floor($newy) $x $y);
return $im;
}

               

上一篇:使用PHP接收POST数据,解析json数据

下一篇:如何打开PHP文件,PHP文件怎么打开?