Tom Canfarotta
Tom Canfarotta

Reputation: 773

HTML JPG Upload to PHP Script to POST RESTful Web Service

I have a need for auser to upload two images and then for the images to be base64 enocded and posted to a restful webservice.

I am able to encode and post the images and get a successful response when i use a file on the server but what i need to do is use the image being uploaded by the end user dynamically.

Here is my form:

 <form action="dcams.php" enctype="multipart/form-data" method="post">
    <input name="MAX_FILE_SIZE" type="hidden" value="30000"> Send this
    file: <input name="front" type="file"> And this file: <input name=
    "back" type="file"> <input type="submit" value="Send Files">
</form>

Here is my PHP Script that works with a static file on server but I need to get the file contents from the posted images:

 <?php
header('Content-type: application/json');

$imagedata_front = file_get_contents("front.jpg");
$base64_front    = base64_encode($imagedata_front);

$imagedata_back = file_get_contents("back.jpg");
$base64_back    = base64_encode($imagedata_back);

$url = "https://xxxxxxxxxxxx.com";

$data        = array(
"user" => "",
"pass" => "",
"target" => array(
    "license" => array(
        "front" => "$base64_front",
        "back" => "$base64_back",
        "state" => "CT"
    ),
    "age" => "21+"
),
"service" => ""
);
$data_string = json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 200);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

$result = curl_exec($ch);
echo "$result";
?> 

What I want to do is something like this:

$imagedata_front = $_FILES['front'];
$base64_front    = base64_encode($imagedata_front);

$imagedata_back = $_FILES['back';
$base64_back    = base64_encode($imagedata_back);

But this does not work. Does anyone know the proper way to do this?

Upvotes: 0

Views: 1123

Answers (1)

awinwood
awinwood

Reputation: 135

you were close with your original attempt. the $_FILES array is an associative array and one of the entries (tmp_name) is the location on the server of the file that has been uploaded.

Here is a very good link to a single image example with error checking, max file size handing and file type checking. You'll need to move the uploaded file before accessing them.

$imagedata_front = file_get_contents('/path/to/moved/file');
$base64_front    = base64_encode($imagedata_front);

$imagedata_back = file_get_contents('/path/to/moved/file');
$base64_back    = base64_encode($imagedata_back);

Upvotes: 1

Related Questions