How can I simulate a broswer request in using Guzzle - laravel

I am trying to get cookies with from a site, but the cookies I receive are not valid while vs. when using the cookies received in the browser are valid. Here is the header values:
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
$cookieClient = new Client(
[
'base_uri' => $url,
'headers' => [
'User-Agent'=>'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36',
'Connection'=>'keep-alive',
'Content-Type'=>'application/json',
],
'connect_timeout' => 20,
"timeout" => 150
]);
$jar = new \GuzzleHttp\Cookie\CookieJar;
$r = $cookieClient->request('GET', 'https://example.com', [
'cookies' => $jar
]);
$arrayJar = $jar->toArray();
$cookiesValue = $arrayJar[2]["Value"];
log::info($cookiesValue);
If Guzzle (V7) is not able to to do so, is there another mehtod to get cookies as while mimicing a browser? The cookies are meant to be utilized in the project.

Related

How to make this postman request with laravel httpClient

I want to make a postman request with Laravel httpClient,the request in postman is like this:
The Content-Type in the header is: application/x-www-form-urlencoded
I tried many ways to make this request with Laravel httpClient, but it either return null or return all of the datas, not the data I am looking for.
I tried this:
$res = Http::withHeaders([
'Content-Type' => 'application/x-www-form-urlencoded',
'Authorization' => 'Basic XXXXXXXXXX'
])->withBody(http_build_query(["uuid"=>$uuid]),"application/json")->post("https://xxx.com.cn/entity.find");
and also tried this:
$res = Http::withHeaders([
'Content-Type' => 'application/x-www-form-urlencoded',
'Authorization' => 'Basic ZHh5LWVpbnRlbGxpZxxxxxxxx'
])->post("https://xxxx.com.cn/entity.find", [
"form_params" => [
"filter" => ['uuid'=>$uuid],
]
]);
All are not work. Could anyone give me some tips about this?

Laravel Guzzle HTTP keep returning 404

I'm using openlibrary's API to fetch book data. I have problem with some API (not all) which keep return 404, but when i'm using postman to test, it's working fine.
$response = Http::get('http://openlibrary.org/search.json', [
'q' => 'Johngreen'
]);
dd($response->body());
I tested this endpoint with Laravel and I had the same problem but it works on Postman and browser.
The problem is related to the User-Agent of the client. If you don't set it, Openlibrary cannot check the source of the API call (browsers and Postman send the own user agent).
I solved with this code:
$guzzle_client = new \GuzzleHttp\Client();
$response = $this->guzzleClient->get("http://openlibrary.org/search.json?q=Johngreen", [
'headers' => ['User-Agent' => 'PUT AN USER AGENT HERE']
]);
$response_body = json_decode($response->getBody()->getContents(), true);
dd($response_body);
Try to use this User Agent:
Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36
or use another one
openlibrary is not accepting guzzlehttp user agent, try using only curl or a browser user agent.
Both of these works
using curl user agent
try{
$response = Http::withHeaders([
'User-Agent' => 'curl/7.65.3'
])->get('https://openlibrary.org/search.json?q=Johngreen');
dd($response->body());
} catch(\Illuminate\Http\Client\RequestException $e){
// Log your errors
}
using browser user agent
try{
$response = Http::withHeaders([
'User-Agent' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36'
])->get('https://openlibrary.org/search.json?q=Johngreen');
dd($response->body());
} catch(\Illuminate\Http\Client\RequestException $e){
// Log your errors
}
For more info on default user agent used by guzzle, see docs
Try code below first to view response all content.
Http::dd()->get('http://openlibrary.org/search.json', [
'q' => 'Johngreen'
]);
You are using Guzzle. Try using the below code for consuming API.
$client = new \GuzzleHttp\Client();
$response = $client->get('http://openlibrary.org/search.json', [
'query' => ['q' => 'Johngreen']
]);
dd(json_decode($response->getBody()));

Getting null when posting data using Guzzle Client in Laravel

Am working on an a Laravel application whereby am posting some data to an API using Guzzle Http Client. The APIhas passport authentication which requires the token of the authenticated user to be passed on the headers. The headers also accept application/json as content-type and accept type.
I am also passing the data via POST request
The problem is that I keep getting a null response.
public
function post_policies($data, $token, $url) {
$client = new Client();
$serverURL = 'http://localhost/digital-apps-apis/public'.
'/'.$url;
$body = $client - > request('POST', $serverURL, $data, [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization' => 'Bearer '.$token,
]) - > getBody();
$contents = $body - > getbody() - > getContents();
$data = json_decode($contents);
dd($data);
}
$body = $client->request('POST', $serverURL , $data, [
'debug' => true, //switch it to false before go live
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $token,
]]
)->getBody();
You must define your headers in the headers array.
Since it's a post i don't see you actually sending any data in the body. But if you do use the form_params array exactly like i used the headers array.

Fetch From a Dump Array

I have a dump array and want the value of email, how can I do it?
string(614) "a:6:{s:10:"session_id";s:32:"f0fd7825ad5e0760c635f136e1f508db";s:10:"ip_address";s:15:"202.142.176.142";s:10:"user_agent";s:120:"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36 OPR/27.0.1";s:13:"last_activity";i:1423743791;s:9:"user_data";s:0:"";s:9:"logged_in";a:8:{s:7:"user_id";s:2:"78";s:8:"username";s:5:"Ahsan";s:7:"role_id";s:1:"1";s:9:"user_type";s:8:"Reseller";s:19:"reseller_company_id";s:1:"1";s:9:"full_name";s:14:"Muhammad Ahsan";s:5:"email";s:17:"ahsan#tasmimy.com";s:5:"thumb";s:18:"14236608537282.jpg";}}e92d7c14027cd35d0a2e45e3e0d50328"
All you need to do to get the session is after you have set your sessions.
Auto load session library and add encryption key in config.php and enable sessions. Codeigniter 2.2.1 and Codeigniter 3 are different slightly.
$data = array(
'isLogged' => true,
'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
);
$this->session->set_userdata($data);
Then you should be able to use echo $this->session->userdata('email');

CodeIgniter Session Issues

I set session in a controller function like
$search = array(
'search_count' => count($data['result']),
'projectInfo' => $data['result']
);
$this->session->set_userdata($search);
where $data['result'] is an array;
but if I try to access this variable in other function of same controller it shows nothing:
print_r($this->session->userdata('projectInfo'));
though on using print_r($this->session->userdata('search_count')); it shows correct value.
also if I use print_r($this->session->all_userdata()); in second function of same controller it does not show array value index which I have already set in first function
Array
(
[session_id] => 4adf3a42ee64ffca2b2f273cb293a10a
[ip_address] => 127.0.0.1
[user_agent] => Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1
[last_activity] => 1347689522
[user_data] =>
)
If I'm correct you can't save arrays into a session without serializing them first.
$search = array(
'search_count' => count($data['result']),
'projectInfo' => $data['result']
);
$this->session->set_userdata($search);
Becomes:
$search = array(
'search_count' => count($data['result']),
'projectInfo' => serialize($data['result'])
);
$this->session->set_userdata($search);
Now if you want to retrieve the array:
$data = unserialize($this->session->userdata('projectInfo'));
print_r($data);
Please note that you should use the database to store sessions when you are setting large amounts of data in a session.
config.php
$config['sess_use_database'] = TRUE;
Thanks I added Native PHP Session Class

Resources