PHP จะใช้ cURL Upload File อัพรูปในแบบฟอร์มอันนี้ต้องเขียนยังไงอะครับ
Code (PHP)
$file_name_with_full_path = realpath('./sample.jpeg');
$post = array('extra_info' => '123456','file_contents'=>'@'.$file_name_with_full_path);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);
Date :
2013-09-16 10:34:40
By :
mr.win
Code (PHP)
<?php
header('Content-type: application/json');
$output = [];
if (empty($_FILES['image']['name']) || !isset($_FILES['image']['error'])) {
$_FILES['image']['error'] = 4;
}
if ($_POST && $_FILES) {
// @link https://www.php.net/manual/en/features.file-upload.errors.php#115746
$phpFileUploadErrors = array(
0 => 'There is no error, the file uploaded with success',
1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3 => 'The uploaded file was only partially uploaded',
4 => 'No file was uploaded',
6 => 'Missing a temporary folder',
7 => 'Failed to write file to disk.',
8 => 'A PHP extension stopped the file upload.',
);
$uploadFolder = __DIR__ . DIRECTORY_SEPARATOR . 'uploaded';
$allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (isset($_FILES['image']['error']) && $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
$output['error'] = true;
$output['message'] = $phpFileUploadErrors[$_FILES['image']['error']];
} else {
if (!is_dir($uploadFolder)) {
$oldumask = umask(0);
mkdir($uploadFolder, 0777);
umask($oldumask);
unset($oldumask);
}
$moveToFileName = $uploadFolder . DIRECTORY_SEPARATOR . $_FILES['image']['name'];
if (move_uploaded_file($_FILES['image']['tmp_name'], $moveToFileName)) {
$Finfo = new finfo();
$output['uploadedMimeType'] = $Finfo->file($moveToFileName, FILEINFO_MIME_TYPE);
unset($Finfo);
if (in_array(strtolower($output['uploadedMimeType']), $allowedMimeTypes)) {
http_response_code(201);
$output['uploadSuccess'] = true;
$output['message'] = 'Uploaded completed.';
} else {
http_response_code(400);
$output['uploadSuccess'] = false;
$output['error'] = true;
$output['message'] = 'You have uploaded disallowed file types.';
@unlink($moveToFileName);
}
} else {
$output['error'] = true;
$output['message'] = 'Unable to move uploaded file.';
}
unset($moveToFileName);
}
unset($uploadFolder);
}
$output['debug']['_POST'] = $_POST;
$output['debug']['_FILES'] = $_FILES;
echo json_encode($output);
upload.php
Code (PHP)
<?php
$imageFile = __DIR__ . DIRECTORY_SEPARATOR . 'image.jpg';
$targetURL = (strtolower($_SERVER['REQUEST_SCHEME']) === 'https' ? 'https://' : 'http://')
. ($_SERVER['HTTP_HOST'] ?? 'localhost')
. (isset($_SERVER['REQUEST_URI']) ? dirname($_SERVER['REQUEST_URI']) : '')
. '/upload.php';
if (!is_file($imageFile)) {
http_response_code(404);
echo '<p>Image file was not found. Please prepare image file at this location: <strong>' . $imageFile . '</strong></p>';
exit();
}
$headers = [];
$allHeaders = [];
$postFields = [];
// create post fields
$postFields['hidden-input'] = 'hidden value (from cURL).';
// create upload file to post fields.
$Finfo = new finfo();
$fileMimeType = $Finfo->file($imageFile, FILEINFO_MIME_TYPE);
unset($Finfo);
$CurlFile = new CURLFile($imageFile, $fileMimeType, 'curl-upload-' . basename($imageFile));
$postFields['image'] = $CurlFile;
unset($CurlFile, $fileMimeType);
// start cURL.
$ch = curl_init($targetURL);
// don't echo out immediately.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// method POST.
curl_setopt($ch, CURLOPT_POST, true);
// disable SSL verify. this is for test with self signed (local host) only. remove this on production site.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
// response headers work.
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'headerFunction');
// POST data with file upload.
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
// execute cURL.
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
http_response_code(500);
echo '<p>cURL error: ' . curl_error($ch) . '</p>';
curl_close($ch);
exit();
}
// close cURL.
curl_close($ch);
unset($ch, $postFields);
http_response_code($httpCode);
if (isset($headers['content-type'])) {
header('Content-type: ' . $headers['content-type']);
}
unset($headers);
// add headers to `$response` to see what we have here.
$responseJson = json_decode($response);
unset($response);
$responseJson->debug->allHeaders = $allHeaders;
$responseJson->debug->httpCode = $httpCode;
// echo out cURL response.
echo json_encode($responseJson);
unset($responseJson);
/**
* cURL header manipulatement function.
*
* @param resource $ch cURL resource
* @param string $header A header line.
* @return int Return length of header line.
*/
function headerFunction($ch, $header)
{
global $allHeaders, $headers;
if (!empty(trim($header))) {
$headerExp = explode(':', $header, 2);
if (count($headerExp) === 2) {
$headers[strtolower(trim($headerExp[0]))] = trim($headerExp[1]);
}
$allHeaders[] = $header;
}
return (int) mb_strlen($header);
}// headerFunction
curl-upload.php
https://rundiz.com/?p=805
สิ่งที่แตกต่างคือ โค้ดนี้ใช้คลาส CURLFile() ซึ่งเป็นของที่มีตั้งแต่ PHP 5.5+ และโค้ดใหม่ๆจะแนะนำให้ใช้อันนี้แทน.
ประวัติการแก้ไข 2022-06-12 00:37:58
Date :
2022-06-12 00:37:07
By :
mr.v
Load balance : Server 03