What is cURL in PHP?
cURL is a library that lets you make HTTP requests in PHP. Everything you need to know about it (and most other extensions) can be found in the PHP manual.
In order to use PHP's cURL functions
you need to install the » libcurl
package. PHP requires that you use
libcurl 7.0.2-beta or higher. In PHP
4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that's
7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.
You can make HTTP requests without cURL, too, though it requires allow_url_fopen
to be enabled in your php.ini
file.
// Make a HTTP GET request and print it (requires allow_url_fopen to be enabled)
print file_get_contents('http://www.example.com/');
PHP, cURL, and HTTP POST example?
<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
// Further processing ...
if ($server_output == "OK") { ... } else { ... }
?>
Properly running a curl in php
Here is one way to do it with curl and an options array:
<?php
$curl = curl_init("https://secure.fusebill.com/v1/customers/{id}/Overview");
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: Basic {APIKey}",
"Content-Type: application/json"
)
));
$response = curl_exec($curl);
curl_close($curl);
You can alternatively set each option by calling curl_setopt($curl, OPTION_NAME, "value");
for each option in place of curl_setopt_array();
:
$curl = curl_init("https://secure.fusebill.com/v1/customers/{id}/Overview");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Authorization: Basic {APIKey}",
"Content-Type: application/json"
));
$response = curl_exec($curl);
curl_close($curl);
For this request in PHP, you initialize curl and store in a variable so you can add options to the request before executing.
Here is a breakdown of the options from the snippet above:
CURLOPT_RETURNTRANSFER - return data from the request as a string instead of outputting directly (useful if you need to use the data in another function somewhere).
CURLOPT_CUSTOMREQUEST - HTTP request method for the request
CURLOPT_HTTPHEADER - set headers for the request.
Here is how the PHP maps to the cURL above:
-X specifies the HTTP method and the URL. In PHP we set CURLOPT_CUSTOMREQUEST
and set the URL when we initialize the cURL handler, you can optionally use CURLOPT_URL
to set the URL instead.
-H - stands for headers for the request. In PHP we set CURLOPT_HTTPHEADER
. We set the headers as an array since there are multiple headers.
Remember to replace {id}
in the URL and {APIKey}
in the authorization header of your request.
HTTP request with PHP CURL and getting different result from postman and curl cli
It turns out that this API requires the User-Agent header and it seems that Postman and the curl cli send those automatically while the php-curl request doesn't. As soon as I added that header and made up a value it started working.
How to get PHP 8.1 to recognize curl_init?
This line from the error log indicates what the problem most likely is:
#5 /var/lib/jenkins/workspace" while reading response header from upstream, client: 96.244.127.121, server: url-here.com, request: "GET /googleSearch.php?q=test HTTP/1.1", upstream: "fastcgi://unix:/run/php/php8.0-fpm.sock:", host: "url-here.com", referrer: "https://url-here.com/apps/browser.html"
You've got PHP 8.0 here, but you've installed Curl for PHP 8.1. You need to check your FPM or server configuration.
I think you're using Nginx. If that's correct then this article might be helpful. Specifically you'll want to look in:
- /etc/nginx/sites-available to check which socket is used
- /etc/php/VERSION/fpm/pool.d to check what sockets are available
Using Curl in PHP
Right I'm going to do this with you as I do it :d So far I've been able to get one user, the reason you're getting errors is because you're not setting any curl options. I taught myself using this https://github.com/paypal/rest-api-curlsamples/blob/master/execute_all_calls.php which I found MASSIVELY helpful when learning curl. The code itself is basic but it's so easy to read. I managed to understand it and make it 100% more complicated :D
First things first, I'll show you how I got the test user.
What you want to do is set the options, I'll keep to the simple method first.
The 2 methods are CURLOPT_HEADER
and CURL_RETURNTRANSFER
. Your url you can set with the init function.
$twitch=curl_init('https://api.twitch.tv/kraken/users/test_user1');
curl_setopt($twitch,CURLOPT_HTTPHEADER,array('Accept: application/vnd.twitchtv.v3+json'));//must be an array.
curl_setopt($twitch,CURLOPT_RETURNTRANSFER,true);
$result=curl_exec($twitch);
$info=curl_getinfo($twitch);
print_r($result);
This will get you your test user and hopefully show you a little bit about what you're doing wrong. If you wanted to use the array method, then you must use your curl options as the array key so that the set function know what to set what as. (don't ask me how it all technically works :S)
I'll update to show you how to get an authorisation and data once I've worked it out. But the basic principles are you need to send post data and set CURLOPT_POST
to true and include the postdata CURLOPT_POSTFIELDS
which must be a json array as your application requires json I believe?
Anyway the array:
curl_set_opts($twitch,array(CURLOPT_HEADER=>array('Accept: application/vnd.twitchtv.v3+json',CURLOPT_RETURNTRANSFER=true));
Seeing as you already know how to authorise a user I'll skip that bit, although I'd recommend using something a little more secure than a $_GET
. Maybe a session variable would be a bit better.
To get a specific user using the Auth that is returned. You want to do something like this: (Sorry I can't test it myself, I don't have a twitch dev account)
$twitch=curl_init('https://api.twitch.tv/kraken/user');
curl_setopt($twitch,CURLOPT_HEADER,array('Accept: application/cvd.twitchtv.v3+json','Authorization: OAuth '.$_SESSION['token']));
curl_setopt($twitch,CURLOPT_RETURNTRANSFER,true);
$result=curl_exec($twitch);
print_r($result);
//don't forget to close!
curl_close($twitch);
$user=json_decode($result);
echo$user->display_name;
That should work although I have no idea how you're getting a oAuth token lol
if you wanted to be a really cool programmer 8| I'd recommend doing some classes for this. Like this
class twitch{
private$token,$twitch,$url="http://api.twitch.tv/kraken/";
protected$code,$state,$report;
private static$details;
public function __construct($code,$state){
$this->code=$code;
$this->state=$state;
self::$details=(object)array('client_id'=>'id','client_secret'=>'secret','return_url'=>'redirect');
$result=$this->makeCall('oauth2/token',true);
print_r($result);
}
protected function makeCall($extention,$auth=false,$object=true){
$this->twitch=curl_init($this->url.$extention);
//$opts=array(CURLOPT_)
if($auth!==false){
$opts=array(CURLOPT_FOLLOWLOCATION=>true,CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>json_encode(array('client_id'=>self::$details->client_id,'client_secret'=>self::$details->client_secret,'grant_type'=>'authorization_code','code'=>$this->code,'redirect_uri'=>self::$details->return_url)));
}else{
$opts=array(CURLOPT_HEADER=>array('Accept: application/cvd.twitchtv.v3+json','Authorization: OAuth '.$this->token),CURLOPT_RETURNTRANSFER=>true);
}
curl_setopt_array($this->twitch,$opts);
$result=curl_exec($this->twitch);
$this->report=array('info'=>curl_getinfo($this->twitch),'error'=>curl_error($this->twitch));
curl_close($this->twitch);
return($object===true)?json_decode($result):$result;
}
protected function userDetails(){
return$this->makeCall('user');
}
public function user(){
return$this->userDetails();
}
}
Related Topics
Checking If Form Has Been Submitted - PHP
Why Is PHP Printing My Number in Scientific Notation, When I Specified It as .000021
PHP: Regex to Ignore Escaped Quotes Within Quotes
How to Get Name of Calling Function/Method in PHP
Pdo MySQL: How to Know If Insert Was Successful
Laravel Eloquent Query Using Where With or and Or
How to Call Shell Script from PHP That Requires Sudo
Automatic Post-Registration User Authentication
Capturing Text Between Square Brackets in PHP
How to Minify PHP Page HTML Output
Reference Assignment Operator in PHP, =&
What Is the Best Method to Merge Two PHP Objects
Woocommerce, Get Current Product Id
Guzzlehttp - How Get the Body of a Response from Guzzle 6
PHP Warning: Call-Time Pass-By-Reference Has Been Deprecated