整理 20 個高頻使用的 PHP 片段,涵蓋隨機字串、郵件驗證、目錄操作、JSON/XML 解析、Slug 生成、真實 IP 取得、強制下載、標籤雲、相似度比對、Gravatar、斷詞截斷、ZIP 壓縮解壓、URL 處理、超連結轉換、圖片縮圖、AJAX 偵測等,適合收藏備查。
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($len) {
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$rand = '';
for ($i = 0; $i < $len; $i++) $rand .= $chars[random_int(0, strlen($chars)-1)];
return $rand;
}
function encode_email($email='info@domain.com', $linkText='Contact Us', $attrs='class="emailencoder"') {
$email = str_replace(['@','.'], ['@','.'], $email);
$linkText = str_replace(['@','.'], ['@','.'], $linkText);
$parts = ['',''];
$encoded = '';
return $encoded;
}
function is_valid_email($email, $check_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 ($check_mx) {
list(, $domain) = explode('@', $email);
return checkdnsrr($domain, 'MX');
}
return true;
}
function list_files($dir) {
if (is_dir($dir) && $handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (!in_array($file, ['.','..','Thumbs.db']))
echo "{$file}
\n";
}
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 (in_array($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
$xml = simplexml_load_string($xml_string);
foreach ($xml->user as $user) {
echo $user['id'] . ' ' . $user->name . ' ' . $user->email . '
';
}
function create_slug($string) {
return 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-Length: ' . filesize($file));
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
readfile($file);
} else { echo 'No file selected'; }
}
function getCloud($data=[], $min=12, $max=30) {
$minC = min(array_values($data)); $maxC = max(array_values($data));
$spread = $maxC - $minC ?: 1;
$tags = [];
foreach ($data as $tag => $count) {
$size = $min + ($count - $minC) * ($max - $min) / $spread;
$tags[] = ''.htmlspecialchars($tag).'';
}
return join("\n", $tags);
}
// 用法
$arr = ['Actionscript'=>35,'Adobe'=>22,'Array'=>44,'Background'=>43];
echo getCloud($arr, 12, 36);
similar_text($str1, $str2, $percent);
echo $percent; // 相似百分比
function show_gravatar($email, $size=80, $default='', $rating='G') {
echo '
';
}
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;
}
function create_zip($files=[], $dest='', $overwrite=false) {
if (file_exists($dest) && !$overwrite) return false;
$valid = array_filter($files, 'file_exists');
if (!$valid) return false;
$zip = new ZipArchive();
if ($zip->open($dest, $overwrite ? ZipArchive::OVERWRITE : ZipArchive::CREATE) !== true) return false;
foreach ($valid as $file) $zip->addFile($file, basename($file));
$zip->close();
return file_exists($dest);
}
// 用法
create_zip(['file1.jpg','file2.jpg'], 'backup.zip', true);
function unzip_file($file, $dest) {
$zip = new ZipArchive();
if ($zip->open($file) !== true) die('Could not open archive');
$zip->extractTo($dest);
$zip->close();
echo 'Archive extracted to '.$dest;
}
if (!preg_match('/^(http|ftp):/i', $_POST['url'])) {
$_POST['url'] = 'https://'.$_POST['url'];
}
function makeClickableLinks($text) {
$text = preg_replace('/((f|ht)tp:\/\/[-a-zA-Z0-9@:%_+.~#?&\/=]+)/i', '$1', $text);
$text = preg_replace('/([\s(\[{])(www\.[-a-zA-Z0-9@:%_+.~#?&\/=]+)/i', '$1$2', $text);
$text = preg_replace('/([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})/i', '$1', $text);
return $text;
}
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 = $y * $xmax / $x; }
else { $newy = $ymax; $newx = $x * $ymax / $y; }
$im2 = imagecreatetruecolor($newx, $newy);
imagecopyresampled($im2, $im, 0,0,0,0, $newx, $newy, $x, $y);
return $im2;
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
// AJAX 請求
} else {
// 一般請求
}