PHP Curl doesn't return a response - php

I'm trying to get the response back from an API using curl in php but for some reason it fails. However, when I open the API call link in a browser it works fine. Furthermore, if I try to get the response with curl after I've opened the link in the browser curl works but if I change the $url variable to a new link it again stops working until I open it in the browser again.
Here is my code, don't worry about the api key it's just a test:
<?php
set_time_limit(30);
$API_KEY = "ak_wujpBbfefrmxDleyAmnqtFpqAcmey";
$url = 'https://www.google.com/';
$api_call = "https://www.screenshot-website.com/api/$API_KEY?url=$url&type=tablet";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $api_call,
CURLOPT_TIMEOUT => 30,
CURLOPT_TIMEOUT_MS => 30000,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_CONNECTTIMEOUT_MS => 30000 )
);
$response = json_decode(curl_exec($curl), true);
if($errno = curl_errno($curl)) {
$error_message = curl_strerror($errno);
echo "cURL error ({$errno}):\n {$error_message}";
}
curl_close($curl); ?>
<img src="<?php echo $response['image']; ?>">
I get no errors at all.

I think your problem is with the "https" since curl set ssl_verifier to true
"The problem is that cURL has not been configured to trust the server’s HTTPS certificate." you can read the full information here.
You could try setting this option:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

Related

not able to upload a file to the host in laravel with file_get_contents() error [duplicate]

I'm getting the following error when running a script. The error message is as follows...
Warning: file_get_contents() [function.file-get-contents]: https:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /home/satoship/public_html/connect.php on line 22
I know this is a server issue but what do I need to do to the server in order to get rid of the above warning?
#blytung Has a nice function to replace that function
<?php
$url = "http://www.example.org/";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($ch);
if (curl_errno($ch)) {
echo curl_error($ch);
echo "\n<br />";
$contents = '';
} else {
curl_close($ch);
}
if (!is_string($contents) || !strlen($contents)) {
echo "Failed to get contents.";
$contents = '';
}
echo $contents;
?>
If you do not have the ability to modify your php.ini file, use cURL:
PHP Curl And Cookies
Here is an example function I created:
function get_web_page( $url, $cookiesIn = '' ){
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => true, //return headers in addition to content
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLINFO_HEADER_OUT => true,
CURLOPT_SSL_VERIFYPEER => true, // Validate SSL Cert
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_COOKIE => $cookiesIn
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$rough_content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header_content = substr($rough_content, 0, $header['header_size']);
$body_content = trim(str_replace($header_content, '', $rough_content));
$pattern = "#Set-Cookie:\\s+(?<cookie>[^=]+=[^;]+)#m";
preg_match_all($pattern, $header_content, $matches);
$cookiesOut = implode("; ", $matches['cookie']);
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['headers'] = $header_content;
$header['content'] = $body_content;
$header['cookies'] = $cookiesOut;
return $header;
}
NOTE: In revisiting this function I noticed that I had disabled SSL checks in this code. That is generally a BAD thing even though in my particular case the site I was using it on was local and was safe. As a result I've modified this code to have SSL checks on by default. If for some reason you need to change that, you can simply update the value for CURLOPT_SSL_VERIFYPEER, but I wanted the code to be secure by default if someone uses this.
Use this code in your php script (first lines)
ini_set('allow_url_fopen',1);
Edit your php.ini, find allow_url_fopen and set it to allow_url_fopen = 1
Using relative instead of absolute file path solved the problem for me.
I had the same issue and setting allow_url_fopen=on
did not help. This means for instance :
use
$file="folder/file.ext";
instead of
$file="https://website.com/folder/file.ext";
in
$f=fopen($file,"r+");
THIS IS A VERY SIMPLE PROBLEM
Here is the best method for solve this problem.
Step 1 : Login to your cPanel (http://website.com/cpanel OR http://cpanel.website.com).
Step 2 : SOFTWARE -> Select PHP Version
Step 3 : Change Your Current PHP version : 5.6
Step 3 : HIT 'Set as current' [ ENJOY ]

How to get data from a website that uses SSL using cURL and PHP?

I am trying to get some data from a website where you need to have a SSL certificate to be able to connect to it.
I have found the following code :
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, $host);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, $host);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
The cURL query works well, but the data that I get is this one :
400 No required SSL certificate was
sent 400 Bad
Request No required SSL certificate was
sent nginx
What I am looking for is the data contained in the index.php (and the other paths) of the website.
So, how can I do to add a Certificate to the code, and, using cURL, get the data from the website ?
PS : Will the data will be in JSON format ?
PPS : if this can be helpfull, I am using PHPStorm
Try this.
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://jsonplaceholder.typicode.com/todos/1",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array("content-type: application/json"),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
can you try like this?
echo $str = file_get_contents("https://jsonplaceholder.typicode.com/todos/1");

