Python请求模块post到PHP脚本


python requests module post to php script

我需要上传一些。csv文件到自签名https apache服务器。我的https服务器正在运行PHP。我的客户端正在运行一个python脚本POST文件到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);
?>

my apache error.log报告以下PHP通知

[Thu Jun 05 09:35:19.120760 2014] [:error] [pid 8030] [client xxx.xxx.xxx. xxx.]PHP: multipart/form-data POST data在第0行

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

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

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

我的www文件夹是own -R www-data.www-data

解决方案如下:

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

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

现在在接收PHP文件中的$_FILES变量必须如下所示使用:

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

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