7

I'm having a nightmare using PHP to upload files to my server, however when using this simple HTML form, it appears to work:

<html><body>
<form enctype="multipart/form-data" action="uploads.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>

The PHP is then:

<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>

Is there any possible way to send a file via this technique using curl from the command line or a shell script? i.e something along the lines of:

curl -f "@/path/to/my/file;type=text/html" http://mywebserver.com/uploads.php

That particular line gives me: "curl: (22) Failed to connect to ::1: Permission denied" although there is no password on the site etc. I assume this is possible, but I'm getting the syntax wrong?

4

1 回答 1

11

我认为您希望该论点成为大写字母F(对于形式)。小写f代表失败,返回错误代码22。说真的,它在手册中!

-f,--失败

(HTTP)在服务器错误时静默失败(根本没有输出)。这样做主要是为了更好地使脚本等更好地处理失败的尝试。在正常情况下,当 HTTP 服务器无法传递文档时,它会返回一个 HTML 文档来说明这一点(通常还描述了原因等等)。该标志将阻止 curl 输出该标志并返回错误 22。

此方法不是万无一失的,有时会出现不成功的响应代码,尤其是在涉及身份验证时(响应代码 401 和 407)。

-F,--表格

(HTTP) 这让 curl 模拟用户按下提交按钮的填写表单。这会导致 curl 根据 RFC 2388 使用 Content-Type multipart/form-data 发布数据。这可以上传二进制文件等。要强制“内容”部分成为文件,请在文件名前加上 @ 符号。要仅从文件中获取内容部分,请在文件名前加上符号 <。@ 和 < 之间的区别在于 @ 使文件作为文件上传附加在帖子中,而 < 生成文本字段并仅从文件中获取该文本字段的内容。

此外,您还没有命名文件变量。我想你想要:

curl -F "uploadedfile=@/path/to/my/file" http://mywebserver.com/uploads.php
于 2013-04-30T19:50:51.010 回答