【问题标题】:PHP file upload works with HTTP form but not with Python scriptPHP 文件上传适用于 HTTP 表单,但不适用于 Python 脚本
【发布时间】:2021-09-15 12:02:29
【问题描述】:

我目前正在实现一个 python 项目,其中我需要通过 HTTP 将文本文件上传到我的服务器。

起初,为了方便起见,我使用了 HTTP 表单,并且上传工作正常。 但现在,我想要它,这样我就不必手动选择文件,只需让我的 Python 脚本为我发送文件。

但即使 Apache2 日志表明在使用 Python 脚本时服务器已收到 POST 请求,文件也不会上传。

PHP

<?php
$uploaddir = './uploads/';
$uploadfile = $uploaddir . basename($_FILES['filer']['name']);

print_r($_FILES);
echo "<br/>";
echo $uploaddir;
echo "<br/>";
echo $uploadfile;

if (move_uploaded_file($_FILES['filer']['tmp_name'], $uploadfile)) {
    echo "<br/>UPLOAD SUCCESS\n";
} else {
    echo "<br/>ERROR :\n";
}
?> 

工作 HTML 表单

<form action='processing.php' method="post" enctype="multipart/form-data">
      <p></p>
      <input type="file" name="filer" accept=".txt" id="file_loader">
      <p></p>
      <a href="https://www.commpro.biz/how-and-where-to-pay-using-bitcoin-in-3-easy-steps/" target="_blank">How to pay in bitcoin</a>
      <p></p>
      <input type="submit" name="send_file" value="Send File ">
    </form>

Python

这个脚本已经用 httpbin.org/post 测试过,我只收到了代码 200。

import requests

with open("987654321.txt", "rb") as a_file:

    file_dict = {"987654321.txt": a_file}
    headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0','Origin':"http://www.myurl.com"}
    response = requests.post("http://www.myurl.com/processing.php", files=file_dict,headers=headers)
    print(response.text)
    print(response)

APACHE2 日志

这是服务器日志。第一行是 HTML 表单上传成功,第二行是 python 脚本尝试失败。

127.0.0.1 - - [04/Jul/2021:09:39:46 +0000] "POST /processing.php HTTP/1.1" 302 562 "http://www.myurl.com/" "Mozilla/5.0 (Windows NT 6.1; rv:60.0) Gecko/20100101 Firefox/60.0"
127.0.0.1 - - [04/Jul/2021:09:40:55 +0000] "POST /processing.php HTTP/1.1" 302 523 "-" "Mozilla/5.0 (Windows NT 6.1; rv:60.0) Gecko/20100101 Firefox/60.0"

如果我需要更改脚本或 php 端的某些内容以上传我的文件,有人可以告诉我吗?

【问题讨论】:

  • 如果你有一个重定向响应(302 FOUND 状态),pythons 请求对象可能会隐藏第一个响应,只显示来自后续重定向的响应,这对你的分析来说是违反直觉的。将allow_redirects 设置为false,默认为true。这应该会给你更多的见解。

标签: python php html upload


【解决方案1】:

您将文件命名为 987654321.txt,而不是预期的 filer

import requests

with open("987654321.txt", "rb") as a_file:    
    file_dict = {"filer": a_file}
    response = requests.post("http://www.myurl.com/processing.php", files=file_dict)
    print(response.text)
    print(response)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-14
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 2021-09-20
    相关资源
    最近更新 更多