I want to get data from External API. but, I must login to get session before Getting data and I must Logout after get data
this is my code
use GuzzleHttp\Client;
$client = new Client();
$res = $client->request('POST', 'Login_URL', [
'json' => [
"JSON param"
]
]);
$res = $client->request('GET', 'Get_URL');
$res = $client->request('POST', 'Logout_URL');
but I can only the first step (Login). and I getting error message in the second step to get data
Client error: `GET "Get_URL" ` resulted in a `401 Unauthorized` response:{"message":"You are not logged in."}
how I can run all this code with login session on first step ?
CodePudding user response:
this code for you to do login and logout session
$cookie_jar = tempnam("tmp", "cookie");
//login
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => '_URL',
CURLOPT_RETURNTRANSFER=> true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION=> true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_COOKIEJAR => $cookie_jar,
CURLOPT_POSTFIELDS =>'{
"name" : "****",
"password" : "****",
"company" : "****"
}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'),
)
);
$response = curl_exec($curl);
//get data
curl_setopt_array($curl, array(
CURLOPT_URL => '_URL',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_COOKIEFILE => $cookie_jar
)
);
$datapo = json_decode(curl_exec($curl));
//logout
curl_setopt_array($curl, array(
CURLOPT_URL => '_URL',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => '{
"name" : "****",
"password" : "****",
"company" : "****"
}',
CURLOPT_COOKIEFILE => $cookie_jar
)
);
$response = curl_exec($curl);