資深 PHP 開發者都知道,累積常用代碼片段能大幅提升開發效率。本文精選 19 個高頻使用的實用片段,涵蓋 Whois 查詢、簡訊發送、記憶體監控、原始碼顯示、Data URI 生成等實戰場景,助您事半功倍。
根據域名後綴自動選擇對應 WHOIS 伺服器,回傳完整註冊資訊:
<?php
function whois_query($domain) {
$domain = strtolower(trim($domain));
$domain = preg_replace('/^https?:\/\//i', '', $domain);
$domain = preg_replace('/^www\./i', '', $domain);
$domain = explode('/', $domain)[0];
$tld = array_pop(explode('.', $domain));
$servers = array(
'com' => 'whois.internic.net',
'net' => 'whois.internic.net',
'org' => 'whois.pir.org',
'cn' => 'whois.cnnic.net.cn',
// ... 更多 TLD 對應
);
if (!isset($servers[$tld])) die("Error: No matching NIC server for .$tld");
$fp = fsockopen($servers[$tld], 43);
if (!$fp) die("Error: Could not connect to {$servers[$tld]}");
fputs($fp, $domain . "\r\n");
$out = '';
while (!feof($fp)) $out .= fgets($fp, 128);
fclose($fp);
return $out;
}
?>
<?php
require('textmagic-sms-api-php/TextMagicAPI.php');
$router = new TextMagicAPI(array(
'username' => 'your_username',
'password' => 'your_password'
));
$result = $router->send('Wake up!', array(9991234567), true);
// $result 包含發送狀態、訊息 ID 等資訊
?>
<?php
echo "Initial: " . memory_get_usage() . " bytes\n";
for ($i = 0; $i < 100000; $i++) $array[] = md5($i);
for ($i = 0; $i < 100000; $i++) unset($array[$i]);
echo "Final: " . memory_get_usage() . " bytes\n";
echo "Peak: " . memory_get_peak_usage() . " bytes\n";
?>
<?php
$lines = file('https://www.google.com/');
foreach ($lines as $num => $line) {
echo "Line #{$num}: " . htmlspecialchars($line) . "\n";
}
?>
<?php
function data_uri($file, $mime) {
$data = base64_encode(file_get_contents($file));
return "data:$mime;base64,$data";
}
// CSS 中使用:background: url(= data_uri('icon.png', 'image/png') ?>);
?>
這 19 個片段覆蓋 PHP 開發高頻場景,建議收藏並逐步內化為個人/團隊代碼庫核心資產。