整理 23 個高頻使用的 PHP 代碼片段,涵蓋通訊、安全、檔案、圖片、資料格式等面向,適合快速複製調整投入專案。
function sendSms($mobile, $message) {
$authKey = 'YOUR_AUTH_KEY';
$senderId = 'YOUR_SENDER_ID'; // 6 字元
$postData = [
'authkey' => $authKey,
'mobiles' => $mobile,
'message' => urlencode($message),
'sender' => $senderId,
'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,
]);
return curl_exec($ch);
}
function sendEmail($to, $subject, $html) {
require 'Mandrill.php';
$mandrill = new Mandrill('YOUR_API_KEY');
$message = [
'html' => $html,
'subject' => $subject,
'from_email' => 'noreply@example.com',
'from_name' => '系統通知',
'to' => [['email' => $to]],
'track_opens' => true,
];
return $mandrill->messages->send($message);
}
function cleanInput($input) {
if (is_array($input)) {
return array_map(__FUNCTION__, $input);
}
$input = trim($input);
if (get_magic_quotes_gpc()) $input = stripslashes($input);
return htmlentities($input, ENT_QUOTES, 'UTF-8');
}
function detectCity($ip) {
$url = "https://ipinfodb.com/ip_locator.php?ip=" . urlencode($ip);
$html = file_get_contents($url);
if (preg_match('{<li>City : ([^<]*)</li>}i', $html, $m)) $city = $m[1];
if (preg_match('{<li>State/Province : ([^<]*)</li>}i', $html, $m)) $state = $m[1];
return isset($city, $state) ? "$city, $state" : 'UNKNOWN';
}
function fetchSource($url) {
$lines = file($url);
$out = '';
foreach ($lines as $i => $line) {
$out .= "Line #<b>$i</b> : " . htmlspecialchars($line) . "<br>";
}
return $out;
}
function getFbLikes($pageName) {
$data = json_decode(file_get_contents("https://graph.facebook.com/$pageName"));
return $data->likes ?? 0;
}
function dominantColor($imagePath) {
$im = imagecreatefromjpeg($imagePath);
$r = $g = $b = $total = 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('rgb(%d,%d,%d)', round($r/$total), round($g/$total), round($b/$total));
}
function whois($domain) {
$domain = strtolower(trim($domain));
$domain = preg_replace('/^https?:\/\//', '', $domain);
$domain = preg_replace('/^www\./', '', $domain);
$domain = explode('/', $domain)[0];
$tld = array_pop(explode('.', $domain));
$servers = ['com'=>'whois.internic.net','net'=>'whois.internic.net','org'=>'whois.pir.org','tw'=>'whois.twnic.net'];
if (!isset($servers[$tld])) return "Unsupported TLD: $tld";
$fp = fsockopen($servers[$tld], 43);
fputs($fp, "$domain\r\n");
$out = '';
while (!feof($fp)) $out .= fgets($fp, 128);
fclose($fp);
return $out;
}
function isValidEmail($email) {
return (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
}
function getRealIp() {
foreach (['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'] as $key) {
if (!empty($_SERVER[$key])) {
$ip = $_SERVER[$key];
if (strpos($ip, ',') !== false) $ip = explode(',', $ip)[0];
return trim($ip);
}
}
return 'unknown';
}
function autoLink($text) {
$text = preg_replace('@(https?://[-\w.]+[^[:space:]]*)@', '<a href="$1" target="_blank">$1</a>', $text);
$text = preg_replace('/(?
$deny = ['192.168.1.100', '10.0.0.5'];
if (in_array(getRealIp(), $deny)) {
exit('Your IP is blocked.');
}
function forceDownload($filePath, $fileName = null) {
if (!file_exists($filePath)) return false;
$fileName = $fileName ?? basename($filePath);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
exit;
}
header('Content-Type: application/json');
echo json_encode(['id' => 1, 'name' => 'John', 'tags' => ['php', 'api']], JSON_UNESCAPED_UNICODE);
function createZip(array $files, $zipPath, $overwrite = false) {
if (file_exists($zipPath) && !$overwrite) return false;
$zip = new ZipArchive();
if ($zip->open($zipPath, $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($zipPath);
}
function unzip($zipPath, $destDir) {
$zip = new ZipArchive();
if ($zip->open($zipPath) !== true) return false;
$zip->extractTo($destDir);
$zip->close();
return true;
}
function resizeImage($srcPath, $maxW, $maxH, $destPath) {
list($w, $h, $type) = getimagesize($srcPath);
if ($w <= $maxW && $h <= $maxH) return copy($srcPath, $destPath);
$ratio = min($maxW/$w, $maxH/$h);
$newW = (int)($w * $ratio);
$newH = (int)($h * $ratio);
$src = match($type) {
IMAGETYPE_JPEG => imagecreatefromjpeg($srcPath),
IMAGETYPE_PNG => imagecreatefrompng($srcPath),
IMAGETYPE_GIF => imagecreatefromgif($srcPath),
default => return false,
};
$dst = imagecreatetruecolor($newW, $newH);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newW, $newH, $w, $h);
switch ($type) {
case IMAGETYPE_JPEG: imagejpeg($dst, $destPath, 90); break;
case IMAGETYPE_PNG: imagepng($dst, $destPath); break;
case IMAGETYPE_GIF: imagegif($dst, $destPath); break;
}
imagedestroy($src); imagedestroy($dst);
return true;
}
function mailHtml($to, $subject, $html) {
$headers = "From: System <noreply@example.com>\r\n";
$headers .= "Reply-To: noreply@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
return mail($to, $subject, $html, $headers);
}
function secondsToHuman($secs) {
$units = [['year', 31536000], ['month', 2592000], ['week', 604800], ['day', 86400], ['hour', 3600], ['minute', 60], ['second', 1]];
$parts = [];
foreach ($units as [$name, $val]) {
if ($secs >= $val) {
$count = (int)($secs / $val);
$parts[] = "$count $name" . ($count > 1 ? 's' : '');
$secs %= $val;
}
}
return implode(', ', $parts) ?: '0 seconds';
}
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'user', 'pass', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
function listFiles($dir) {
if (!is_dir($dir)) return [];
return array_diff(scandir($dir), ['.', '..']);
}
function detectLanguage(array $supported = ['en','zh-TW','ja'], $default = 'en') {
if (empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) return $default;
foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
$code = strtolower(substr($lang, 0, 2));
if (in_array($code, $supported)) return $code;
}
return $default;
}
function readCsv($path) {
$rows = [];
if (($h = fopen($path, 'r')) !== false) {
while (($row = fgetcsv($h, 1024)) !== false) $rows[] = $row;
fclose($h);
}
return $rows;
}
helpers.php 並用 Composer files 自動載入。這 23 個片段覆蓋了 PHP 專案 80% 的常見需求,建議收藏並依專案慣用風格微調。