Cannot upload an image on imgur [API 3] - php

I'm trying to upload images on imgur but I often have problem and I am not able to upload the image.
In the code I'll publish I don't understand why I keep getting the boolean value: false as result of curl_exec($ch); and not a json string. From the PHP Manual it means that the post failed but I don't understand why.
Here I successfully read the image from a post request
$imageContent = file_get_contents($myFile["tmp_name"][$i]);
if ($imageContent === false) {
// Empty image - I never get this error
} else {
//Image correctly read
$url = $this->uploadLogged($imageContent);
}
While here is my attempt to upload it
public function uploadLogged($image){
$upload_route = "https://api.imgur.com/3/image";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $upload_route);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Authorization: Bearer '.$this->access_token));
curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => base64_encode($image)));
$response = curl_exec($ch);
$responseDecoded = json_decode($response);
curl_close ($ch);
$link = $responseDecoded->data->link;
if( empty($link) ){
throw new Exception("Cannot upload the image.<br>Response: ".json_encode($response));
}
return $link;
}
Moreover $this->access_token correspond to a valid access token

when curl_exec returns bool(false), there was an error during the transfer. to get an extended error description, use the curl_errno() and curl_error() functions. to get even more detailed info of the transfer, use the CURLOPT_VERBOSE and CURLOPT_STDERR options of curl_setopt. eg
$curlstderrh=tmpfile();
curl_setopt_array($ch,array(CURLOPT_VERBOSE=>1,CURLOPT_STDERR=>$curlstderrh));
$response = curl_exec($ch);
$curlstderr=file_get_contents(stream_get_meta_data($curlstderrh)['uri']);
fclose($curlstderrh);
if(false===$response){
throw new \RuntimeException("curl_exec failed: ".curl_errno($ch).": ".curl_error($ch).". verbose log: $curlstderr");
}
unset($curlstderrh,$curlstderr);
should get you both the libcurl error code, an error description, and a detailed log of what happened up until the error, in the exception message.
common issues include an SSL/TLS encryption/decryption error, timeout errors, and an unstable connection.

Related

php Curl vs postman giving different results on error

I have a php curl script that returns the results of a get the run as a command from another process. The code is:
<?php
$arr = getopt("f:");
$url = $arr['f'];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo curl_error($ch);
} else {
echo $result;
}
curl_close($ch);
?>
When I do a api get request for a specific url with curl that gives a 400 error, curl_error($ch) is "The requested URL returned error: 400 Bad Request"
When I run the same request in postman, I get a json reply such as: {"result_ok":false,"code":400,"message":"Invalid Email: xxxxxxxxxx#ail.com (POST)"}.
How can I get the json returned in the curl request? If I echo the $result when there is an error condition, it is null.
From CURLOPT_FAILONERROR explained:
fail the request if the HTTP code returned is equal to or larger than 400. The default action would be to return the page normally, ignoring that code.
CURLOPT_FAILONERROR is false by default so either remove it or set it:
curl_setopt($ch, CURLOPT_FAILONERROR, false);

PHP: How to GET request a page and get body and http error codes

I want know if is possible to get the HTTP error codes and response in case of error instead of false (file get contents error) and error throwed. I'm using file_get_contents on PHP 7.2
I already tried doing this:
$r = file_get_contents("https://somewebsite");
Output:
PHP Warning: file_get_contents(https://somewebsite): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
I can get the response code with $http_response_header but $r is false and i want get the error response page.
You should try with curl
$ch = curl_init('https://httpstat.us/404');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// if you want to follow redirections
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// you may want to disable certificate verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode >= 400) {
// error
// but $response still contain the response
} else {
// everything is fine
}
curl_close($ch);
Using file get contents
$context = stream_context_create(array(
'http' => array('ignore_errors' => true),
));
$result = file_get_contents('http://your/url', false, $context);

PHP & CURL scraping

