简体   繁体   中英

python requests module post to php script

I need to upload some .csv file into a self signed https apache server. My https server is running PHP. My client is running a python script to POST files into the https server. PHP.ini has 20M for upload_file and POST_max_size directives with no extra whitespace. The file i need to upload is only 4kilobytes

my python script:

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

I receive a status code 200 but the file is not in the destination server I believe the error is somewhere in my file_upload.php

$_FILES['userfile']['name'] was the name i was using when i was posting the file from a HTML form which is not the case anymore. I believe i am missing something due to my lack of understanding of the $_FILES variable in PHP - How the file-id should look like when not posting from a form?

<?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 reports the following PHP notice

[Thu Jun 05 09:35:19.120760 2014] [:error] [pid 8030] [client xxx.xxx.xxx.xxx:49207] PHP Warning: Missing boundary in multipart/form-data POST data in Unknown on line 0

[Thu Jun 05 09:35:19.124625 2014] [:error] [pid 8030] [client xxx.xxx.xxx.xxx:49207] PHP Notice: Undefined index: file in /var/www/html/file_upload.php on line 8

[Thu Jun 05 09:35:19.124673 2014] [:error] [pid 8030] [client xxx.xxx.xxx.xxx:49207] PHP Notice: Undefined index: file in /var/www/html/file_upload.php on line 11

[Thu Jun 05 09:35:19.124686 2014] [:error] [pid 8030] [client xxx.xxx.xxx.xxx:49207] PHP Notice: Undefined index: file in /var/www/html/file_upload.php on line 12

Permission my www folder is chown -R www-data.www-data

Here is the solution:

When you want to upload a file using the python module requests read the file as follow:

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

now in the receiving PHP file the $_FILES variable must be used as follow:

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

basically the name for the $_FILES index is the NAME of the label you give when you read your file name in python.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM