本文收錄 23 個高頻 PHP 代碼片段,涵蓋短信/郵件發送、安全防護、用戶識別、文件處理、數據交換等核心場景。每個片段均附帶調用示例,適合快速複製應用於項目中。
需替換 $authKey、$senderId 為自己的賬號信息,手機號需包含國家代碼(如中國 86)。
function send_sms($mobile, $msg) {
$postData = [
'authkey' => 'YOUR_AUTH_KEY',
'mobiles' => $mobile,
'message' => urlencode($msg),
'sender' => 'YOUR_SENDER_ID',
'route' => 'template',
];
$ch = curl_init('https://control.msg91.com/sendhttp.php');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
]);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
需 composer require mandrill/mandrill 並配置 API Key、發件域名 DNS(SPF/DKIM/DMARC)。
function send_email($to, $subject, $html) {
$mandrill = new Mandrill('YOUR_API_KEY');
$message = [
'html' => $html,
'text' => strip_tags($html),
'subject' => $subject,
'from_email' => 'noreply@yourdomain.com',
'from_name' => 'Your App',
'to' => [['email' => $to]],
'track_opens' => true,
];
return $mandrill->messages->send($message);
}
現代建議: 改用 PDO 預處理語句(prepare() + execute()),此函數僅作舊項目兼容參考。
function clean($input) {
if (is_array($input)) return array_map('clean', $input);
$output = (string)$input;
if (get_magic_quotes_gpc()) $output = stripslashes($output);
return htmlentities($output, ENT_QUOTES, 'UTF-8');
}
免費額度有限,生產環境建議使用 MaxMind GeoIP2 本地庫或付費 API。
function detect_city($ip) {
$url = "https://api.ipinfodb.com/v3/ip-city/?key=YOUR_KEY&ip=$ip&format=json";
$data = json_decode(file_get_contents($url), true);
return ($data['cityName'] ?? '') . ', ' . ($data['regionName'] ?? '');
}
function display_sourcecode($url) {
$lines = file($url);
foreach ($lines as $num => $line) {
echo "Line #$num : " . htmlspecialchars($line) . "
";
}
}
需 Access Token,v12+ 版本字段為 fan_count。
function fb_fan_count($page) {
$json = file_get_contents("https://graph.facebook.com/$page?fields=fan_count&access_token=YOUR_TOKEN");
return json_decode($json, true)['fan_count'] ?? 0;
}
遍歷像素取平均,大圖建議先縮略或使用 K-means 聚類。
function dominant_color($image) {
$im = imagecreatefromjpeg($image);
$total = $r = $g = $b = 0;
for ($x = 0; $x < imagesx($im); $x++) {
for ($y = 0; $y < imagesy($im); $y++) {
$rgb = imagecolorat($im, $x, $y);
$r += ($rgb >> 16) & 0xFF;
$g += ($rgb >> 8) & 0xFF;
$b += $rgb & 0xFF;
$total++;
}
}
return sprintf('#%02x%02x%02x', round($r/$total), round($g/$total), round($b/$total));
}
內置主流後綴對應的 WHOIS 服務器,通過 TCP 43 端口查詢。
function is_validemail($email) {
return (int)filter_var($email, FILTER_VALIDATE_EMAIL);
}
function getRealIpAddr() {
foreach (['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'] as $key) {
if (!empty($_SERVER[$key])) {
$ips = explode(',', $_SERVER[$key]);
return trim($ips[0]);
}
}
return 'unknown';
}
使用 preg_replace 替換 eregi_replace(已棄用)。
function makeClickableLinks($text) {
$text = preg_replace('@(https?://\S+)@i', '$1', $text);
$text = preg_replace('@(?$1', $text);
$text = preg_replace('@([\w.-]+@[\w.-]+\.\w+)@', '$1', $text);
return $text;
}
支援從文件加載,建議改用 Redis/資料庫存儲以提升性能。
function force_download($file, $dir = '../log/exports/') {
$path = $dir . $file;
if (!file_exists($path)) return false;
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Length: ' . filesize($path));
readfile($path);
exit;
}
echo json_encode(['id' => 1, 'name' => 'Mohit'], JSON_UNESCAPED_UNICODE);
使用 ZipArchive 類,支援大文件分卷(需擴展)。
調用系統 unzip 命令,Windows 環境建議改用 ZipArchive::extractTo()。
function resize_image($src, $max_w, $max_h) {
list($w, $h, $type) = getimagesize($src);
$ratio = min($max_w/$w, $max_h/$h);
$new_w = (int)($w * $ratio);
$new_h = (int)($h * $ratio);
$dst = imagecreatetruecolor($new_w, $new_h);
$src_im = match($type) {
IMAGETYPE_JPEG => imagecreatefromjpeg($src),
IMAGETYPE_PNG => imagecreatefrompng($src),
IMAGETYPE_GIF => imagecreatefromgif($src),
};
imagecopyresampled($dst, $src_im, 0, 0, 0, 0, $new_w, $new_h, $w, $h);
return $dst;
}
需服務器配置 Postfix/Sendmail,大量發送建議用 SMTP 库(PHPMailer/Symfony Mailer)。
function secsToStr($secs) {
$units = ['年'=>31536000, '月'=>2592000, '天'=>86400, '小時'=>3600, '分鐘'=>60, '秒'=>1];
$str = '';
foreach ($units as $name => $val) {
if ($secs >= $val) {
$num = floor($secs/$val);
$str .= "$num$name";
$secs %= $val;
}
}
return $str ?: '0秒';
}
棄用提示: mysql_* 函數已移除,請使用 mysqli 或 PDO。
$mysqli = new mysqli('localhost', 'root', 'password', 'dbname');
if ($mysqli->connect_errno) die('Connect Error: ' . $mysqli->connect_error);
function list_files($dir) {
$files = array_diff(scandir($dir), ['.', '..', 'Thumbs.db']);
foreach ($files as $f) echo "$f
";
}
function get_client_language($available = ['en','zh','ja'], $default = 'en') {
if (empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) return $default;
foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
$code = substr($lang, 0, 2);
if (in_array($code, $available)) return $code;
}
return $default;
}
function readCSV($file) {
$data = [];
if (($h = fopen($file, 'r')) !== false) {
while (($row = fgetcsv($h, 1024)) !== false) $data[] = $row;
fclose($h);
}
return $data;
}
league/csv、phpmailer/phpmailer、spatie/geocoder 等成熟庫,減少自造輪子。