Using CURL to POST Images to a Server

Using CURL to POST Images to a Server

cURL is a computer software project providing a library and command-line tool for transferring data using various protocols. The cURL project produces two products, libcurl and cURL . It was first released in 1997. The name originally stood for "see URL". The original author and lead developer is the Swedish developer Daniel Stenberg.

In this tutorial I will show you how to send and store images between servers using cURL and PHP.

CURL Request & Images

//Create an array of images
$imagesArray = array(
    "C:/xampp/htdocs/images/12345/IMAGE001.jpg", 
    "C:/xampp/htdocs/images/12345/IMAGE002.jpg",
    "C:/xampp/htdocs/images/12345/IMAGE003.jpg",
    "C:/xampp/htdocs/images/12345/IMAGE004.jpg",
);

//New array to store the encoded images
$images = array();
foreach ($imagesArray as $image) {
    //Get the contents of the image
    $file  = file_get_contents($image);
    //Base 64 Encode and add to new array
    array_push($images, base64_encode($file));
}
//Set up the data to be sent, auth if you want
$data = array(
    "Username"=> "testUsername",
    "Password"=> "testPassword",
    "References" => array(
        "myId" => 12345
    ),
    "images" => $images             
);

//The URL of your server, mine is localhost for testing
$url = 'localhost/api/imageDownloader.php';
$data_string = json_encode($data);

try {
    $ch = curl_init($url);

    if (FALSE === $ch) {
        echo 'Error in Connection';
    } else {
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        //REMOVE BEFORE GOING LIVE
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: multipart/form-data')
        );
    
        $content = curl_exec($ch);
        if (curl_error($ch)) {
            echo 'error:' . curl_error($ch);
        }

        if (FALSE === $content) {
            echo 'Curl Error:' . curl_error($ch).curl_errno($ch);
        } else {
            $content = json_decode($content);
            
            if ($content) {
                //Output data sent back
                echo "
";
                print_r($content);
            } else {
                echo 'No Content';
            }           
        }
    } 
} catch(Exception $f) {
    echo 'Curl failed with error '.$f->getCode().' ' . $f->getMessage();
}

Download the Images from CURL

Here we will get the images from the CURL request and store them in a folder, then return a JSON response.


//get the Curl Stream and decode it to a variable
$data = json_decode(file_get_contents('php://input'), true);
$jobImages = $data['images'];


//This should put all uploaded files into a new directory called sent
$dirname = 'C:/xampp/htdocs/photographers/jobimages/SENT/';
if (!file_exists($dirname) ) {
    mkdir($dirname, 0777);
    chmod($dirname, 0777);
}

$i = 0;
//Loop through all the images passed and decode them
foreach ($jobImages as $image) {
    $dataDecoded        = base64_decode($image);
    $nextFileName       = "IMAGE00".$i.".jpg";
    
    //Add file to server actual image, thumb for image viewer
    file_put_contents($dirname . $nextFileName, $dataDecoded);
    $i++;
}

$references = array("references" => array(
"theId" => $data['References']['myId']
));   

$result_json = array(
    "success" => true,
    "reason"=> null,
    $references
);

// headers for not caching the results
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');

// headers to tell that result is JSON
header('Content-type: application/json');

// send the result now
echo json_encode($result_json);
 

Categories: Posts