could not decode nested json api php

I am using these code to fetch koinex api data. From this API URL -
https://koinex.in/api/ticker
<?php
$getCurrency = "inr";
$displayArrayOutput = true;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://koinex.in/api/ticker",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
if($displayArrayOutput){
$response = json_decode($response, true);
print_r($response);
}
else{
header("Content-type:application/json");
}
}
?>
I have also try file_get_contents but same problem. I have face this issue in 2 more api's. Note: Once i get the data and use it correctly but today this is not working again.
I tried your code, and apparently the website you are trying to reach with CURL uses a security:
Why have I been blocked?
This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.
What can I do to resolve this?
You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.
It seems that the website you are trying to reach asks for a user agent. This code works for me:
<?php
$getCurrency = "inr";
$displayArrayOutput = true;
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://koinex.in/api/ticker',
CURLOPT_USERAGENT => 'Something here'
));
// Send the request & save response to $resp
$response = curl_exec($curl);
// Close request to clear up some resources
$err = curl_error($curl);
curl_close($curl);
if ($err) {
} else {
if($displayArrayOutput){
$response = json_decode($response, true);
print_r($response);
}
else{
header("Content-type:application/json");
echo 'touine';
}
}
?>
Good luck

Cannot remote upload through openload API [PHP - curl]

I'm trying to upload a file using the openload API that can be found here.
When I upload some file I always get a JSON response of success (code: 200):
Unfortunately when I check the file status (using both API and website) it tells me that there was an error in upload. Here the JSON response (code 200):
Here is how I send the request. Where's the error? I tried using both the urlencode function and not.
$user = "...";
$psw = "...";
$link = urlencode("https://google.com/favicon.ico");
$url = "https://api.openload.co/1/remotedl/add?login=$user&key=$psw&url=$link";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_URL => $url,
CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
$resp = curl_exec($curl);
curl_close($curl);
echo $resp;
EDIT: Switched to https and added CURLOPT_FOLLOWLOCATION => true, still no success.
I think you are hitting a http 301 redirect while using curl
http://google.com/favicon.ico
to
https://www.google.com/favicon.ico
If that case curl option CURLOPT_FOLLOWLOCATION might help.

Google Maps API not working with server side code but works client side

I'm generating a URL such as:
http://maps.googleapis.com/maps/api/geocode/json?address=143+Blackstone+Street%2C+Mendon%2C+MA+-+01756&key=***********
If I open this in browser, I'm getting a result successfully. However, if I use the same URL using curl, I'm getting:
error:couldn't connect to host
Here is my PHP code
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode('143 Blackstone Street, Mendon, MA - 01756')."&key=***********";
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 100,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => false
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
if(curl_error($ch))
{
echo 'error:' . curl_error($ch);
}
curl_close ($ch);
print_r($response);
UPDATE
I came across a term called as server key and browser key when using the Google APIs. Howerver, in the API manager, I can't seem to see where to set or change the API type.
You are urlencodeing parts of the url that need to be in plain text.
Only urlencode your parameters
<?php
$address = urlencode("143 Blackstone Street, Mendon, MA - 01756");
$key = urlencode("************");
$ch = curl_init();
$options = array(
CURLOPT_URL => "http://maps.googleapis.com/maps/api/geocode/json?address=".$address."&key=".$key,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 100,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => false
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
if(curl_error($ch))
{
echo 'error:' . curl_error($ch);
}
curl_close ($ch);
print_r($response);
If you're hitting an 'couldn't connect to host' error message from curl it sounds like the problem may not be on the Google Maps API side and instead be on the proxy / networking side. A connection to maps.googleapis.com should always be possible, regardless of key type or url params.
I would look into the steps suggested here: How to resolve cURL Error (7): couldn't connect to host?

Categories