PHP Curl with attachment ( CurlFile)

Sender PHP Code

<form method="post" action="<?=$_SERVER["PHP_SELF"] ?>" enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="submit" value="Upload" />


    echo "<pre>";
    echo "</pre>";

    // Create a CURLFile object / procedural method 
    $cfile = curl_file_create($_FILES["file"]["tmp_name"],$_FILES["file"]["type"],$_FILES["file"]["name"]); // try adding 

    // Create a CURLFile object / oop method 
    #$cfile = new CURLFile("resource/test.png","image/png","testpic"); // uncomment and use if the upper procedural method is not working.

    // Assign POST data
    $imgdata = array("file" => $cfile);

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $target);
    #curl_setopt($curl, CURLOPT_USERAGENT,"Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15");
    curl_setopt($curl, CURLOPT_HTTPHEADER,array("Content-Type: multipart/form-data"));
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // stop verifying certificate
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($curl, CURLOPT_POST, true); // enable posting
    curl_setopt($curl, CURLOPT_POSTFIELDS, $imgdata); // post images 
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); // if any redirection after upload
    $r = curl_exec($curl); 

    echo "<h1>Result</h1>";
    echo "<pre>";
    echo "</pre>";

Receiver PHP Code


$uploaddir = realpath("./") . "/";
$uploadfile = $uploaddir . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "Possible file upload attack!\n";

echo "<pre>";
echo "Here is some more debugging info:";
echo "\n<hr />\n";
echo "</pre>";

Ref :

You may also like...