php实现文件传输
PHP 实现文件传输的方法
使用 move_uploaded_file 函数上传文件
在 HTML 表单中设置 enctype="multipart/form-data",通过 $_FILES 超全局变量获取上传的文件信息。
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload">
<input type="submit" value="Upload File">
</form>
在 PHP 脚本中处理上传的文件:
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
echo "The file " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
使用 FTP 传输文件
通过 PHP 的 FTP 函数库可以实现文件传输到远程服务器。
$ftpServer = "ftp.example.com";
$ftpUsername = "username";
$ftpPassword = "password";
$localFile = "localfile.txt";
$remoteFile = "remotefile.txt";
$connId = ftp_connect($ftpServer);
$loginResult = ftp_login($connId, $ftpUsername, $ftpPassword);
if (ftp_put($connId, $remoteFile, $localFile, FTP_BINARY)) {
echo "Successfully uploaded $localFile to $remoteFile";
} else {
echo "There was a problem while uploading $localFile";
}
ftp_close($connId);
使用 cURL 发送文件
通过 cURL 可以发送文件到远程服务器。
$url = "http://example.com/upload.php";
$filePath = "localfile.txt";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'file' => new CURLFile($filePath)
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
使用 file_put_contents 下载文件
通过 PHP 可以下载远程文件到本地服务器。
$fileUrl = "http://example.com/remote/file.txt";
$localPath = "local/file.txt";
$fileContent = file_get_contents($fileUrl);
if ($fileContent !== false) {
file_put_contents($localPath, $fileContent);
echo "File downloaded successfully";
} else {
echo "Failed to download file";
}
使用 SSH2 传输文件
通过 SSH2 扩展可以在安全通道中传输文件。
$sshHost = "example.com";
$sshUsername = "username";
$sshPassword = "password";
$localFile = "localfile.txt";
$remoteFile = "remotefile.txt";
$connection = ssh2_connect($sshHost, 22);
ssh2_auth_password($connection, $sshUsername, $sshPassword);
if (ssh2_scp_send($connection, $localFile, $remoteFile)) {
echo "File transferred successfully";
} else {
echo "File transfer failed";
}
ssh2_disconnect($connection);
注意事项
- 确保上传目录有正确的写入权限。
- 验证文件类型和大小以防止安全漏洞。
- 使用 HTTPS 或 SFTP 传输敏感文件以提高安全性。
- 对于大文件传输,考虑分块传输或使用专门的库如
GuzzleHttp或Flysystem。
以上方法涵盖了从简单上传到复杂安全传输的多种场景,根据需求选择适合的方案。







