首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 實用技巧大全:文件操作、分頁、上傳、下載、正則、IP驗證等核心功能封裝

     編輯:PHP 相關知識

核心功能函數庫

1. 文件讀取

function PHP_Read($file_name) {
    $fd = fopen($file_name, 'r');
    $buf = '';
    while ($bufline = fgets($fd, 4096)) {
        $buf .= $bufline;
    }
    fclose($fd);
    return $buf;
}

2. 文件寫入(含文件鎖)

function PHP_Write($file_name, $data, $method = "w") {
    $filenum = @fopen($file_name, $method);
    flock($filenum, LOCK_EX);  // 獨佔鎖
    $file_data = fwrite($filenum, $data);
    fclose($filenum);
    return $file_data;
}

3. 靜態頁面生成

function phptohtm($filefrom, $fileto, $u2u = 1) {
    $data = ($u2u == 1) ? PHP_Read($filefrom) : $filefrom;
    PHP_Write($fileto, $data);
    return true;
}

4. 條件記錄數統計

function rec_exist($table, $where) {
    $query = "SELECT COUNT(*) AS num FROM $table $where";
    $result = mysql_query($query) or die('Query Error');
    $row = mysql_fetch_array($result);
    return $row['num'] ?: false;
}

5. 遞歸刪除目錄

function del_DIR($directory) {
    $mydir = dir($directory);
    while ($file = $mydir->read()) {
        $path = "$directory/$file";
        if (is_dir($path) && $file != '.' && $file != '..') {
            del_DIR($path);
        } elseif ($file != '.' && $file != '..') {
            unlink($path);
        }
    }
    $mydir->close();
    rmdir($directory);
}

6. 目錄名合法性檢測

function isen($str) {
    $ret = '';
    for ($i = 0; $i < strlen($str); $i++) {
        $p = ord($str[$i]);
        if (($p < 48 && $p != 45 && $p != 46) ||
            ($p > 57 && $p < 65) ||
            ($p > 90 && $p < 97 && $p != 95) ||
            $p > 122) {
            return false;  // 包含非法字符
        }
        $ret .= chr($p);
    }
    return $ret;
}

7. 通用分頁函數

function splitlist($HALT, $LRLIST, $ECHOCNT, $paper, $table, $where, $page_id, $userid) {
    global $splitstr, $sumcnt;
    // ... 完整分頁邏輯(計算總頁數、生成頁碼鏈接、返回帶 LIMIT 的 SQL 片段)
    // 詳細代碼見原文,核心:自動計算總記錄數、生成分頁導航 HTML、返回限制條數的 WHERE 子句
}

8. 圖片上傳處理

function upload_img($UploadFile, $UploadFile_name, $UploadFile_size, $UploadPath, $max_size = 64) {
    // 文件大小格式化、存在性檢查、移動文件、錯誤處理
    // 詳細代碼見原文
}

常用小技巧速查

IP 地址合法性判斷

// 方法一
if (!strcmp(long2ip(sprintf("%u", ip2long($ip))), $ip)) echo "is ip";

// 方法二:IP 與掩碼匹配
$ip = ip2long('192.168.0.84');
$mask = ip2long('255.255.255.0');
$network = ip2long('192.168.0.0');
if (($ip & $mask) == $network) echo "valid ip and mask";

文件下載 HTTP 頭

header("Content-Type: application/x-download");
header("Content-Disposition: attachment; filename=$file_download_name");
header("Accept-Ranges: bytes");
header("Content-Length: $download_size");
echo $file_content;

FTP 下載支持斷點續傳

header('Pragma: public');
header('Cache-Control: private, no-cache, must-revalidate');
header('Accept-Ranges: bytes');
header('Connection: close');
header("Content-Type: audio/mpeg");
header("Location: ftp://user:pass@host/path/file.rmvb");

正則匹配中文

ereg("^[".chr(0xa1)."-".chr(0xff)."]+$", $str);  // 經典 GB2312 範圍
// 現代建議:preg_match("/^[\x{4e00}-\x{9fa5}]+$/u", $str);  // Unicode 範圍

批量轉換文本中的 URL 為鏈接

function urlParse($str) {
    if (!$str) return $str;
    $types = ['http', 'ftp', 'https'];
    $replace = '\1\2';
    foreach ($types as $type) {
        $str = preg_replace("|($type://)([^\s]*)|", $replace, $str);
    }
    return $str;
}

現代化建議

  • 數據庫操作請改用 PDO 或 mysqli(mysql_* 函數已移除)
  • 分頁邏輯建議封裝為類,支持多種數據源
  • 文件上傳請參考《PHP 文件上傳完整指南》一文的安全最佳實踐
  • 正則處理中文請使用 u 修飾符與 Unicode 碼點範圍
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved