0

I have this code in php that retrieves login authentication from an API. My problem is, I cannot properly extract the curl response from this code.

$baseURL = "http://127.0.0.1:8000/api"; $loginURL = $baseURL."/login"; $data = array( 'email'=>'[email protected]', 'password'=>'sample' ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $loginURL); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $preAuthToken = curl_exec($ch); curl_close($ch); echo "Response: ".$preAuthToken; 

What it displays in page is something like tjis

 { "access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC8xMjcuMC4wLjE6ODAwMFwvYXBpXC9sb2dpbiIsImlhdCI6MTU0NDE3ODU3NSwiZXhwIjoxNTQ0MTgyMTc1LCJuYmYiOjE1NDQxNzg1NzUsImp0aSI6IjRSVEhiNGx3aUxoYTlJZjciLCJzdWIiOjUsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEiLCJtZXJjaGFudENvZGUiOiI4NTYyMzJiYSIsImhhc2hlZElkIjoiOHYiLCJsb2dpblR5cGUiOiJtZXJjaGFudFVwbG9hZCIsIjJmYUVuYWJsZWQiOmZhbHNlfQ.gnpmb8HbeRK7FlG5b-GDh-CMR5oBA5qXWfjcEtZZTs8", "token_type":"bearer", "expires_in":3600 }Response: 1 

I am confused why the echoed response is Response: 1? How can I properly extract the JSON response and get the access_token field?

3
  • 4
    Since you're not using _RETURNTRANSFER, the response goes straight to stdout. And the trailing garbage is caused by echo "Response: ".$preAuthToken; Commented Dec 7, 2018 at 10:41
  • You can use this tools to convert cURL command into PHP. incarnate.github.io/curl-to-php Commented Dec 7, 2018 at 10:45
  • oh ok. I got it thanks. Commented Dec 7, 2018 at 10:45

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.