php

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

20个实用PHP实例代码


发布日期:2022年11月18日
 
20个实用PHP实例代码

                                    

PHP可阅读随机字符串
            
            此代码将创建一个可阅读的字符串使其更接近词典中的单词实用且具有密码验证功能
            
            /**************
            *@lengthlengthofrandomstring(mustbeamultipleof)
            **************/
            functionreadable_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生成一个随机字符串
            
            如果不需要可阅读的字符串使用此函数替代即可创建一个随机字符串作为用户的随机密码等
            /*************
            *@llengthofrandomstring
            */
            functiongenerate_rand($l){
            $c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            srand((double)microtime()*);
            for($i=;$i<$l;$i++){
            $rand=$c[rand()%strlen($c)];
            }
            return$rand;
            }
            
            PHP编码电子邮件地址
            
            使用此代码可以将任何电子邮件地址编码为html字符实体以防止被垃圾邮件程序收集
            
            functionencode_email($email=’info@domaincom’$linkText=’ContactUs’$attrs=’class="emailencoder"’)
            {
            //remplazararobaypuntos
            $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=’<ahref="ma’;
            $part=’ilto&#;’;
            $part=’"’$attrs’>’;
            $part=’</a>’;
            
            $encoded=’<scripttype="text/javascript">’;
            $encoded="documentwrite(’$part’);";
            $encoded="documentwrite(’$part’);";
            foreach($emailas$e)
            {
            $encoded="documentwrite(’$e’);";
            }
            $encoded="documentwrite(’$part’);";
            foreach($linkTextas$l)
            {
            $encoded="documentwrite(’$l’);";
            }
            $encoded="documentwrite(’$part’);";
            $encoded=’</script>’;
            
            return$encoded;
            }
            
            PHP验证邮件地址
            
            电子邮件验证也许是中最常用的网页表单验证此代码除了验证电子邮件地址也可以选择检查邮件域所属DNS中的MX记录使邮件验证功能更加强大
            
            functionis_valid_email($email$test_mx=false)
            {
            if(eregi("^([_az]+)([_az]+)*@([az]+)([az]+)*([az]{})$"$email))
            if($test_mx)
            {
            list($username$domain)=split("@"$email);
            returngetmxrr($domain$mxrecords);
            }
            else
            returntrue;
            else
            returnfalse;
            }
            
            PHP列出目录内容
            
            functionlist_files($dir)
            {
            if(is_dir($dir))
            {
            if($handle=opendir($dir))
            {
            while(($file=readdir($handle))!==false)
            {
            if($file!=""&&$file!=""&&$file!="Thumbsdb")
            {
            echo’<atarget="_blank"href="’$dir$file’">’$file’</a><br>’"n";
            }
            }
            closedir($handle);
            }
            }
            }
            
            PHP销毁目录
            
            删除一个目录包括它的内容
            
            /*****
            *@dirDirectorytodestroy
            *@virtual[optional]whetheravirtualdirectory
            */
            functiondestroyDir($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);
            returntrue;
            }
            else
            {
            returnfalse;
            }
            }
            
            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;//printsfoo
            echo$obj>interest[];//printsphp
            
            PHP解析XML数据
            
            //xmlstring
            $xml_string="<?xmlversion=’’?>
            <users>
            <userid=’’>
            <name>Foo</name>
            <email>foo@barcom</name>
            </user>
            <userid=’’>
            <name>Foobar</name>
            <email>foobar@foocom</name>
            </user>
            </users>";
            
            //loadthexmlstringusingsimplexml
            $xml=simplexml_load_string($xml_string);
            
            //loopthroughtheeachnodeofuser
            foreach($xml>useras$user)
            {
            //accessattribute
            echo$user[’id’]’’;
            //subnodesareaccessedby>operator
            echo$user>name’’;
            echo$user>email’<br/>’;
            }
            
            PHP创建日志缩略名
            
            创建用户友好的日志缩略名
            
            functioncreate_slug($string){
            $slug=preg_replace(’/[^AZaz]+/’$string);
            return$slug;
            }
            
            PHP获取客户端真实IP地址
            
            该函数将获取用户的真实IP地址即便他使用代理服务器
            
            functiongetRealIpAddr()
            {
            if(!emptyempty($_SERVER[’HTTP_CLIENT_IP’]))
            {
            $ip=$_SERVER[’HTTP_CLIENT_IP’];
            }
            elseif(!emptyempty($_SERVER[’HTTP_X_FORWARDED_FOR’]))
            //tocheckipispassfromproxy
            {
            $ip=$_SERVER[’HTTP_X_FORWARDED_FOR’];
            }
            else
            {
            $ip=$_SERVER[’REMOTE_ADDR’];
            }
            return$ip;
            }
            
            PHP强制性文件下载
            
            为用户提供强制性的文件下载功能
            
            /********************
            *@filepathtofile
            */
            functionforce_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"Nofileselected";
            }
            }

            

