Skip to content
Advertisement

PHP file upload works with HTTP form but not with Python script

I’m currently achieving a python project in which I need to have a text file uploaded through HTTP to my server.

At first I was using for convenience an HTTP form and the upload has been working fine. But now, I want it so I don’t have to manually select the file and just have my Python script sending the file for me.

But even if the Apache2 logs indicate that a POST Request have been received by the server while using the Python script, the file is not uploaded.

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 SUCCESSn";
} else {
    echo "<br/>ERROR :n";
}
?> 

WORKING HTML FORM

<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

This script has been tested with httpbin.org/post and I have received only code 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 LOGS

Here are the server logs. The first line is a successful upload by the HTML form, the second is an unsuccessful attempt from the python script.

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"

Can someone indicates me if I need to change something about the script or the php side to have my file uploaded ?

Advertisement

Answer

You named your file 987654321.txt, not filer as expected:

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)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement