phongvan phongvan - 1 year ago 61
PHP Question

How to check that you have been login use session & curl?

I need login to get token to run other api, I use curl to post. This is my code:

function login($email, $password){
if (!isset($_SESSION["access_token"])){
print("\nRUNNING LOGIN API SCRIPT...\n\n");
$data = array('password'=> $password,
'username'=> $email,

$login = SendRequest('***', true, $data, array('Content-Type: application/x-www-form-urlencoded; charset=UTF-8'), true);

$token = json_decode( $login[1],true)['access_token'];
$_SESSION["access_token"] = $token;
print "\nEND LOGIN API SCRIPT!!!\n";
$token = $_SESSION["access_token"];
return $token;

Here is my setup cookies in SendRequest function:

curl_setopt($ch, CURLOPT_COOKIEFILE, '/Users/***/Desktop/***/cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEJAR, '/Users/***/Desktop/***/cookies.txt');
curl_setopt($ch, CURLOPT_COOKIESESSION, 0);

But it not work, api alway call when I rerun script. What is my wrong ?

Answer Source

My original answer was:

The way you described it, it seems like your session is ALWAYS not set. Remember to check whether or not you're running session_start() before invoking your login function.

The $_SESSION is not set if you don't start the session.

From the chat session with OP I understood he is actually running it from the command line, and that's why $_SESSION is not working.

$_SESSION is a superglobal filled by session_start native PHP function. When PHP receives a HTTP request through a webserver, it creates a local file under a hash name and store your session data in said file. Through the HTTP response, it sets a cookie with the hash name created. This is how PHP knows which session belongs to which user and how to recover data from previous executions (as in a web environment, a request is processed from begin to end and then responded).

Command line PHP has no access to $_SESSION 'cause it doesn't follow the same process flow a http request runs, it has no cookies and can't create them natively.

Maybe setting up a curl client with a cookie jar may work, but it would be an extra layer as this curl client would call "login.php" file in a webserver, and this file would call the login API.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download