简体   繁体   English

如何在功能中设置SESSION,以便在任何地方使用此SESSION? 这不行

[英]How do I set the SESSION in function, to use this SESSION everywhere? This isn't working

I've got a problem with a SESSION, inside a function. 我在函数内遇到了SESSION问题。

How can I set $_SESSION['idUser'] = $result['idUser']; 如何设置$ _SESSION ['idUser'] = $ result ['idUser']; to a SESSION, which I can use for upcoming activity's. 会议,我可以将其用于即将进行的活动。

    <?php

// Session starts
    session_start();


    class DB_Functions {

        public function getUserByEmailAndPassword($email, $password) {
            $result = mysql_query("SELECT * FROM User WHERE emailadress = '" . $email . "'") or die(mysql_error());
            // check for result 
            $no_of_rows = mysql_num_rows($result);
            if ($no_of_rows > 0) {
                $result = mysql_fetch_array($result);



//This is the session I want to use

$_SESSION['idUser'] = $result['idUser'];

                    return $result;

Assuming this is just a snippet of a larger class, I see no reason why this line: 假设这只是较大类的一小段,我看不出这行的原因:

$_SESSION['idUser'] = $result['idUser'];

wouldn't work (again assuming that $result['idUser'] contains a value). 将不起作用(再次假设$ result ['idUser']包含一个值)。 Ensure that you have session_start(); 确保您具有session_start(); called on all pages that you want to use the global session variable. 在要使用全局会话变量的所有页面上调用。

Delete the space before <?php . 删除<?php之前的空格。 Before session_start() there shouldn't be any output. session_start()之前不应有任何输出。

I suggest using the following in the first place: 我建议首先使用以下内容:

Session Management Library 会话管理库

I highly recommend it. 我强烈推荐它。

  1. Like you wanted, you could use it everywhere. 如您所愿,您可以在任何地方使用它。
  2. It'll keep you from using super globals like $_SESSION (not easy to debug) 它可以防止您使用$ _SESSION之类的超级全局变量(不容易调试)
  3. Make your code more testable and it'll alleviate you from having to manage sessions manually. 使您的代码更具可测试性,这将使您不必手动管理会话。

Example code: 示例代码:

use Symfony\Component\HttpFoundation\Session\Session;

$session = new Session();
$session->start();

// set and get session attributes
$session->set('name', $result['id_user']);
$session->get('name'); //Easy to get 'id_user' in another page.

//Other examples: 
// set flash messages (appears only once, for warnings/alerts)
$session->getFlashBag()->add('notice', 'Profile updated');

// retrieve messages
foreach ($session->getFlashBag()->get('notice', array()) as $message)
{
    echo '<div class="flash-notice">'.$message.'</div>';
}

If you like like what you see here are the links: 如果您喜欢您所看到的内容,请访问以下链接:

Download 下载

Install Instructions 安装说明

Warning 警告

Make sure your PHP session isn't already started before using the Session class. 使用Session类之前,请确保尚未启动PHP会话。 If you have a legacy session system that starts your session, see Legacy Sessions . 如果您有一个旧的会话系统启动您的会话,请参阅旧会话

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM