首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

20 個實用 PHP 程式碼片段:從隨機字串到圖片處理完整收錄

     編輯:PHP 相關知識

前言

整理 20 個高頻使用的 PHP 實用函數,涵蓋字串處理、驗證、檔案操作、圖片處理、資料解析等常見需求,可直接複製套用專案中。

1. 可閱讀隨機字串產生器

交替子音母音,適合產生易記密碼:

function readable_random_string($length = 6) {
    $conso = ['b','c','d','f','g','h','j','k','l','m','n','p','r','s','t','v','w','x','y','z'];
    $vocal = ['a','e','i','o','u'];
    $password = '';
    for ($i = 0; $i < $length/2; $i++) {
        $password .= $conso[array_rand($conso)] . $vocal[array_rand($vocal)];
    }
    return $password;
}

2. 通用隨機字串產生器

function generate_rand($length) {
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    $str = '';
    for ($i = 0; $i < $length; $i++) {
        $str .= $chars[random_int(0, strlen($chars)-1)];
    }
    return $str;
}

3. Email 地址編碼防採集

function encode_email($email = 'info@domain.com', $linkText = 'Contact Us', $attrs = 'class="emailencoder"') {
    $email = str_replace(['@', '.'], ['@', '.'], $email);
    $linkText = str_replace(['@', '.'], ['@', '.'], $linkText);
    
    $encoded = '<script type="text/javascript">';
    $encoded .= 'document.write(\'<a href="ma\');';
    $encoded .= 'document.write(\'ilto:\');';
    $encoded .= 'document.write(\'' . implode('\');document.write(\'', str_split($email, 5)) . '\');';
    $encoded .= 'document.write(\'" ' . $attrs . ' >\');';
    $encoded .= 'document.write(\'' . implode('\');document.write(\'', str_split($linkText, 5)) . '\');';
    $encoded .= 'document.write(\'</a>\');';
    $encoded .= '</script>';
    return $encoded;
}

4. Email 格式與 MX 記錄驗證

function is_valid_email($email, $checkMx = false) {
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) return false;
    if ($checkMx) {
        list(, $domain) = explode('@', $email);
        return checkdnsrr($domain, 'MX');
    }
    return true;
}

5. 列出目錄內容

function list_files($dir) {
    if (is_dir($dir) && $handle = opendir($dir)) {
        while (($file = readdir($handle)) !== false) {
            if (!in_array($file, ['.', '..', 'Thumbs.db'])) {
                echo '<a href="' . $dir . $file . '" target="_blank">' . $file . '</a><br>';
            }
        }
        closedir($handle);
    }
}

6. 遞迴刪除目錄

function destroyDir($dir, $virtual = false) {
    $ds = DIRECTORY_SEPARATOR;
    $dir = $virtual ? realpath($dir) : $dir;
    $dir = rtrim($dir, $ds);
    
    if (is_dir($dir) && $handle = opendir($dir)) {
        while (($file = readdir($handle)) !== false) {
            if ($file === '.' || $file === '..') continue;
            $path = $dir . $ds . $file;
            is_dir($path) ? destroyDir($path) : unlink($path);
        }
        closedir($handle);
        return rmdir($dir);
    }
    return false;
}

7. JSON 資料解析

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

8. XML 資料解析

$xmlStr = "<?xml version='1.0'?><users><user id='398'><name>Foo</name><email>foo@bar.com</email></user></users>";
$xml = simplexml_load_string($xmlStr);
foreach ($xml->user as $user) {
    echo $user['id'] . ' ' . $user->name . ' ' . $user->email . '<br>';
}

9. 部落格 Slug 產生器

function create_slug($string) {
    return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $string), '-'));
}

10. 取得真實客戶端 IP

function getRealIpAddr() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) return $_SERVER['HTTP_CLIENT_IP'];
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) return $_SERVER['HTTP_X_FORWARDED_FOR'];
    return $_SERVER['REMOTE_ADDR'];
}

11. 強制檔案下載

function force_download($file) {
    if (isset($file) && file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($file) . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        readfile($file);
        exit;
    }
    echo '檔案不存在';
}

12. 標籤雲產生器

