Curl request works on console but not in PHP - php

This simple request works on my console
curl 'https://www.nike.com/en'
But in PHP (with or without options like headers, useragent ...) I get Access Denied 403
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.nike.com/en");
$result = curl_exec($ch);
Thanks

Well, this would work for you.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.nike.com/en");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 40000);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
echo $result;

<?php
class Curl {
public static function makeRequest($url) {
$ch = curl_init();
$request_headers = [
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8;',
'Accept-Encoding: gzip, deflate',
"Connection: keep-alive",
"Content-Type: text/html; charset=UTF-8",
];
$options = [
CURLOPT_URL => $url,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_USERAGENT => "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.0",
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_AUTOREFERER => true,
CURLOPT_COOKIESESSION => true,
CURLOPT_FILETIME => true,
CURLOPT_FRESH_CONNECT => true,
CURLOPT_HTTPHEADER => $request_headers,
CURLOPT_COOKIESESSION => true,
CURLOPT_ENCODING => "gzip, deflate, scdh",
];
curl_setopt_array($ch, $options);
$result['content'] = curl_exec($ch);
$result['header'] = curl_getinfo($ch);
$result['error'] = curl_error($ch);
return $result;
}
}
var_dump(Curl::makeRequest('https://www.nike.com/en')['header']);
Some website strictly check the request headers and return you encoded so .. I added request headers ad decoding method to decode the content

Related

How to send HTTP GET request to REST API via cURL using PHP and call method from REST API with cURL

I'm using PHP and cURL.
I want to send HTTP GET request to REST API and I want to call method from REST API. How can i make via cURL using PHP? I have API URL and Key. I must send my key with URL and I need method inside REST API. What I need to do? At the same time, i have to send basic authentication on all requests and I'll get JSON data.How can i do?
Thanks.
Regards
this is my code
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $username.':'.$password);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'Content-Type: application/json')
);
$result = curl_exec($ch);
curl_close($ch);
I have tried your code and changed variables into array.
Added httpheaders, useragents.
And save to cookies and cookie location.
And tested:
$username = "username";
$password = "password";
$url = "http://localhost/html/login";
$send = "?username=".$username."&password=".$password;
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_VERBOSE => 1,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0',
CURLOPT_POST => true,
CURLOPT_USERNAME, $username,
CURLOPT_USERPWD, $password,
CURLOPT_POSTFIELDS => $send,
CURLOPT_SSL_VERIFYPEER, false,
CURLOPT_HEADER => 1,
CURLOPT_HTTPHEADER => array(
"Accept-Language: en-US;q=0.6,en;q=0.4",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Connection: keep-alive"
),
CURLOPT_COOKIEFILE => "cookies.txt",
CURLOPT_COOKIEJAR => "cookies.txt",
CURLOPT_REFERER => "http://localhost/html/login",
CURLOPT_ENCODING => 'gzip,deflate'
)); //gzip, if modul on
curl_exec($ch);
curl_close($ch);

CURLOPT_POSTFIELDS varaible format

