function PHP_Read($file_name) {
$fd = fopen($file_name, 'r');
$buf = '';
while ($bufline = fgets($fd, 4096)) {
$buf .= $bufline;
}
fclose($fd);
return $buf;
}
現代替代:PHP 5.4+ 可直接用 file_get_contents($file_name),更簡潔高效。
function PHP_Write($file_name, $data, $method = 'w') {
$fp = @fopen($file_name, $method);
if (!$fp) return false;
flock($fp, LOCK_EX);
$bytes = fwrite($fp, $data);
fclose($fp);
return $bytes;
}
function phptohtm($source, $target, $isFile = true) {
$data = $isFile ? PHP_Read($source) : $source;
return PHP_Write($target, $data);
}
注意:mysql_* 函數已棄用(PHP 7.0 移除),實務請改用 PDO 或 mysqli。
function rec_exist($table, $where) {
$sql = "SELECT COUNT(*) AS num FROM {$table} {$where}";
$res = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($res);
return $row['num'] > 0 ? $row['num'] : false;
}
function del_DIR($dir) {
$handle = opendir($dir);
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') continue;
$path = "{$dir}/{$file}";
is_dir($path) ? del_DIR($path) : unlink($path);
}
closedir($handle);
rmdir($dir);
}
function isen($str) {
for ($i = 0, $len = strlen($str); $i < $len; $i++) {
$c = ord($str[$i]);
if (($c < 48 && $c !== 45 && $c !== 46) ||
($c > 57 && $c < 65) ||
($c > 90 && $c < 97 && $c !== 95) ||
$c > 122) {
return false; // 含非法字元
}
}
return true;
}
支援:總筆數自動查詢、頁碼範圍顯示、上一頁/下一頁、首尾頁、URL 參數 Base64 雙重編碼傳遞。
function splitlist($HALT, $LRLIST, $ECHOCNT, &$paper, $table, $where, $page_id, $userid) {
global $splitstr, $sumcnt;
// ... 完整邏輯見原始碼,核心回傳帶 LIMIT 的 $where 字串
}
使用說明:呼叫前需設定 $paper、$sumcnt、$enwhere;執行後輸出 echo $splitstr; 顯示頁碼列。
function upload_img($tmpName, $fileName, $fileSize, $uploadPath, $maxSizeKB = 64) {
if ($fileSize > $maxSizeKB * 1024) die('檔案過大');
$dest = $uploadPath . $fileName;
if (file_exists($dest)) die('檔案已存在');
if (!move_uploaded_file($tmpName, $dest)) die('上傳失敗');
return $fileName . ' (' . round($fileSize/1024,1) . ' KB)';
}
| 需求 | 代碼片段 |
|---|---|
| 驗證 IP 格式 | !strcmp(long2ip(sprintf('%u', ip2long($ip))), $ip) |
| Email 正則驗證 | preg_match('/^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,}$/i', $email) |
| 檢測 IP 與網段 | ($ip & $mask) == $network(皆用 ip2long 轉換) |
| 檔案下載標頭 | header('Content-Type: application/x-download'); header('Content-Disposition: attachment; filename="'.$name.'"); |
| FTP 斷點續傳導向 | header('Location: ftp://user:pass@host/file'); |
| 中文正則匹配 | preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $str)(需 u 修飾符) |
| 批量轉換超連結 | 見原始碼 urlParse(),使用 preg_replace_callback 更安全 |
SplFileObject 或 file_get_contents()/file_put_contents()。PDO 預處理語句,防止 SQL 注入。finfo_file() 偵測真實 MIME,避免副檔名偽裝。