How to recieve an image (file) with PHP that was submitted over a POST request

16,119

Solution 1

You couold read this example http://www.w3schools.com/php/php_file_upload.asp

which basically does something like this:

<?php
$target_dir = "uploads/";
$target_dir = $target_dir . basename( $_FILES["uploadFile"]["name"]);
$uploadOk=1;

if (move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $target_dir)) {
    echo "The file ". basename( $_FILES["uploadFile"]["name"]). " has been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
}

The key is on the $_FILES global array.

To check if there were an error before appliying that example, you could use this example:

if ($_FILES['file']['uploadFile'] === UPLOAD_ERR_OK) { 
/**
* Do the upload process mentioned above
**/
} else { 
/**
* There were an error
**/ 
} 

Solution 2

If you want to upload using a mobile app for example, you have to send via POST the base64 content of the image with the mimetype or the file extension of it, and then use something like this:

  • Send the content base64 encoded and urlescaped.
  • Receive the content and do base64 decode and then urldecode.

Then in PHP just do:

<?php
$base64decodedString = base64_decode(urldecode($_POST['yourInputString']));
$fileName = $_POST['fileNameString']; 
file_put_contents($fileName, $base64decodedString);

This will generate a file with the content

Share:
16,119
sparecycle
Author by

sparecycle

Updated on June 07, 2022

Comments

  • sparecycle
    sparecycle over 1 year

    I have a file: success.jpg

    I would like to send this file over an HTTP POST request and have it land in a public directory on my server.

    I have a simple HTML form and PHP processor that work if I'm uploading from the browser: php.net/manual/en/features.file-upload.post-method.php

    I'm trying to drop the use of a form altogether and just pass data over POST to a URL (e.g. myimageserver.com/public/upload.php).

    It seems that I can use the PHP function move_uploaded_file and it even talks about using POST here: http://php.net/manual/en/function.move-uploaded-file.php but it doesn't provide the code which can receive and store a file that has been uploaded with POST.

    Has anyone ever done something similar?