I'm trying to post a parameter with cURL,
when I tried with this type of format :
CURLOPT_POSTFIELDS => "label=sample"
I exactly got "label" key in the server with "sample" as its value
but I get it empty in the server when I sent it out as a variable .
CURLOPT_POSTFIELDS => "label=$email"
$curl = curl_init();
$user_info=$this->web_model->retriveUserInfo();
$email=$user_info->email;
curl_setopt_array($curl, array(
CURLOPT_URL => "https://test.bitgo.com/api/v2/".$coin."/wallet/".$wallet_id."/address",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "label=$email",
CURLOPT_HTTPHEADER => array(
"Accept: */*",
"Accept-Encoding: gzip, deflate",
"Authorization: Bearer v2x4e7cf3fb7e6c2e87bf8103e49756b3892b2e350d6cdbaeb65757980",
"Cache-Control: no-cache",
"Connection: keep-alive",
"Content-Length: 11",
"Content-Type: application/x-www-form-urlencoded",
"Host: test.bitgo.com",
"Postman-Token: b3f2ee7c-9a19-479b-bfe2-27000c90e3c7,d611bde9-3eb1-4e2b-b8f5-a7a5f5485726",
"User-Agent: PostmanRuntime/7.15.2",
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$response = json_decode($response, true);
$err = curl_error($curl);
curl_close($curl);
my main problem is CURLOPT_POSTFIELDS format for variables !
Doc says about CURLOPT_POSTFIELDS:
This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value.
So you can:
Replace: CURLOPT_POSTFIELDS => "label=$email", with CURLOPT_POSTFIELDS => ['label' => $email], and if you'll need more data to pass as POST field you can just add another pair $key => $value to that array or prepare it before setting curl options.
Set POST fields via http_build_query:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); where $ch is curl handle and $data is array of $key => $value pairs where $key is field name.
But keep in mind:
Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.
Many thanks
Finally I had to use Guzzle library simply
$client = new GuzzleHttp\Client(['base_uri' => 'https://test.bitgo.com/api/v2/']);
$response = $client->post($coin.'/wallet/'.$wallet_id.'/address', [
'headers' => [
'Authorization' => 'Bearer v2x4e7cf3fb7e6c2e87bf8103e4975dsddbaeb65ba017b555757980'],
'form_params' => [
"label" => $email
]
very very useful
You can try this
function curl($post = array(), $url, $token = '', $method = "POST", $json = false, $ssl = false){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
if($method == 'POST'){
curl_setopt($ch, CURLOPT_POST, true);
}
if($json == true){
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer '.$token, 'Content-Length: ' . strlen(json_encode($post))));
}else{
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSLVERSION, 6);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
// Proxy example only
if (!empty($proxy)) {
curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:888');
if (!empty($proxyAuth)) {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, 'user:password');
}
}
if($ssl == false){
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$this->statusCode = $statusCode;
if (curl_error($ch)) {
$error = 'CURL_ERROR '.$statusCode.' - '.curl_error($ch);
// print_r('CURL_ERROR '.$statusCode.' - '.curl_error($ch));
throw new Exception('CURL_ERROR '.curl_error($ch), $statusCode);
}
curl_close($ch);
return $response;
}

PHP request to API endpoint with authorized header

I would like to ask you how to use PHP request to API with authorized header.
API end point example is
Quotation Service : ­ POST https://api.website.com/v4/quotation
Content­type: application/json; charset=utf­8
Accept: application/json
Authorization: hmac $id:$milliSeconds:$signature
{
"serviceType": "CARD",
"specialRequests": [
"ROUNDTRIP"
]}
as you mention, they use hmac as an authorization in a header and request parameters is serviceType, specialRequest
I try using PHPCurl to make a request but i'm not a good on it. Please give me and advice how to use Curl with this API.
edit:
<?php
$customerId = "585a-SAMPLE-980dfe0097"; //by provider
$privKey = "MC4CAQACBQDSk4ghAgMB---SAMPLE---QIDAOPFAgMAk7QIDAMYq"; //by provider
$requestTime = (int)(microtime(true) * 1000);
$signature = hash_hmac('sha256', $requestTime, $privKey);
$headers = array(
"Authorization: hmac $customerId:$requestTime:$signature"
);
$params = array(
'serviceType' => 'CARD',
'specialRequests' => array('ROUNDTRIP')
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.samplesite.com/v1/quotations",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => $headers,
));
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Regards,
Hmm ... maybe something like this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.website.com/v4/quotation');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
/* if you want to use SSL certificate, otherwise delete this */
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_CAPATH , '/path/to/certificate');
$auth = hash_hmac('sha1', $id.':'.$milisecond.':'.$signature, <ENCRYPTION KEY>, true);
$headers = array(
'Authorization: '.$auth
);
$params = array(
'serviceType' => 'CARD',
'specialRequests' => array('ROUNDTRIP')
);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);

PHP CURL Background Process - REST API URL

I am trying to execute the background REST API Call with Curl
library in php. I guess it is not working.
can you suggest me ?
$cum_url = http://localhost/test/list;
$post = [ 'id' => $object->id ];
$ch = curl_init($cum_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1);
curl_exec($ch);
curl_close($ch);
UPDATE: Cull error says "Timeout was reached".
Thanks,
Raja K
You need to transfer your post data from array to http parameter string, ex:
$cum_url = "http://localhost/test/list";
$post = [ 'id' => $object->id ];
$postdata = http_build_query($post);
$options = array (CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_AUTOREFERER => true,
CURLOPT_USERAGENT => "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1",
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false);
$ch = curl_init($cum_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt_array ( $ch, $options );
$res = null;
if(!curl_errno($ch)) {
$res = curl_exec($ch);
}
curl_close($ch);
Of course, some option is optional depends on you, ex CURLOPT_USERAGENT. Just show you an example.

php curl: I need a simple post request and retrival of page example

I would like to know how to send a post request in curl and get the response page.
What about something like this :
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL => "http://www.example.com/yourscript.php",
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => array(
'field1' => 'some date',
'field2' => 'some other data',
)
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_close($ch);
// result sent by the remote server is in $result
For a list of options that can be used with curl, you can take a look at the page of curl_setopt.
Here, you'll have to use, at least :
CURLOPT_POST : as you want to send a POST request, and not a GET
CURLOPT_RETURNTRANSFER : depending on whether you want curl_exec to return the result of the request, or to just output it.
CURLOPT_POSTFIELDS : The data that will be posted -- can be written directly as a string, like a querystring, or using an array
And don't hesitate to read the curl section of the PHP manual ;-)
$url = "http://www.example.com/";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
'username' => 'foo',
'password' => 'bar'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$contents = curl_exec($ch);
curl_close($ch);
You need to set the request to post using CURLOPT_POST and if you want to pass data with it, use CURLOPT_POSTFIELDS:
$ch = curl_init();
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_POST, 1);
$data = array(
'username' => 'foo',
'password' => 'bar'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$contents = curl_exec($ch);
curl_close($ch);
try the one in the comments: http://php.net/manual/en/curl.examples-basic.php
(but add curl_setopt($ch, CURLOPT_POST, 1) to make it a post instead of get)
or this example: http://php.dzone.com/news/execute-http-post-using-php-cu
<?php
ob_start();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://example.com/student_list.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
echo $response;
?>
I think you need to add
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $postFields);
Using JSON DATA with CURL
client.php
<?php
$url="http://192.168.44.10/project/server/curl_server.php";
$data=['username'=>'abc','password'=>'123'];
$data = json_encode($data);
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $data
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_close($ch);
echo $result; //here you get result like: username: abc and password: 123
?>
curl_server.php
<?php
$data = file_get_contents('php://input');
$Data= json_decode($data,true);
echo 'username: '.$Data['username']." and password: ".$Data['password'];
?>
Check out my code in this post
https://stackoverflow.com/a/56027033/6733212
<?php
if (!function_exists('curl_version')) {
exit("Enable cURL in PHP");
}
$url = "https://www.google.com/";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "",
CURLOPT_HTTPHEADER => array(
"Accept: */*",
"Cache-Control: no-cache",
"Connection: keep-alive",
"Host: " . url($url),
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36",
"accept-encoding: gzip, deflate",
"cache-control: no-cache",
),
));
function url($url)
{
$result = parse_url($url);
return $result['host'];
}
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo "<textarea>" . $response . "</textarea>";
}
http://codepad.org/YE6fyzCA

Categories