与cURL的会话 [英] Sessions with cURL

查看:153
本文介绍了与cURL的会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我有一个非常简单的问题。我目前正在做一个API,在你可以使用它,你必须登录。登录通过http请求进行,因此要登录您将访问

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



当电子邮件和密码正确时,我设置了一些会话变量,我开始一个会话:

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

但是,当我访问api并且我从我的终端通过cURL请求,它说,我没有授权,而我第一次执行登录请求。在每个api调用在另一个页面上,我检查会话变量。如果已设置,则用户已登录:

  function checkSession()
{
session_start );
if(!isset($ _ SESSION ['idUser'])||!isset($ _ SESSION ['email']))
{
print json_encode(array(error=> ; 未经授权));
exit();
}
}

为什么说我未经授权?当我从网络浏览器访问这些页面时,一切正常。



谢谢!

解决方案

这可能是因为您的PHP会话使用Cookie来代表将会话存储在用户的浏览器上。这就是你的PHP应用程序每次向你的PHP页面发出HTTP请求时识别你的用户的方式。



你必须使用cUrl的'cookie'选项。 / p>

基本上,您将首先使用

登录和存储会话cookie。

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

然后,您接下来请求cUrl 发回 cookie

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

您将在Cookie.txt中看到以纯文本形式存储的Cookie


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!

解决方案

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

这篇关于与cURL的会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