Core PHP

Uploading an Image via Post

This PHP example program demonstrates how to upload an image file via post.

PostImage.php

<?php

// Set the protocol
if (!empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) == 'on' || $_SERVER['HTTPS'] == '1')) {
	$sProtocol = 'https';
} else {
	$sProtocol = 'http';
}
// The base path for this PHP file and the receiver
$sUrlBase = $sProtocol."://".$_SERVER['SERVER_NAME'].":".$_SERVER['SERVER_PORT'].dirname($_SERVER["PHP_SELF"]);
// The URL of the receiving PHP script
$sUrl = $sUrlBase.'/ReceiveImage.php';

if (function_exists('curl_file_create')) {
    $qImageContent = curl_file_create("./XoaXFavIcon.png", 'image/png');
} else {
    $qImageContent = '@' . realpath("./XoaXFavIcon.png", 'image/png');
}

$qaData = array('CURLFile'=> $qImageContent);

$qCurl = curl_init($sUrl);
curl_setopt($qCurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($qCurl, CURLOPT_POST, true);
curl_setopt($qCurl, CURLOPT_POSTFIELDS, $qaData);
$sResult=curl_exec ($qCurl);
curl_close ($qCurl);

echo $sResult;
echo '<hr />';
echo '<img src="XoaXFavIcon.png" \>';
echo '<p>Post:</p>';
echo '<pre>'.json_encode($qaData, JSON_PRETTY_PRINT).'</pre>';
?>
 

ReceiveImage.php

<?php

$sTargetDir = 'uploads';
if ($_FILES["CURLFile"]["tmp_name"] != "") {
    $TempFile = $_FILES["CURLFile"]["tmp_name"];
    
    $sBase = basename($_FILES["CURLFile"]["name"]);
    if(move_uploaded_file($TempFile, $sTargetDir . "/" . $sBase)) {
        echo "The image has been uploaded.";
    } else {
        echo "The image upload failed.";
    }
}

?>
 

Output

 
 

© 2007–2025 XoaX.net LLC. All rights reserved.