1

I'm to sent an image to the server of one social network using curl. The following code works well if I put the link to the image in $post_params variable. I try to do the same with base64 encoded image and insert base64 code into $post_params variable, but then the code doesn't work. How can I fix the issue and upload base64 image?

<?php
    if (isset($_POST["upload_url"])) {
     
        $upload_url = $_POST["upload_url"];
     
        $post_params['photo'] = '@' . 'image.jpg'; // link
     
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $upload_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_params);
        $result = curl_exec($ch);
        curl_close($ch);
     
        echo $result;
     
    }
    ?>
Ronny
  • 97
  • 10
  • Is there any specific reason why you need to encode it to base64? You can simply send the image. See [here](http://stackoverflow.com/questions/3433542/curl-php-send-image). – Andrei Jun 12 '16 at 00:51
  • @Andrew the point is that I can get this image only as base64 or HTMLImageElement js object after generating it from canvas – Ronny Jun 12 '16 at 01:15

1 Answers1

0

I try to do the same with base64 encoded image and insert base64 code into $post_params variable, but then the code doesn't work.

How doesn't it work? Have you tried using something like runscope or requestb.in to see what the request you're sending looks like? Does the service you're sending it to give you a descriptive error?

How can I fix the issue and upload base64 image?

The file you're sending (image.jpg) is it a normal jpg file? Or is it a base64 version of the file? If the services specifies base64, are they expecting it as a multipart/form-data encoded POST with a file that's base64 encoded? That doesn't make much sense (to me at least).

My guess is they want the image as a base64 encoded string. For that just take your file contents and run it through base64_encode(), then pass that as a string parameter.

Tim Lytle
  • 17,549
  • 10
  • 60
  • 91