Properly running a curl in php - php

I am doing research for a university task where we need to run this cURL code in PHP. Is there any way that this can be done?
What's the right syntax?
curl -X GET "https://secure.fusebill.com/v1/customers/{id}/Overview" \
-H "Content-Type: application/json" \
-H "Authorization: Basic {APIKey}"

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.

I will give you some examples you can Just copy and paste in your PHP file to check.
First this is my favorite and most efficient way to get information from other webpages or even insert information if you need to.
GET RESULTS FROM WEBPAGE BY GET METHOD(It would work for the work you need):
$ch = CURL_INIT();
$url = 'https://google.com';
CURL_SETOPT($ch, CURLOPT_URL, $url );
//CURL_SETOPT($ch, CURLOPT_PROXY, $ip); //IN CASE YOU NEED TO USE PROXY
//CURL_SETOPT($ch, CURLOPT_PROXYPORT, $port);
CURL_SETOPT($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:42.0) Gecko/20100101 Firefox/42.0');
CURL_SETOPT($ch, CURLOPT_POST, 0);//Get instead of post
CURL_SETOPT($ch, CURLOPT_RETURNTRANSFER, True);
CURL_SETOPT($ch, CURLOPT_FOLLOWLOCATION, True);
CURL_SETOPT($ch, CURLOPT_ENCODING, 'gzip, deflate');//Try to curl https://amazon.com WITHOUT THIS LINE, it would give you some extra encryption.
CURL_SETOPT($ch, CURLOPT_CONNECTTIMEOUT,90);
CURL_SETOPT($ch, CURLOPT_TIMEOUT,90);
$result = CURL_EXEC($ch);
echo $result;
Next is if you need to insert data in the page using a post method.
You can use this to LOG IN in some websites or you use to insert and get data automatically
$data = array(
"email" => "example#gmail.com",
"pwd" => "12341234",
"some other field"=> '123123'
);
$ch = CURL_INIT();
$url = 'https://google.com';
CURL_SETOPT($ch, CURLOPT_URL, $url );
CURL_SETOPT($ch, CURLOPT_POST, true); //Post request
CURL_SETOPT($ch, CURLOPT_POSTFIELDS, $data);
CURL_SETOPT($ch, CURLOPT_RETURNTRANSFER,True);
CURL_SETOPT($ch, CURLOPT_FOLLOWLOCATION,True);
CURL_SETOPT($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) ."/cookie.txt");//I am saving here the cookies in case I need to go to another page or do some action after login
CURL_SETOPT($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) ."/cookie.txt");
CURL_SETOPT($ch, CURLOPT_FOLLOWLOCATION, true); //ALLOW REDIRECTION
CURL_SETOPT($ch, CURLOPT_CONNECTTIMEOUT,90);
CURL_SETOPT($ch, CURLOPT_TIMEOUT,90);
$result = CURL_EXEC($ch);
Second it is the most easy one that has some limitations and because of that I don't like:
$url = 'https://www.google.com/';
echo file_get_contents($url);
If you have any questions, let me know.
I work with curl all the time!

Related

PHP cURL how to send a JSON POST request and also include a URL querystring?

I'm trying to submit a POST request with JSON data to an api endpoint. The endpoint requires a querystring passing the api credentials, but also requires the JSON data to be POSTed.
When I try to do this with PHP cURL as shown below, the querystring is apparently removed - thus the api is rejecting the request due to missing api key.
I can do this easily with Postman when testing access to the api endpoint.
How can I make the cURL request include both the querystring AND the JSON POST body?
Example code:
// $data is previously defined as an array of parameters and values.
$url = "https://api.endpoint.url?api_key=1234567890";
$ch = curl_init();
$json = json_encode($data);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($json)
]
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
You are doing almost right.
Sometimes you need to relax SSL verification.
Otherwise, update php ca bundle:
https://docs.bolt.cm/3.7/howto/curl-ca-certificates
Add the following:
$headers = array(
"Content-type: application/json;charset=UTF-8",
"Accept-Encoding: gzip,deflate",
"Content-length: ".strlen($json),
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 300);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_ENCODING, "identity, deflate, gzip");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
Sometimes you need to change encoding too:
$result = utf8_decode($result);
And check the returning data.

Using curl to post an array to the godaddy api

I am trying to post a bunch of domains to the godaddy api in order to get information about pricing and availability. However, whenever I try to use curl to execute this request, I am returned nothing. I double checked my key credentials and everything seems to be right on that end. I'm pretty confident the issue is in formatting the postfield, I just don't know how to do that... Thank you to whoever can help in advance!
$header = array(
'Authorization: sso-key ...'
);
$wordsArray = ['hello.com', "cheese.com", "bytheway.com"];
$url = "https://api.godaddy.com/v1/domains/available?checkType=FAST";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_POST, true); //Can be post, put, delete, etc.
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $wordsArray);
$result = curl_exec($ch);
$dn = json_decode($result, true);
print_r($dn);
There are two problems in your code:
Media type of sent data must be application/json (by default this is application/x-www-form-urlencoded), and your PHP app must accept application/json as well:
$headers = array(
"Authorization: sso-key --your-api-key--",
"Content-Type: application/json",
"Accept: application/json"
);
Post fields must be specified as JSON. To achieve this, use the json_encode function:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($wordsArray));
Full PHP code is:
$headers = array(
"Authorization: sso-key --your-api-key--",
"Content-Type: application/json", // POST as JSON
"Accept: application/json" // Accept response as JSON
);
$wordsArray = ["hello.com", "cheese.com", "bytheway.com"];
$url = "https://api.godaddy.com/v1/domains/available?checkType=FAST";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($wordsArray));
$result = curl_exec($ch);
$dn = json_decode($result, true);
print_r($dn);

