首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >8个 PHP 开发常用代码片段

8个 PHP 开发常用代码片段

作者头像
程序猿的栖息地
发布2022-04-29 15:01:59
发布2022-04-29 15:01:59
38700
代码可运行
举报
运行总次数:0
代码可运行

1. 压缩 zip 文件

使用下面的 PHP 片段可以即时压缩 zip 文件

代码语言:javascript
代码运行次数:0
运行
复制
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;  
    }  
}
用法:
<?php
$files=array('file1.jpg', 'file2.jpg', 'file3.gif');  
create_zip($files, 'myzipfile.zip', true); 
?>;

2. 解压文件

代码语言:javascript
代码运行次数:0
运行
复制
function unzip($location,$newLocation)
{
        if(exec("unzip $location",$arr)){
            mkdir($newLocation);
            for($i = 1;$i&lt; count($arr);$i++){
                $file = trim(preg_replace("~inflating: ~","",$arr[$i]));
                copy($location.'/'.$file,$newLocation.'/'.$file);
                unlink($location.'/'.$file);
            }
            return TRUE;
        }else{
            return FALSE;
        }
}
用法
<?php
unzip('test.zip','unziped/test'); //File would be unzipped in unziped/test folder
?>

3. 缩放图片

代码语言:javascript
代码运行次数:0
运行
复制
function resize_image($filename, $tmpname, $xmax, $ymax)  
{  
    $ext = explode(".", $filename);  
    $ext = $ext[count($ext)-1];  
         
    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 &lt;= $xmax && $y &lt;= $ymax)  
        return $im;  
         
    if($x &gt;= $y) {  
        $newx = $xmax;  
        $newy = $newx * $y / $x;  
    }  
    else {  
        $newy = $ymax;  
        $newx = $x / $y * $newy;  
    }  
             
    $im2 = imagecreatetruecolor($newx, $newy);  
    imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);  
    return $im2;   
}

4. 目录清单 使用下面的 PHP 代码片段可以在一个目录中列出所有文件和文件夹

代码语言:javascript
代码运行次数:0
运行
复制
function list_files($dir)
{
    if(is_dir($dir))
    {
        if($handle = opendir($dir))
        {
            while(($file = readdir($handle)) !== false)
            {
                if($file != "." && $file != ".." && $file != "Thumbs.db"/*pesky windows, images..*/)
                {
                    echo '&lt;a target="_blank" href="'.$dir.$file.'"&gt;'.$file.'&lt;/a&gt;'."\n";
                }
            }
            closedir($handle);
        }
    }
}

语法:

代码语言:javascript
代码运行次数:0
运行
复制
<?php
    list_files("images/"); //This will list all files of images folder
?>;

5. 转发数量 使用这个 PHP 片段可以检测你的页面 URL 有多少转发数量

代码语言:javascript
代码运行次数:0
运行
复制
function tweetCount($url) {
    $content = file_get_contents("http://api.tweetmeme.com/url_info?url=".$url);
    $element = new SimpleXmlElement($content);
    $retweets = $element-&gt;story-&gt;url_count;
    if($retweets){
        return $retweets;
    } else {
        return 0;
    }
}
    
语法:
&lt;?php
$url = "http://blog.koonk.com";
$count = tweetCount($url);
return $count;
?&gt;

6. 删除文件夹内容

代码语言:javascript
代码运行次数:0
运行
复制
function Delete($path)
{
    if (is_dir($path) === true)
    {
        $files = array_diff(scandir($path), array('.', '..'));
        foreach ($files as $file)
        {
            Delete(realpath($path) . '/' . $file);
        }
        return rmdir($path);
    }
    else if (is_file($path) === true)
    {
        return unlink($path);
    }
    return false;
}

语法:

代码语言:javascript
代码运行次数:0
运行
复制
&lt;?php
$path = "images/";
Delete($path); // This will delete images folder along with its contents.
?&gt;

7. 生成二维码

代码语言:javascript
代码运行次数:0
运行
复制
function qr_code($data, $type = "TXT", $size ='150', $ec='L', $margin='0')  
{
     $types = array("URL" =--&gt; "http://", "TEL" =&gt; "TEL:", "TXT"=&gt;"", "EMAIL" =&gt; "MAILTO:");
    if(!in_array($type,array("URL", "TEL", "TXT", "EMAIL")))
    {
        $type = "TXT";
    }
    if (!preg_match('/^'.$types[$type].'/', $data))
    {
        $data = str_replace("\\", "", $types[$type]).$data;
    }
    $ch = curl_init();
    $data = urlencode($data);
    curl_setopt($ch, CURLOPT_URL, 'http://chart.apis.google.com/chart');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, 'chs='.$size.'x'.$size.'&cht=qr&chld='.$ec.'|'.$margin.'&chl='.$data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;

语法

代码语言:javascript
代码运行次数:0
运行
复制
&lt;?php
header("Content-type: image/png");
echo qr_code("http://koonk.com", "URL");
?&gt;

8. 把文本转换成图片

代码语言:javascript
代码运行次数:0
运行
复制
&lt;?php
header("Content-type: image/png");
$string = $_GET['text'];
$im = imagecreatefrompng("images/button.png");
$color = imagecolorallocate($im, 255, 255, 255);
$px = (imagesx($im) - 7.5 * strlen($string)) / 2;
$py = 9;
$fontSize = 1;
imagestring($im, fontSize, $px, $py, $string, $color);
imagepng($im);
imagedestroy($im);
?&gt;
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-05-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序猿的栖息地 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档