Sessions with cURL

耗尽温柔 提交于 2019-12-12 02:37:47

问题


I think I have a very simple problem. I'm currently working on an API and before you can use it, you have to login. Logging in goes via a http request, so to login you would access

http://myapi.com/login.php?email=mail@mail.com&password 

for example.

When the email and the password are correct, I set some session variables and I start a session:

session_start();
$_SESSION['idUser'] = $row['id'];
$_SESSION['email'] = $row['email'];
print(json_encode(array("authenticated" => true)));

However, when I access the api and I do a request (not login) by cURL from my terminal, it says that I'm not authorized, while I first executed the login request. On every api call on another page I check the session variables. If they are set, the user is logged in:

function checkSession()
{
    session_start();
    if(!isset($_SESSION['idUser']) || !isset($_SESSION['email']))
    {
            print json_encode(array("error" => "Not authorized"));
            exit();
    }
}

Why does it say that I'm not authorized? When I access the pages from a web browser, everything is working fine.

Thanks!


回答1:


That's probably because your PHP session uses cookies on your behalf to store the session on the user's browser. That's how your php app can recognize your users each time they make an HTTP request to your PHP pages.

You have to play with the 'cookie' options of cUrl.

Basically, you would first login and store the session cookie with with

curl -c cookies.txt http://myapi.com/login.php?email=mail@mail.com&password=yourpassword

Then you do next requests telling cUrl to send back the cookie

curl -b cookies.txt http://myapi.com/login.php?email=mail@mail.com&password 

You'll see your cookie(s) stored as plain text inside cookies.txt




回答2:


Need a cookie jar...

http://curl.haxx.se/libcurl/php/examples/cookiejar.html

Browser cookies != your codes (curl client) cookies.

Now I got cookie monsters song stuck in my head...



来源:https://stackoverflow.com/questions/12752555/sessions-with-curl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!