i need to rename the image file before upload how can i do that i can use the rename but it moves the file to a different dir file_get_contents to change the name is not working for me i need to rename this part /C-laragon-www-api-backend-screenshots-1-jpg.jpg
this is the path on my system
here is my function
JavaScript
x
/**
* @param $image
* @return mixed|exception
*/
function imgUpload($image)
{
try {
$API_KEY = 'xxxxx';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.imgbb.com/1/upload?key=' . $API_KEY);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$extension = pathinfo($image, PATHINFO_EXTENSION);
$file_name = uniqid() . '.' . $extension;
$data = [
'image' => base64_encode(file_get_contents($image, $file_name))
];
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
curl_close($ch);
} catch (Exception $e) {
$e->getMessage();
}
return json_decode($result, true);
}
the output
JavaScript
["data"]=>
array(12) {
["id"]=>
string(7) "xxxxx"
["title"]=>
string(49) "C-laragon-www-api-backend-screenshots-1-jpg"
["url_viewer"]=>
string(22) "https://ibb.co/xxxx"
["url"]=>
string(78) "https://i.ibb.co/xxxx/C-laragon-www-api-backend-screenshots-1-jpg.jpg"
["display_url"]=>
string(78) "https://i.ibb.co/xxxx/C-laragon-www-api-backend-screenshots-1-jpg.jpg"
["size"]=>
int(435765)
["time"]=>
string(10) "xxxxxx"
["expiration"]=>
string(1) "0"
["image"]=>
array(5) {
Advertisement
Answer
Does this work for you:
JavaScript
function imgUpload($image)
{
try {
$file = new CURLFile("@{$image}"); //<-- Path of the image with @ in front
$data = array('name' => 'New name of image', 'file' => $file);
$API_KEY = 'xxxxx';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.imgbb.com/1/upload?key=' . $API_KEY);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$extension = pathinfo($image, PATHINFO_EXTENSION);
// $file_name = uniqid() . '.' . $extension;
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
curl_close($ch);
} catch (Exception $e) {
$e->getMessage();
}
return json_decode($result, true);
}