Created
October 29, 2020 14:00
-
-
Save codetycon/e7fd146b44aeee3633367e8e24d6b19c to your computer and use it in GitHub Desktop.
Upload file using PHP curl to API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function getCurlValue($filepath) | |
{ | |
$contentType = mime_content_type($filepath); | |
$filename = basename($filepath); | |
// PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax | |
// See: https://wiki.php.net/rfc/curl-file-upload | |
if (function_exists('curl_file_create')) { | |
return curl_file_create($filepath, $contentType, $filename); | |
} | |
// Use the old style if using an older version of PHP | |
$value = "@{$filepath};filename=" . $filename; | |
if ($contentType) { | |
$value .= ';type=' . $contentType; | |
} | |
return $value; | |
} | |
$filepath = realpath ("de2c5d33-958b-4ce2-8398-e14e5dc9098b.zip"); | |
$cfile = getCurlValue($filepath); | |
$POST_DATA = array( | |
'file' => $cfile | |
); | |
$arr = array( | |
// "Content-Type: application/zip; charset=utf-8", | |
"API-Key: API_KEYS_GOES_HERE_IF_REQUIRED" | |
); | |
$curl = curl_init(); | |
curl_setopt($curl, CURLOPT_URL, 'https://your_domain.com/'); | |
curl_setopt($curl, CURLOPT_TIMEOUT, 30); | |
curl_setopt($curl, CURLOPT_POST, 1); | |
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); | |
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); | |
curl_setopt($curl, CURLOPT_POSTFIELDS, $POST_DATA); | |
curl_setopt($curl, CURLOPT_HTTPHEADER, $arr); | |
$response = curl_exec($curl); | |
if($errno = curl_errno($curl)) { | |
echo $error_message = curl_strerror($errno); | |
echo "cURL error ({$errno}):\n {$error_message}"; | |
} else { | |
echo "<h2>File Uploaded</h2>"; | |
} | |
curl_close ($curl); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment