除了常見的 HTTP POST 上傳,PHP 也可使用 Socket 直接傳輸檔案。本文提供伺服器端監聽與客戶端發送的完整範例,適用於特殊場景(如內部系統檔案同步、避開 HTTP 限制等)。
<?php
set_time_limit(10);
// error_reporting(0); // 生產環境建議開啟錯誤記錄而非關閉
function varinfo($str) {
echo "<pre>";
var_dump($str);
echo "</pre>";
}
$commonProtocol = getprotobyname("tcp");
$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol);
if ($socket) {
$result = socket_bind($socket, '192.168.3.57', 1337);
if ($result) {
$result = socket_listen($socket, 5);
if ($result) {
echo "監聽成功\n";
}
}
} else {
echo "監聽失敗\n";
}
$path = "e://web//"; // 檔案儲存路徑
while (true) {
$connection = socket_accept($socket);
if ($connection) {
$msg = "telnet succeed!\r\n";
socket_write($connection, $msg, strlen($msg));
$buffer = '';
$fp = null;
while ($flag = socket_recv($connection, $buffer, 1024, 0)) {
if (false !== strpos($buffer, 'filename:')) {
$filename = substr($buffer, 9); // 取得檔名
$filename = $path . $filename;
$fp = fopen($filename, "wb");
continue;
}
if ($fp) {
fwrite($fp, $buffer);
}
}
if ($fp) fclose($fp);
socket_close($connection);
}
}
socket_close($socket);
?>
<?php
$errno = '001';
$errstr = "socket file error";
$fp = fsockopen("192.168.3.57", 1337, $errno, $errstr, 10);
if (!$fp) {
echo "$errstr ($errno)\n";
} else {
$str = "filename:socket_file.bmp";
fwrite($fp, $str);
$out = file_get_contents('../../iphone3G.bmp'); // 讀取要上傳的檔案
if ($out) {
fwrite($fp, $out);
fwrite($fp, 'over'); // 結束標記
echo "上傳成功\n";
}
}
fclose($fp);
?>
filename: 開頭傳遞檔名,以 over 結尾標記傳輸結束,實際應用建議設計更健壯的協議(如長度前綴、JSON 標頭、校驗碼)。fopen($filename, "wb") 確保 Windows 下正確寫入二進位檔案。socket_set_nonblock())搭配 socket_select() 多路複用。upload_max_filesize、post_max_size)