【问题标题】:python requests module post to php scriptpython请求模块发布到php脚本
【发布时间】:2014-07-26 05:57:26
【问题描述】:

我需要将一些 .csv 文件上传到自签名的 https apache 服务器。 我的 https 服务器正在运行 PHP。我的客户端正在运行一个 python 脚本来将文件发布到 https 服务器。 PHP.ini 有 20M 用于 upload_file 和 POST_max_size 指令,没有额外的空格。我需要上传的文件只有 4kb

我的 python 脚本:

import requests
username = "user"
password = 'password'
myfile = "/full/path/to/myfile.csv"
url = "https://www.mydomain.com/file_upload.php"

files = {'file': open(myfile, 'rb')}

r = requests.post(url, files=files, auth=(username, password), verify=False)
print r.text
print r.status_code

我收到状态码 200,但文件不在目标服务器中 我相信错误出现在我的 file_upload.php 中

$_FILES['userfile']['name'] 是我从 HTML 表单发布文件时使用的名称,现在不再是这种情况了。 我相信由于我对 PHP 中的 $_FILES 变量缺乏了解,我遗漏了一些东西 - 不从表单发布时文件 ID 应该是什么样子?

<?php

$uploaddir = '/var/www/html/uploads/';
$uploadfile = $uploaddir . basename($_FILES['file-id']['name']);

move_uploaded_file($_FILES['file-id']['tmp_name'], $uploadfile);
error_log(print_r($_FILES['file-id']['error']), 3, $error_log_file);

?>

我的 apache error.log 报告以下 PHP 通知

[Thu Jun 05 09:35:19.120760 2014] [:error] [pid 8030] [client xxx.xxx.xxx.xxx:49207] PHP 警告:multipart/form-data POST 数据在 Unknown on第 0 行

[Thu Jun 05 09:35:19.124625 2014] [:error] [pid 8030] [client xxx.xxx.xxx.xxx:49207] PHP 注意:未定义索引:/var/www/html/file_upload 中的文件.php 在第 8 行

[Thu Jun 05 09:35:19.124673 2014] [:error] [pid 8030] [client xxx.xxx.xxx.xxx:49207] PHP 注意:未定义索引:/var/www/html/file_upload 中的文件.php 在第 11 行

[Thu Jun 05 09:35:19.124686 2014] [:error] [pid 8030] [client xxx.xxx.xxx.xxx:49207] PHP 注意:未定义索引:/var/www/html/file_upload 中的文件.php 在第 12 行

权限 我的 www 文件夹是 chown -R www-data.www-data

【问题讨论】:

  • 我看到的第一个错误,在 PHP 脚本中您使用“file-id”,但在请求“file”中。这就是为什么出现通知的原因。我不知道python,但我认为你的请求不是多部分形式。
  • 谢谢,那是因为我在这个线程中将文件重命名为 file-id 以避免混淆

标签: php python post https python-requests


【解决方案1】:

解决办法如下:

当您想使用 python 模块上传文件时,请按如下方式读取文件:

files = {'testname': open(myfile, 'rb')}

现在在接收 PHP 文件中,$_FILES 变量必须按如下方式使用:

$uploadfile = $uploaddir . basename($_FILES['testname']['name']);
move_uploaded_file($_FILES['testname']['tmp_name'], $uploadfile);

基本上 $_FILES 索引的名称是您在 python 中读取文件名时给出的标签的名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 2013-07-25
    • 1970-01-01
    • 2023-01-04
    • 1970-01-01
    • 1970-01-01
    • 2012-10-20
    相关资源
    最近更新 更多