AAA
AAA

Reputation: 2032

Get $_FILES from curl without HTML form

If someone were to upload an image via a form:

<form method="post" accept="image/*" enctype="multipart/form-data">
    <input size="28" name="image_upload" type="file">
    <input type="submit" value="Submit">
</form>

In PHP you can get the uploaded image_upload via $_FILES variable:

if(isset($_FILES['image_upload']))
     var_dump($_FILES['image_upload'])

And you can proceed to do things with it, such as show the tmp_name and can move_uploaded_file.

How do I allow someone to upload an image if they were to use CURL, like this, but without the form?

   $POST_DATA = array(
    'ImageData' => file_get_contents('image.jpg'),
    );
    $handle = curl_init($url);
    curl_setopt($handle, CURLOPT_URL, 'http://example.com/?image');
    curl_setopt($handle, CURLOPT_POSTFIELDS, 'image={$POST_DATA['ImageData']}');
    curl_setopt($handle, CURLOPT_POST, 1);
    curl_close($handle);

Then in the page in which I receive the curl request...

if(isset($_REQUEST['image']))
    var_dump($_FILES); // won't work because i can't get $_FILES from $_POST['image']
var_dump($_POST['image']) // will only show the image data.. i want it to show what the $_FILES variable would normally show.

Upvotes: 1

Views: 207

Answers (2)

cmorrissey
cmorrissey

Reputation: 8583

This is answered right in the php documents ... Example #2 (http://uk.php.net/manual/en/function.curl-setopt.php)

<?php

/* http://localhost/upload.php:
print_r($_POST);
print_r($_FILES);
*/

$ch = curl_init();

$data = array('name' => 'Foo', 'file' => '@/home/user/test.png');

curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);
?>

Upvotes: 1

Aleksandar Vasić
Aleksandar Vasić

Reputation: 593

I beleive cURL can POST files like this:

$post = array('file_contents'=>'@'.$file_name_with_full_path);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

I've tested this a lot of times, always worked for me. Full code would be:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://www.somerandomurl.com/test.php');
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('file_contents'=>'@'.$file_name_with_full_path));
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result=curl_exec ($ch);
curl_close ($ch);
echo $result;

Upvotes: 1

Related Questions