I have a problem when I run this script in Google Chrome I got a blank page. When I use another link of a web site, it works successfully. I do not what is happening.
$curl = curl_init();
$url = "https://www.danmurphys.com.au/dm/home";
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($curl);
echo $output;
There are some conditions which make your result blank. Such as:
Curl error.
Redirection without response body and the curl doesn't follow the redirection.
The target host doesn't give any response body.
So here you have to find out the problem.
For the first possibility, use curl_error and curl_errno to confirm that the curl wasn't errored when its runtime.
For the second, use CURLOPT_FOLLOWLOCATION option to make sure the curl follows the redirection.
For the third possibility, we can use curl_getinfo. It returns an array which contains "size_download". The size_download shows you the length of the response body. If it is zero that is why you see a blank page when printing it.
One more, try to use var_dump to see the output (debug purpose only). There is a possibility where the curl_exec returns bool false or null. If you print the bool false or null it will show a blank.
Here is the example to use all of them.
<?php
$curl = curl_init();
$url = "https://www.danmurphys.com.au/dm/home";
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$output = curl_exec($curl);
$info = curl_getinfo($curl);
$err = curl_error($curl);
$ern = curl_errno($curl);
if ($ern) {
printf("An error occurred: (%d) %s\n", $ern, $err);
exit(1);
}
curl_close($curl);
printf("Response body size: %d\n", $info["size_download"]);
// Debug only.
// var_dump($output);
echo $output;
Hope this can help you.
Update:
You can use CURLOPT_VERBOSE to see the request and response information in details.
Just add this
curl_setopt($curl, CURLOPT_VERBOSE, true);
It doesn't need to be printed, the curl will print it for you during runtime.

PHP how to check if openload video exist?

I need something to check if openload video exist, some videos sometimes get removed by DMCA report and i just need to display myself not working links.
Just a sketch what I wanna
$result = mysqli_query($db, "SELECT videos FROM table");
while($row=mysqli_fetch_assoc($result) {
$embedUrl = $row["videos"];
//so i wanna show only not working url's
if($embedUrl == false)
echo $embedUrl;
}
This is example of not working link here
Try this. Outputs: 'Video unavailable' if a video doesn't exist.
See comments for step-by-step explanation.
<?php
// Your Openload URL
$url = 'https://openload.co/embed/UgmaOAo1wlg/Horrible.Bosses.2.2014.720p.BluRay.x264.YIFY.mp4';
// Initialize cURL library.
if (($curl = curl_init()) === FALSE)
{
$errno = curl_errno();
throw new RuntimeException("curl_init() ($errno): " . curl_strerror($errno));
}
// Tell cURL which URL to operate on. GET is the default method.
curl_setopt($curl, CURLOPT_URL, $url);
// Optionally specify a path to a certificate store in PEM format.
// curl_setopt($curl, CURLOPT_CAINFO, __DIR__ . '/cacert.pem');
// Given Openload URL is requested over https. Allow for some sanity checking.
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, TRUE);
// Set this to the latest SSL standard supported by PHP at the time of this answer.
curl_setopt($curl, CURLOPT_SSLVERSION, 6);
// Return response, so we can inspect its contents.
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
// Openload returns HTTP code 200 if a video wasn't found. Any code >= 400 indicates a different problem.
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);
// Allow for server-side redirects.
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
// Don't include header in response.
curl_setopt($curl, CURLOPT_HEADER, FALSE);
if (($response = curl_exec($curl)) === FALSE)
throw new RuntimeException("curl_exec() failed for $url: " . curl_error($curl));
// Perform a case-insensitive search for a token that is specific to the 'video not found' page.
if (stripos($response, '<img class="image-blocked" src="/assets/img/blocked.png" alt="blocked">') !== FALSE)
echo 'Video unavailable';

API gives a JSON response, but PHP doesn't treat it as JSON on the HTTP request, only if I copy to a local file

I am using an API that gives a JSON response. If I copy that response into a 'test.txt' file and retrieve data from it - it's fine. However, if I try to #file_get_contents directly on the HTTPS url, I get a non-object.
function fetchMeasurments($url, $energyCoefficient, $filePrefix) {
$connectionSettings = stream_context_create(array('http'=>
array(
'timeout' => 5
)
));
$jsonData = #file_get_contents($url, false, $connectionSettings);
$obj = json_decode($jsonData);
if( is_null($obj) ){
echo 'null'; die();
}else{
echo 'not null'; die();
}
If I use test.txt - I get 'not null', but if I use the HTTPS url, I get null. Any thoughts?
Here is the JSON response:
{"overview":{"lastUpdateTime":"2014-10-27 11:03:15","lifeTimeData":{"energy":2.1047042E7,"revenue":2639.4795},"lastYearData":{"energy":2.105334E7},"lastMonthData":{"energy":1388652.8},"lastDayData":{"energy":749.25397},"currentPower":{"power":817.0}}}
I think you should really consider using CURL instead of file_get_contents(). Curl has support for secure connections and you will not have problems with https.
Morover suppresion of errors is not a good idea.
Here you have tutorial how to make CURL connections with https
http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/
function getData($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
Use this function instead of file_get_contents().
Notice this is very basic function without setting headers, error handling and certificate acceptation.

Categories