Trivia API not returning proper JSON in PHP

I am using this API
https://market.mashape.com/pareshchouhan/trivia
for making widget in my site but when i am calling this API through CURL it is returning following error:
Any solution for that?
Here my code :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://pareshchouhan-trivia-v1.p.mashape.com/v1/getAllQuizQuestions");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, FALSE);
curl_setopt($ch,CURLOPT_HEADER,FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"X-Mashape-Key" => "MY_KEY",
"Accept" => "application/json"
));
$data = curl_exec($ch);
curl_close($ch);
echo $data;
when i execute this PHP file, it is returning "Missing Mashape application key" in return data.
http://i.prntscr.com/5f98b1e8965f42eda29875543b052ec5.png
You are specifying you curl headers incorrectly. Look at the CURLOPT_HTTPHEADER option in the docs at http://php.net/manual/en/function.curl-setopt.php. Your code should look like this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://pareshchouhan-trivia-v1.p.mashape.com/v1/getAllQuizQuestions");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"X-Mashape-Key: MY_KEY",
"Accept: application/json"
));
$data = curl_exec($ch);
curl_close($ch);

PHP cURL GET request and request's body

i'm trying using cURL for a GET request like this:
function connect($id_user){
$ch = curl_init();
$headers = array(
'Accept: application/json',
'Content-Type: application/json',
);
curl_setopt($ch, CURLOPT_URL, $this->service_url.'user/'.$id_user);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
$body = '{}';
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$authToken = curl_exec($ch);
return $authToken;
}
As you an see i want to pass $body as the request's body , but i don't know if its correct or not and i can't debug this actually, do you know if is the right to use curl_setopt($ch, CURLOPT_POSTFIELDS,$body); with a GET request?
Cause this enteire code works perfect with POST, now i'm trying change this to GET as you can see
The accepted answer is wrong. GET requests can indeed contain a body. This is the solution implemented by WordPress, as an example:
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $body );
EDIT: To clarify, the initial curl_setopt is necessary in this instance, because libcurl will default the HTTP method to POST when using CURLOPT_POSTFIELDS (see documentation).
CURLOPT_POSTFIELDS as the name suggests, is for the body (payload) of a POST request. For GET requests, the payload is part of the URL in the form of a query string.
In your case, you need to construct the URL with the arguments you need to send (if any), and remove the other options to cURL.
curl_setopt($ch, CURLOPT_URL, $this->service_url.'user/'.$id_user);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
//$body = '{}';
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
//curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
<?php
$post = ['batch_id'=> "2"];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://example.com/student_list.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
$result = json_decode($response);
curl_close($ch); // Close the connection
$new= $result->status;
if( $new =="1")
{
echo "<script>alert('Student list')</script>";
}
else
{
echo "<script>alert('Not Removed')</script>";
}
?>
For those coming to this with similar problems, this request library allows you to make external http requests seemlessly within your php application. Simplified GET, POST, PATCH, DELETE and PUT requests.
A sample request would be as below
use Libraries\Request;
$data = [
'samplekey' => 'value',
'otherkey' => 'othervalue'
];
$headers = [
'Content-Type' => 'application/json',
'Content-Length' => sizeof($data)
];
$response = Request::post('https://example.com', $data, $headers);
// the $response variable contains response from the request
Documentation for the same can be found in the project's README.md
you have done it the correct way using
curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
but i notice your missing
curl_setopt($ch, CURLOPT_POST,1);

how to read a response back from URL which is sending the response in json

I have been given an API url feed which returns response in JSON format and I have been told to set the headers to this:
Accept: application/json
X-some-API-Key: fdfdfdfdsgddc43aa96c556eb457b4009
Could anyone please tell me how to move ahead with this problem?
Question 1
I would use the PHP curl libraries.
For example:
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'X-some-API-Key: fdfdfdfdsgddc43aa96c556eb457b4009',
));
// grab URL and pass it to the browser
echo curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
See curl_setopt() for more information on the constants such as CURLOPT_HTTPHEADER I have used above.
Question 2 from comments
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'X-some-API-Key: fdfdfdfdsgddc43aa96c556eb457b4009',
));
// grab URL and pass it to the browser
$json = json_decode(curl_exec($ch), true);
// close cURL resource, and free up system resources
curl_close($ch);
$json now contains an associative array of the response, which you can var_dump()to see the structure.
If you're using cURL in PHP you can do set custom headers on the request with:
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'X-some-API-Key: fdfdfdfdsgddc43aa96c556eb457b4009'
));

Categories