Python script send image to PHP

15,919

You can use requests module for this. it is very easy to use

import requests
url = 'http://messi-fan.org/post'
files = {'file': open('image.png', 'rb')}
r = requests.post(url, files=files)

and in PHP

<?php
print_r($_FILES);
move_uploaded_file($_FILES["file"]["tmp_name"],$_FILES["file"]["name"]);
Share:
15,919
Takeyasu V. Nakazato
Author by

Takeyasu V. Nakazato

Updated on June 04, 2022

Comments

  • Takeyasu V. Nakazato
    Takeyasu V. Nakazato almost 2 years

    Good day. Can somebody help me. My task is to create an python script (client side) that send image to php (server side).

    NOTE: The python script is run in different raspberry pi, and the php server only receive the image via internet.

    Achievement: I can now send a text data from my client to server.

    Problem: My big problem is how can I send the image?

    Any comments and suggestion is very appreciated. Thank You.

    My Python Script:

    import urllib2
    from urllib import urlencode 
    
    # 192.168.5.149 is the ip address of server
    url = "http://192.168.5.149/server/server.php"
    data = {'test':'OK'}
    
    encoded_data = urlencode(data)
    
    website = urllib2.urlopen(url, encoded_data)
    print website.read()
    

    My PHP script:

    <?php
    echo $_POST['test'];
    ?>
    

    When I run the python script, I got "ok" as send by PHP server. That means, the connection is successful.

    EDITED

    Python client:

    import requests
    url = 'http://messi-fan.org/post'
    files = {'file': open('image.png', 'rb')}
    r = requests.post(url, files=files)
    

    PHP server:

    <?php
    $file_path = "C:\\xampp\htdocs\server\php\\";
    
    $file_path = $file_path.basename( $_FILES['file']['name']);
    ?>