You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Curl向PHP服务上传文件时出现“unable to move”错误求助

问题解决:PHP文件上传服务无法接收curl/PowerShell上传的文件

核心问题根源

根据错误日志与目录结构,问题源于两点:

  1. curl命令冗余参数干扰
    你添加的-F "id=fileToUpload"属于多余参数,会影响PHP对上传文件字段的识别逻辑——PHP仅通过fileToUpload字段名读取上传文件,额外参数无意义且可能导致解析异常。

  2. PHP相对路径指向错误
    你的upload.php位于/var/www/html/目录下,而uploads目录与html是同级关系(从目录列表可确认),但代码中使用的"uploads/"会让PHP在/var/www/html/uploads/下寻找目录,实际该路径不存在,正确路径应为../uploads/。

修正方案

修正后的PHP代码

<?php
// 修正路径为上级目录的uploads文件夹
$target_dir = "../uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

// 可选:提前检查并创建目标目录,避免目录缺失导致上传失败
if (!file_exists($target_dir)) {
    mkdir($target_dir, 0777, true);
}

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
    // 可选:输出错误码辅助排查
    echo "Error code: " . $_FILES["fileToUpload"]["error"];
}
?>

修正后的Linux curl命令

curl -X POST -F "fileToUpload=@null.txt" http://127.0.0.1/upload.php

Windows PowerShell上传命令补充

Invoke-RestMethod -Uri http://127.0.0.1/upload.php -Method Post -Form @{fileToUpload = Get-Item "null.txt"}

额外说明

  • 路径修正为核心:必须使用../uploads/指向与html同级的上传目录,否则会因目标目录不存在触发failed to open stream错误。
  • 冗余参数必须移除:删除-F "id=fileToUpload"后,PHP才能正确识别上传文件字段。
  • 目录检查逻辑:添加的file_exists与mkdir判断,可避免因目录意外删除导致的上传失败,提升服务稳定性。

内容的提问来源于stack exchange,提问作者Carlton Chen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 15:46:19