PHP创建标签云
            functiongetCloud($data=array()$minFontSize=$maxFontSize=)
            {
            $minimumCount=min(array_values($data));
            $maximumCount=max(array_values($data));
            $spread=$maximumCount$minimumCount;
            $cloudHTML=’’;
            $cloudTags=array();
            
            $spread==&&$spread=;
            
            foreach($dataas$tag=>$count)
            {
            $size=$minFontSize+($count$minimumCount)
            *($maxFontSize$minFontSize)/$spread;
            $cloudTags[]=’<astyle="fontsize:’floor($size)’px’
            ’"href="#"title="’’$tag
            ’’returnedacountof’$count’">’
            htmlspecialchars(stripslashes($tag))’</a>’;
            }
            
            returnjoin("n"$cloudTags)"n";
            }
            /**************************
            ****Sampleusage***/
            $arr=Array(’Actionscript’=>’Adobe’=>’Array’=>’Background’=>
            ’Blur’=>’Canvas’=>’Class’=>’ColorPalette’=>’Crop’=>
            ’Delimiter’=>’Depth’=>’Design’=>’Encode’=>’Encryption’=>
            ’Extract’=>’Filters’=>);
            echogetCloud($arr);
            
            PHP寻找两个字符串的相似性
            
            PHP提供了一个极少使用的similar_text函数但此函数非常有用用于比较两个字符串并返回相似程度的百分比
            similar_text($string$string$percent);
            //$percentwillhavethepercentageofsimilarity
            
            PHP在应用程序中使用Gravatar通用头像
            
            随着WordPress越来越普及Gravatar也随之流行由于Gravatar提供了易于使用的API将其纳入应用程序也变得十分方便
            
            /******************
            *@emailEmailaddresstoshowgravatarfor
            *@sizesizeofgravatar
            *@defaultURLofdefaultgravatartouse
            *@ratingratingofGravatar(GPGRX)
            */
            functionshow_gravatar($email$size$default$rating)
            {
            echo’<imgsrc="($email)
            ’&default=’$default’&size=’$size’&rating=’$rating’"width="’$size’px"
            height="’$size’px"/>’;
            }
            
            PHP在字符断点处截断文字
            
            所谓断字(wordbreak)即一个单词可在转行时断开的地方这一函数将在断字处截断字符串
            
            //OriginalPHPcodebyChirpInternet:wwwchirpcomau
            //Pleaseacknowledgeuseofthiscodebyincludingthisheader
            functionmyTruncate($string$limit$break=""$pad=""){
            //returnwithnochangeifstringisshorterthan$limit
            if(strlen($string)<=$limit)
            return$string;
            
            //is$breakpresentbetween$limitandtheendofthestring?
            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压缩
            
            /*createsacompressedzipfile*/
            functioncreate_zip($files=array()$destination=’’$overwrite=false){
            //ifthezipfilealreadyexistsandoverwriteisfalsereturnfalse
            if(file_exists($destination)&&!$overwrite){returnfalse;}
            //vars
            $valid_files=array();
            //iffileswerepassedin
            if(is_array($files)){
            //cyclethrougheachfile
            foreach($filesas$file){
            //makesurethefileexists
            if(file_exists($file)){
            $valid_files[]=$file;
            }
            }
            }
            //ifwehavegoodfiles
            if(count($valid_files)){
            //createthearchive
            $zip=newZipArchive();
            if($zip>open($destination$overwrite?ZIPARCHIVE::OVERWRITE:ZIPARCHIVE::CREATE)!==true){
            returnfalse;
            }
            //addthefiles
            foreach($valid_filesas$file){
            $zip>addFile($file$file);
            }
            //debug
            //echo’Theziparchivecontains’$zip>numFiles’fileswithastatusof’$zip>status;
            
            //closethezipdone!
            $zip>close();
            
            //checktomakesurethefileexists
            returnfile_exists($destination);
            }
            else
            {
            returnfalse;
            }
            }
            /*****ExampleUsage***/
            $files=array(’filejpg’’filejpg’’filegif’);
            create_zip($files’myzipfilezip’true);
            
            PHP解压缩Zip文件
            
            /**********************
            *@filepathtozipfile
            *@destinationdestinationdirectoryforunzippedfiles
            */
            functionunzip_file($file$destination){
            //createobject
            $zip=newZipArchive();
            //openarchive
            if($zip>open($file)!==TRUE){
            die(’Couldnotopenarchive’);
            }
            //extractcontentstodestinationdirectory
            $zip>extractTo($destination);
            //closearchive
            $zip>close();
            echo’Archiveextractedtodirectory’;
            }
            PHP为URL地址预设http字符串
            
            有时需要接受一些表单中的网址输入但用户很少添加http://字段此代码将为网址添加该字段
            
            if(!preg_match("/^(http|ftp):/"$_POST[’url’])){
            $_POST[’url’]=’http://’$_POST[’url’];
            }
            
            PHP将网址字符串转换成超级链接
            
            该函数将URL和Email地址字符串转换为可点击的超级链接
            
            functionmakeClickableLinks($text){$text=eregi_replace(’(((f|ht){}tp://)[azAZ@:%_+~#?&//=]+)’’<ahref=""></a>’$text);$text=eregi_replace(’([[:space:]()[{}])(www[azAZ@:%_+~#?&//=]+)’<ahref="http://"></a>’$text);$text=eregi_replace(’([_az]+@([az][az]+)+[az]{})’’<ahref="mailto:"></a>’$text);return$text;}
            
            PHP调整图像尺寸
            
            创建图像缩略图需要许多时间此代码将有助于了解缩略图的逻辑
            
            /**********************
            *@filenamepathtotheimage
            *@tmpnametemporarypathtothumbnail
            *@xmaxmaxwidth
            *@ymaxmaxheight
            */
            functionresize_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$imfloor($newx)floor($newy)$x$y);
            return$im;
            }
            
            PHP检测ajax请求
            
            大多数的JavaScript框架如jqueryMootools等在发出Ajax请求时都会发送额外的HTTP_X_REQUESTED_WITH头部信息头当他们一个ajax请求因此你可以在服务器端侦测到Ajax请求
            
            if(!emptyempty($_SERVER[’HTTP_X_REQUESTED_WITH’])&&strtolower($_SERVER[’HTTP_X_REQUESTED_WITH’])==’xmlhttprequest’){
            //IfAJAXRequestThen
            }else{
            //somethingelse
            }

                        

               

上一篇:深入PHP运行环境配置的详解

下一篇:解析php中如何直接执行SHELL