Bad Request 400 uploading images to the imgur API - php

I want to upload some pictures with the imgur-API to imgur, but I am always getting an Error 400 Bad Request. Whats the issue?
<?php
if (isset($_POST['uploadprofileimg'])) {
$image = base64_encode(file_get_contents($_FILES['profileimg']['tmp_name']));
$options = array('http'=>array(
'method'=>"POST",
'header'=>"Authorization: Bearer *MY_ACCESS_TOKEN*\n".
"Content-Type: application/x-www-form-urlencoded",
'content'=>$image
));
$context = stream_context_create($options);
$imgurURL = "https://api.imgur.com/3/image";
$response = file_get_contents($imgurURL, false, $context);
}
?>
<h1>My Account</h1>
<form action="upload-pb.php" method="post" enctype="multipart/form-data">
Upload a profile image:
<input type="file" name="profileimg">
<input type="submit" name="uploadprofileimg" value="Upload Image">
</form>

Looking at the endpoint for /image here, it needs a parameter of image. You're passing it in as content, and not properly encoded as image. Looking here, I borrowed how to properly upload content using stream_context_create/file_get_contents:
<?php
if (isset($_POST['uploadprofileimg'])) {
$image = base64_encode(file_get_contents($_FILES['profileimg']['tmp_name']));
$postdata = http_build_query(
array(
'image' => $image,
)
);
$options = array('http'=>array(
'method'=>"POST",
'header'=>"Authorization: Bearer *MY_ACCESS_TOKEN*\n".
"Content-Type: application/x-www-form-urlencoded",
'content' => $postdata
));
$context = stream_context_create($options);
$imgurURL = "https://api.imgur.com/3/image";
$response = file_get_contents($imgurURL, false, $context);

Related

fetching imgur cURL to json_decode php upload form

i'm trying to use imgur as a uploading backend - i guess it secure my website if there's upload picture (is it right?) so
i went with this way :
<?php
$client_id = 'xxxxx';
$file = file_get_contents($_FILES["imgupload"]["tmp_name"]);
$url = 'https://api.imgur.com/3/image.json';
$headers = array("Authorization: Client-ID $client_id");
$pvars = array('image' => base64_encode($file));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL=> $url,
CURLOPT_TIMEOUT => 30,
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $pvars
));
if ($error = curl_error($curl)) {
die('cURL error:'.$error);
}
$json_returned = curl_exec($curl); // blank response
echo "Result: " . $json_returned ;
curl_close ($curl);
?>
HTML form
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="imgupload" /><br>
<input type="submit" value="Upload to Imgur" />
</form>
when i click on submit the result is fine as i guess ^^
Result: {"data":{"id":"TvFtE29","title":null,"description":null,"datetime":1585015712,"type":"image\/png","animated":false,"width":900,"height":940,"size":48902,"views":0,"bandwidth":0,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":0,"is_ad":false,"in_most_viral":false,"has_sound":false,"tags":[],"ad_type":0,"ad_url":"","edited":"0","in_gallery":false,"deletehash":"Z9xFH8mrSH8lRDB","name":"","link":"https:\/\/i.imgur.com\/TvFtE29.png"},"success":true,"status":200}
but my problem i want to collect the https://i.imgur.com/TvFtE29.png into specific variable like $uploaded = 'https://i.imgur.com/TvFtE29.png'; to added into my database -> user pic
i went with json_decode but it's not completed with me in the right way, if someone can help with this issue 🌹
thanks.
json_decode worked fine here:
$json_returned = json_decode($json_returned, true);
$uploaded = $json_returned['data']['link'];

Xampp php permission denied when trying to post images using imgur api?

The error I get:
Warning: file_get_contents(https://api.imgur.com/3/image): failed to open stream: HTTP request failed! HTTP/1.1 403 Permission Denied in
C:\xampp\htdocs\sn0\classes\Image.php on line 22
Notice: Trying to get property of non-object in
C:\xampp\htdocs\sn0\classes\Image.php on line 25
Notice: Trying to get property of non-object in
C:\xampp\htdocs\sn0\classes\Image.php on line 25
Here's my Image.php file:
<?php
class Image {
public static function uploadImage($formname, $query, $params) {
$image = base64_encode(file_get_contents($_FILES[$formname]['tmp_name']));
$options = array('http'=>array(
'method'=>"POST",
'header'=>"Authorization: Bearer ###\n".
"Content-Type: application/x-www-form-urlencoded",
'content'=>$image
));
$context = stream_context_create($options);
$imgurURL = "https://api.imgur.com/3/image";
if ($_FILES[$formname]['size'] > 10240000) {
die('Image too big, must be 10MB or less!');
}
$response = file_get_contents($imgurURL, false, $context);
$response = json_decode($response);
$preparams = array($formname=>$response->data->link);
$params = $preparams + $params;
DB::query($query, $params);
}
}
?>
You making bad request.
At the beginning you need to generate your Client ID (more info # https://api.imgur.com/#registerapp)
To do this go to https://api.imgur.com/oauth2/addclient
and
Select Anonymous usage without user authorization option as Authorization Type.
Use Authorization: Client-ID not Bearer, you can keep file_get_contents (so - then you need change only authorization header) but CURL will be better for this.
Example with CURL:
<?php
class Image
{
public static function uploadImage($formname, $query, $params)
{
$client_id = 'YOUR CLIENT ID';
$image = base64_encode(file_get_contents($_FILES[$formname]['tmp_name']));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.imgur.com/3/image.json',
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => array(
'Authorization: Client-ID ' . $client_id
) ,
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POSTFIELDS => array(
'image' => $image
)
));
$out = curl_exec($curl);
curl_close($curl);
$response = json_decode($out);
$preparams = array(
$formname => $response->data->link
);
$params = $preparams + $params;
DB::query($query, $params);
}
}
file_get_contents() is used for GET requests. You need to use CURL in PHP in order to make a POST request from a server to another.

Testing recaptcha on localhost

I've been trying to test recaptcha on localhost (xampp with php 5.3); the code below (taken from this answer) works on my remote host and returns 'success':'true', but on localhost { "success": false, "error-codes": [ "missing-input-response" ] } is returned. However, if I change the POST request to a GET request (essentially toggle the comment of the 2 $result = lines), then I get a successful call.
Why does this happen?! Although I'm happy that it works on my actual site, I'd like to understand why GET works but POST doesn't on localhost
<html><head></head><body><script src='https://www.google.com/recaptcha/api.js' async defer>
if(isset($_POST['g-recaptcha-response'])) {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array('secret' => 'my_secret_key',
'response' => $_POST['g-recaptcha-response']);
$options = array(
'http' => array(
'method' => "POST",
'header' => "Content-type: application/x-www-form-urlencoded" . PHP_EOL,
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
//$result = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=my_secretkey&response=' . $_POST['g-recaptcha-response']);
$result = file_get_contents($url, false, $context);
echo $result;
}
?>
<form method="post" action='recaptchatest.php'>
<input id="test" name="test" />
<div style="left:100px;" class="g-recaptcha" data-sitekey="my_key"></div>
<input type="submit" value="Send" id="submit" class="buttons" />
</form>
</body></html>
For completeness, the output of http_build_query($data) is a correctly formed query string (secret=<my key>&response=<response>) and the output of stream_context_create($options) is Resource id #3

Wistia upload using PHP cURL

Does anyone know how to upload a video to Wistia using PHP cURL from a file upload input specified within a form? This is my code but I cannot seem to get this to work with the current API. I’ve looked at a few similar posts on this subject but still no luck...
<?php
$pathToFile = $_FILES['fileName']['tmp_name']; /* /tmp/filename.mov */
$nameOfFile = $_FILES['fileName']['name']; /* filename.mov */
$data = array(
'api_password' => '********',
'file' => '#'.$pathToFile,
'project_id' => '********'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, "https://upload.wistia.com" );
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
curl_close($ch);
?>
UPDATE - FULL CODE (still not working)
cURL returns false for both curl_exec and curl_error when using "'file' => '#'.$pathToFile" but works fine when using "'url' = 'http://example.com/file.mov'... Perhaps I'm not processing the form properly? Here's the full code:
<?php
if ($_POST['submit']) {
$filePath = $_FILES['fileUploaded']['tmp_name'];
$fileName = $_FILES['fileUploaded']['name'];
$fileSize = $_FILES['fileUploaded']['size'];
echo("File Path: ");
echo $filePath;
echo '<br>';
$data = array(
'api_password' => '******',
/* 'url' => 'http://example.com/file.mov', WORKS */
'file' => '#'.$filePath, /* DOES NOT WORK */
'project_id' => '******'
);
// WORKING CMD LINE
// curl -i -F api_password=****** -F file=#file.mov https://upload.wistia.com/
/* cURL */
$chss = curl_init('https://upload.wistia.com');
curl_setopt_array($chss, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POSTFIELDS => http_build_query($data)
));
// Send the request
$KReresponse = curl_exec($chss);
$KError = curl_error($chss);
// Decode the response
$KReresponseData = json_decode($KReresponse, TRUE);
echo '<br>';
echo("Response:");
print_r($KReresponseData);
echo '<br>';
echo("Error:");
print_r($KError);
}
?>
<form name="upload-form" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<input type="file" name="fileUploaded">
<input type="submit" name="submit" value="Upload">
</form>
Any help would be much appreciated!
Try this:
$filePath = "#{$_FILES['fileUploaded']['tmp_name']};filename={$_FILES['fileUploaded']['name']};type={$_FILES['fileUploaded']['type']}";

PHP: Uploading multiple images to imgur at once

I've got the following code and it works perfectly fine for uploading one image to Imgur using their API:
$client_id = $myClientId;
$file = file_get_contents($_FILES["file"]["tmp_name"]);
$url = 'https://api.imgur.com/3/image.json';
$headers = array("Authorization: Client-ID $client_id");
$pvars = array('image' => base64_encode($file));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL=> $url,
CURLOPT_TIMEOUT => 30,
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $pvars
));
$json_returned = curl_exec($curl); // blank response
$json = json_decode($json_returned, true);
curl_close ($curl);
However I need to upload multiple images at once. On the client side, the user will have multiple <input type="file" /> fields. I'm completely stuck now with figuring out where and how I will need to modify this code in order to handle multiple image upload when they come through to the server in the form of an array. Does anyone have any ideas?
Change the markup as follows:
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="file[]" type="file" multiple="multiple" /><br />
<input type="submit" value="Send files" />
</form>
Now, you can loop through the $_FILES array using a foreach, like so:
foreach ($_FILES['file']['tmp_name'] as $index => $tmpName) {
if( !empty( $tmpName ) && is_uploaded_file( $tmpName ) )
{
// $tmpName is the file
// code for sending the image to imgur
}
}

Categories