整理 20 個高頻使用的 PHP 實用函數,涵蓋字串處理、驗證、檔案操作、圖片處理、資料解析等常見需求,可直接複製套用專案中。
交替子音母音,適合產生易記密碼:
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;
}
function generate_rand($length) {
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$str = '';
for ($i = 0; $i < $length; $i++) {
$str .= $chars[random_int(0, strlen($chars)-1)];
}
return $str;
}
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;
}
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;
}
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);
}
}
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;
}
$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
$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>';
}
function create_slug($string) {
return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $string), '-'));
}
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'];
}
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 '檔案不存在';
}
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);
}
similar_text($str1, $str2, $percent);
echo $percent; // 相似度百分比
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">';
}
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;
}
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);
}
function unzip_file($file, $dest) {
$zip = new ZipArchive();
if ($zip->open($file) !== true) die('無法開啟壓縮檔');
$zip->extractTo($dest);
$zip->close();
echo '解壓縮完成至 ' . $dest;
}
if (!preg_match('/^(https?|ftp):/i', $_POST['url'])) {
$_POST['url'] = 'https://' . $_POST['url'];
}
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;
}
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 開發最常見的需求,建議建立個人程式碼庫,並根據專案需求調整參數與錯誤處理。注意:實際部署時請加強輸入驗證與安全防護。