function getCloud(array $data, $minFont = 12, $maxFont = 30) {
    $min = min($data); $max = max($data);
    $spread = $max - $min ?: 1;
    $html = [];
    foreach ($data as $tag => $count) {
        $size = $minFont + ($count - $min) * ($maxFont - $minFont) / $spread;
        $html[] = '<a style="font-size:' . floor($size) . 'px" href="#" title="' . $tag . ' (' . $count . ')">' . htmlspecialchars($tag) . '</a>';
    }
    return implode("\n", $html);
}

13. 字串相似度比較

similar_text($str1, $str2, $percent);
echo $percent; // 相似度百分比

14. Gravatar 通用頭像整合

function show_gravatar($email, $size = 80, $default = '', $rating = 'G') {
    $url = 'https://www.gravatar.com/avatar/' . md5(strtolower(trim($email))) .
           '?s=' . $size . '&r=' . $rating . '&d=' . urlencode($default);
    echo '<img src="' . $url . '" width="' . $size . '" height="' . $size . '" alt="Gravatar">';
}

15. 字詞邊界截斷文字

function myTruncate($string, $limit, $break = ' ', $pad = '...') {
    if (strlen($string) <= $limit) return $string;
    if (false !== ($pos = strpos($string, $break, $limit))) {
        if ($pos < strlen($string) - 1) $string = substr($string, 0, $pos) . $pad;
    }
    return $string;
}

16. 建立 ZIP 壓縮檔

function create_zip(array $files, $dest, $overwrite = false) {
    if (file_exists($dest) && !$overwrite) return false;
    $zip = new ZipArchive();
    if ($zip->open($dest, $overwrite ? ZipArchive::OVERWRITE : ZipArchive::CREATE) !== true) return false;
    foreach ($files as $file) if (file_exists($file)) $zip->addFile($file, basename($file));
    $zip->close();
    return file_exists($dest);
}

17. 解壓縮 ZIP 檔案

function unzip_file($file, $dest) {
    $zip = new ZipArchive();
    if ($zip->open($file) !== true) die('無法開啟壓縮檔');
    $zip->extractTo($dest);
    $zip->close();
    echo '解壓縮完成至 ' . $dest;
}

18. 自動補全 HTTP 協定

if (!preg_match('/^(https?|ftp):/i', $_POST['url'])) {
    $_POST['url'] = 'https://' . $_POST['url'];
}

19. 文字轉可點擊連結

function makeClickableLinks($text) {
    $text = preg_replace('/((https?|ftp):\/\/[^\s]+)/i', '<a href="$1">$1</a>', $text);
    $text = preg_replace('/([\s\(\)\{\}])(www\.[^\s]+)/i', '$1<a href="https://$2">$2</a>', $text);
    $text = preg_replace('/([\w\.-]+@[\w\.-]+\.\w+)/', '<a href="mailto:$1">$1</a>', $text);
    return $text;
}

20. 圖片縮圖產生

function resize_image($src, $dest, $maxW, $maxH) {
    list($w, $h, $type) = getimagesize($src);
    if ($w <= $maxW && $h <= $maxH) return copy($src, $dest);
    
    $ratio = min($maxW/$w, $maxH/$h);
    $newW = (int)($w * $ratio); $newH = (int)($h * $ratio);
    
    $srcImg = match($type) {
        IMAGETYPE_JPEG => imagecreatefromjpeg($src),
        IMAGETYPE_PNG  => imagecreatefrompng($src),
        IMAGETYPE_GIF  => imagecreatefromgif($src),
        default => return false
    };
    $dstImg = imagecreatetruecolor($newW, $newH);
    imagecopyresampled($dstImg, $srcImg, 0, 0, 0, 0, $newW, $newH, $w, $h);
    
    match($type) {
        IMAGETYPE_JPEG => imagejpeg($dstImg, $dest, 90),
        IMAGETYPE_PNG  => imagepng($dstImg, $dest),
        IMAGETYPE_GIF  => imagegif($dstImg, $dest)
    };
    imagedestroy($srcImg); imagedestroy($dstImg);
    return true;
}

總結

這 20 個片段涵蓋了 Web 開發最常見的需求,建議建立個人程式碼庫,並根據專案需求調整參數與錯誤處理。注意:實際部署時請加強輸入驗證與安全防護。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved