PHP ftp_put无法将本地文件复制到远程服务器问题求助
FTP上传报错:
ftp_put(): Can't open that file: No such file or directory 问题详情
本地运行源码时可正常通过FTP复制文件,但部署到远程服务器后出现以下错误:
Warning: ftp_put(): Can't open that file: No such file or directory in C:\xampp\htdocs\samet\cmsdemo\FTPManager.php on line 59
已尝试开放文件权限、设置FTP权限等方法,问题仍未解决。
- 远程路径:
public_html/ds/gediz/Bornova/16.html - 服务器端报错时的本地路径:
C:/cmslib/artsysdepo/gediz/Bornova/16.html
相关代码
//此处已定义FTP用户名和密码,为隐私已删除 class FTPManager { public function sendFilesToFtp($libraryPath, $customerName, $branch) { //.....其余代码 ftp_pasv($ftpConnection, true); $requiredFiles = scandir($libraryPath . "/" . $customerName . "/" . $branch); foreach ($requiredFiles as $file) { var_dump($file); if ($file !== '.' && $file !== '..') { $localFilePath = $libraryPath . "/" . $customerName . "/" . $branch . '/' . $file; $remoteFilePath = $remoteDirectory . '/' . $file; if (ftp_put($ftpConnection, $remoteFilePath, $localFilePath, FTP_BINARY)) { echo "File uploaded:" . $file; } else { echo "Error while uploading file: $file<br/>"; } } } ftp_close($ftpConnection); } catch (Exception $e) { echo 'Error: ' . $e->getMessage() . '<br/>'; } } ?>
排查与解决方法
1. 修正服务器路径错误
本地运行时C:/cmslib/...是Windows本地路径,但远程服务器(大概率为Linux系统)不存在该路径。需:
- 将待上传文件同步到服务器的实际存储目录,而非沿用本地Windows路径
- 检查
$libraryPath参数在服务器环境中的实际值,确认指向服务器上的有效路径
2. 统一路径分隔符
Windows用\、Linux用/,用PHP内置常量DIRECTORY_SEPARATOR拼接路径,避免跨系统错误:
// 替换原路径拼接逻辑 $localDir = implode(DIRECTORY_SEPARATOR, [$libraryPath, $customerName, $branch]); $requiredFiles = scandir($localDir); $localFilePath = implode(DIRECTORY_SEPARATOR, [$localDir, $file]);
3. 前置文件状态检查
在ftp_put前添加检查,提前定位问题:
if (!file_exists($localFilePath)) { echo "本地文件不存在:$localFilePath<br/>"; continue; } if (!is_readable($localFilePath)) { echo "无权限读取本地文件:$localFilePath<br/>"; continue; }
4. 确保远程目录存在
ftp_put不会自动创建远程目录,需提前检查并递归创建:
$remoteDir = dirname($remoteFilePath); if (!ftp_chdir($ftpConnection, $remoteDir)) { $dirs = explode('/', $remoteDir); $currentPath = ''; foreach ($dirs as $dir) { $currentPath .= "/$dir"; if (!ftp_chdir($ftpConnection, $currentPath)) { if (!ftp_mkdir($ftpConnection, $currentPath)) { echo "无法创建远程目录:$currentPath<br/>"; break; } ftp_chdir($ftpConnection, $currentPath); } } }
5. 验证服务器进程权限
确认运行PHP的服务器进程(Apache/Nginx/PHP-FPM)对目标文件有读取权限,权限不足也会触发该错误。
内容的提问来源于stack exchange,提问作者Samet Topal
相关产品推荐
相关产品推荐

