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

PHP 實用代碼片段大全:21 個高頻場景即拿即用

     編輯:PHP 綜合知識

21 個 PHP 實用代碼片段:從隨機字符串到圖片處理

整理自實戰項目,涵蓋字符串、驗證、文件、網絡、圖片、壓縮、SEO 等高頻場景,代碼經測試可直接集成。建議按需複製,注意 PHP 版本兼容性 (部分函數如 eregi 已棄用,請改用 preg_match)。

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 = 1; $i <= $length/2; $i++) {
        $password .= $conso[array_rand($conso)] . $vocal[array_rand($vocal)];
    }
    return $password;
}

2. 通用隨機字符串 (密碼、Token)

function generate_rand($l) {
    $c = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    $rand = '';
    for ($i = 0; $i < $l; $i++) {
        $rand .= $c[random_int(0, strlen($c)-1)]; // PHP 7+ 用 random_int
    }
    return $rand;
}

3. 郵箱地址實體編碼 (防采集)

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

4. 郵箱驗證 (含可選 MX 記錄檢查)

function is_valid_email($email, $test_mx = false) {
    if (!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/i', $email)) return false;
    if ($test_mx) {
        list(, $domain) = explode('@', $email);
        return checkdnsrr($domain, 'MX'); // PHP 5.3+ 支援 Windows
    }
    return true;
}

5. 列出目錄文件 (排除 . .. Thumbs.db)

function list_files($dir) {
    if (is_dir($dir) && $handle = opendir($dir)) {
        while (($file = readdir($handle)) !== false) {
            if (!in_array($file, ['.','..','Thumbs.db'])) {
                echo "<a target='_blank' href='$dir$file'>$file</a><br>\n";
            }
        }
        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)) {
            if (in_array($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 (SimpleXML)

$xml = simplexml_load_string($xmlString);
foreach ($xml->user as $user) {
    echo $user['id'] . ' ' . $user->name . ' ' . $user->email . '<br/>';
}

9. 生成 URL 友好 Slug

function create_slug($string) {
    return 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;
    }
}

12. 生成標簽雲

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

13. 字符串相似度

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

14. Gravatar 頭像

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

15. 斷詞截斷 (保持單詞完整)

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

16. 創建 ZIP 壓縮包

function create_zip($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('Could not open archive');
    $zip->extractTo($dest);
    $zip->close();
}

18. 補全 URL 協議頭

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

19. 文本自動轉超鏈接 (URL/Email)

function makeClickableLinks($text) {
    $text = preg_replace('/\b((https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i', '<a href="$1">$1</a>', $text);
    $text = preg_replace('/\b(www\.[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i', '<a href="https://$1">$1</a>', $text);
    $text = preg_replace('/\b([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,})\b/i', '<a href="mailto:$1">$1</a>', $text);
    return $text;
}

20. 圖片縮略圖生成 (等比縮放)

function resize_image($filename, $tmpname, $xmax, $ymax) {
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    $im = match($ext) {
        'jpg','jpeg' => imagecreatefromjpeg($tmpname),
        'png' => imagecreatefrompng($tmpname),
        'gif' => imagecreatefromgif($tmpname),
        default => false
    };
    if (!$im) return false;
    $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; }
    $im2 = imagecreatetruecolor($newx, $newy);
    imagecopyresampled($im2, $im, 0,0,0,0, $newx, $newy, $x, $y); // 高質量
    return $im2;
}

21. 檢測 AJAX 請求

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
    // AJAX 請求
}

現代化提示:原文使用 eregi、split、rand 等已棄用函數,上述代碼已替換為 preg_match、explode、random_int/array_rand、imagecopyresampled 等現代替代品。實際使用請根據 PHP 版本調整。

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