在不同的 php 文件之间使用 SESSIONS 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26683125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:00:22  来源:igfitidea点击:

Use SESSIONS variables between different php files

phpsession

提问by Nomis

I am new to $_SESSIONSbut needs it to re-use variables between different php files. In the below code I want to use the variable $wordin another php file, but I am unsure how to do this.

我是新手,$_SESSIONS但需要它在不同的 php 文件之间重用变量。在下面的代码中,我想$word在另一个 php 文件中使用该变量,但我不确定如何执行此操作。

My php filelooks like this:

我的php 文件如下所示:

<?php
  if (isset($_POST["search"])) {    

    //include database connection

 $word = mysql_real_escape_string($_POST["search"]);
 $word = htmlentities($word);

 $sql = ("SELECT task_id, task_date FROM customer JOIN task ON customer.id = task.customer_id WHERE mobil = $word ORDER BY task_date DESC LIMIT 0, 10");

$results = mysql_query($sql);
 if (mysql_num_rows($results)==0) {
  echo $word, " text bla";
}else {
  echo $word, " text bla bla";
   while ($row = mysql_fetch_assoc($results)) {
    echo '<pre>', print_r($row), '<pre>';
   }
  } 
}?>

Looking forward to your suggestions.

期待您的建议。



---UPDATE Sessions still not working on page2.php?---

---更新会话仍然无法在 page2.php 上工作?---

I do not understand why $_SESSIONdo not work. One page1.php I can echo($_SESSION['word'])and get the correct value, but one page2.php I get ('$'."_SESSION['word'] isn't set because you had never been at file one");

我不明白为什么$_SESSION不工作。一个 page1.php 我可以echo($_SESSION['word'])得到正确的值,但是一个 page2.php 我得到('$'."_SESSION['word'] isn't set because you had never been at file one");

I tested all the below solutions but none of them worked = same result on page2.php.

我测试了以下所有解决方案,但没有一个有效= page2.php 上的结果相同。

My page1.php file.

我的 page1.php 文件。

<?php
session_start();

//if we got something through $_POST
    if (isset($_POST["search"])) {  

    // include database connection
        $connect = mysql_connect('localhost', 'root', 'NomiS123') or die(mysql_error());
        mysql_select_db('workcard');

    // sanitize user input
        $word = mysql_real_escape_string($_POST["search"]);
        $word = htmlentities($word);

    // build search query to the database
        $sql = ("SELECT task_id, task_date FROM customer JOIN task ON customer.id = task.customer_id WHERE mobil = $word ORDER BY task_date DESC LIMIT 0, 10");

        // get results
        $_SESSION['word'] = $word;
        $results = mysql_query($sql);
        if (mysql_num_rows($results)==0) {
            $_SESSION['word'] = $word;
            echo($_SESSION['word']. "<br>");
            var_dump($_SESSION);
            echo "<br>";
            echo "link link <br>";
            echo "<a href=\"../page2.php/\">new card</a> <br>";
            echo "<a href=\"//cykelc/\">New Search</a>";
        }   else {
                echo $word, " bla bla text <br> Create card <br>";
                echo "Edit info on: ", $word, "<br>";
                echo "<a href=\"//cykelc/\">New Search</a> <br>";

                while ($row = mysql_fetch_assoc($results)) {
                    echo '<pre>', print_r($row), '<pre>';
                    }
                    //$results->free();
            }   
        }
// mysql_close($connect);
?>

My PAGE2.php file.

我的 PAGE2.php 文件。

<?php 
session_start();
if(isset($_SESSION['word'])) {
    $word = $_SESSION['word'];
    echo($word);
} else {
    die('$'."_SESSION['word'] isn't set because you had never been at file one");
}
?>

I am going insane over this.

我快要疯了。



UPDATE - SOLVED
I tested all the below suggestions but none of them worked which was weird because I could set and echo out the sesson_id()on page1.php and page2.php, but on page2.php I got a different sesson_id(). I began to look into my MAMP sessions settings, but everything was correct set. The solution was "simply" to place the session_start();on the very top on page2.php. And by the very top I mean before everythingeven the <!DOCTYPE html>etc.
Solved + lesson learned :-)

更新 - 已解决
我测试了以下所有建议,但它们都sesson_id()不起作用,这很奇怪,因为我可以在 page1.php 和 page2.php 上设置和回显,但是在 page2.php 上我得到了不同的sesson_id(). 我开始查看我的 MAMP 会话设置,但一切都设置正确。解决方案是“简单地”将session_start();放在 page2.php 的最顶部。最重要的是我的意思是在一切之前,甚至<!DOCTYPE html>等等。
解决了+学到的教训:-)

采纳答案by jankal

First you must start the seesion via session_start();directly after the opening PHP 'tag' (<?php session_start();... ?>)

首先,您必须session_start();在打开 PHP '标签' ( <?php session_start();... ?>)之后直接通过

Then you must save your variable to the session. You can use $_SESSION['word'] = $word;for this purpose.

然后,您必须将变量保存到会话中。您可以$_SESSION['word'] = $word;为此目的使用。

And in the other file you must also use session_start();at the very first after the <?php'tag'.

在另一个文件中,您还必须session_start();<?php“标签”之后的第一个使用。

Then you could access the old variable via $word = $_SESSION['word'];.

然后你可以通过$word = $_SESSION['word'];.

You now can also use $wordin the second file. But you only can use it if it's set (and you where at the first file before).

您现在还可以$word在第二个文件中使用。但是你只能在它被设置的情况下使用它(并且你之前在第一个文件中的位置)。

File one:

档案一:

<?php
session_start();
    if (isset($_POST["search"])) {    

    //include database connection

 $word = mysql_real_escape_string($_POST["search"]);
 $word = htmlentities($word);
 $_SESSION['word'] = $word;

 $sql = ("SELECT task_id, task_date FROM customer JOIN task ON customer.id = task.customer_id WHERE mobil = $word ORDER BY task_date DESC LIMIT 0, 10");

$results = mysql_query($sql);
 if (mysql_num_rows($results)==0) {
  echo $word, " text bla";
}else {
  echo $word, " text bla bla";
   while ($row = mysql_fetch_assoc($results)) {
    echo '<pre>', print_r($row), '<pre>';
   }
  } 
}?>

File two:

文件二:

<?php
session_start();
if(isset($_SESSION['word'])) {
    $word = $_SESSION['word'];
} else {
    die('$'."_SESSION['word'] isn't set because you had never been at file one");
}
echo $word;
?>

Hope this helps ;)

希望这可以帮助 ;)

回答by Nicolas

To use PHP sessions you would do the below:

要使用 PHP 会话,您可以执行以下操作:

Initiate the session, session_start();

启动会话, session_start();

Note:session_start();must be the first line of PHP in your file.

注意:session_start();必须是文件中 PHP 的第一行。

Create the session, $_SESSION['word'] = $word;

创建会话, $_SESSION['word'] = $word;

To access it on another page:

要在另一个页面上访问它:

Initiate the session, session_start();

启动会话, session_start();

Access the session, $word = $_SESSION['word'];

访问会话, $word = $_SESSION['word'];

回答by HitMeWithYourBestShot

Call session_start();at the beginning of the PHP file, and if anything is set in the $_SESSIONsuper global array, you can re-access it.

session_start();在PHP文件的开头调用,如果$_SESSION超级全局数组中设置了任何内容,则可以重新访问它。

If it isn't set you can set it with:
$_SESSION['a name']= 'some thing';

如果未设置,您可以使用以下命令进行设置:
$_SESSION['a name']= 'some thing';

So for your example:
PHP FILE1

所以对于你的例子:
PHP FILE1

<?php
session_start();
$_SESSION['word'] = $_POST['word']
?>

PHP FILE2

PHP文件2

<?php
session_start();
echo $_SESSION['word'];
?>

回答by Neglected Sanity

There are many many ways to accomplish this it all depends on how you want to use it. You can include your file in that file, you can use require or require_once, or yes you can use the session super global.

有很多方法可以实现这一点,这完全取决于您想如何使用它。您可以在该文件中包含您的文件,您可以使用 require 或 require_once,或者您可以使用会话超级全局。

The $_SESSION super global will be accessible to all files within your application. The only thing you need to make sure you do is use session_start() on the page as the first thing on that page. If you use session_start() after any output has gone to teh browser it will not work. Usually you will want to run session_start() as the first line on your index.php file. Then you can use ...

应用程序中的所有文件都可以访问 $_SESSION 超级全局变量。您需要确保做的唯一一件事是在页面上使用 session_start() 作为该页面上的第一件事。如果在任何输出进入浏览器后使用 session_start(),它将无法工作。通常你会希望在 index.php 文件的第一行运行 session_start()。然后你可以使用...

<?php
if (isset($_POST["search"])) {    

//include database connection

 $word = mysql_real_escape_string($_POST["search"]);
 $word = htmlentities($word);
 $_SESSION['word'] = $word;

 $sql = ("SELECT task_id, task_date FROM customer JOIN task ON customer.id = task.customer_id WHERE mobil = $word ORDER BY task_date DESC LIMIT 0, 10");

$results = mysql_query($sql);
 if (mysql_num_rows($results)==0) {
  echo $word, " text bla";
}else {
  echo $word, " text bla bla";
   while ($row = mysql_fetch_assoc($results)) {
    echo '<pre>', print_r($row), '<pre>';
   }
  } 
}?>

then in any page you want access to it just cal it up...

然后在您想要访问它的任何页面中调用它...

<?php
    echo $_SESSION['word'];

Hope that helps

希望有帮助

回答by Spencer Wieczorek

session_start()means that you are using session variables, make sure it's at the top of the page. To make a session you do: $_SESSION['word'] = [some value]. This can be used between pages as long as you have session_start()at the top. Make sure to make sure it's set first, if it's not set initialize.

session_start()意味着您正在使用会话变量,请确保它位于页面顶部。要进行会话,请执行以下操作:$_SESSION['word'] = [some value]。只要您session_start()在顶部,就可以在页面之间使用它。如果没有设置初始化,请确保首先设置它。

<?php session_start(); ?>

...

<?php 
    if ( isset($_SESSION['word']) ) {
      $_SESSION['word'] = /* change existing session value */;
    } else {
      $_SESSION['word'] = /* new session value */;
    }
?>

回答by Benz

You first of all should start the session using the function 'session_start()'. Place this in your index.php/bootstrap.php (a file that is always loaded when loading your website).

您首先应该使用函数“session_start()”启动会话。把它放在你的 index.php/bootstrap.php (加载你的网站时总是加载的文件)。

After that, you can use the '$_SESSION' global to set data.

之后,您可以使用 '$_SESSION' 全局设置数据。

//In your index.php/boostrap.php
session_start();

In the file you want to save the $word:

在要保存 $word 的文件中:

$_SESSION['myword'] = $word;

And from that point you can use this variable on another page.

从那时起,您可以在另一个页面上使用此变量。

//On another page, after the variable is being set
echo $_SESSION['myword']; 

Be aware that when you are using shared webhosting, your session data is often stored in a global folder on the webserver and can be used by every website on that server. To prevent this, you should change you session save path using the 'session_save_path()' function or by creating you own session handler.

请注意,当您使用共享虚拟主机时,您的会话数据通常存储在网络服务器上的全局文件夹中,可供该服务器上的每个网站使用。为了防止这种情况,您应该使用“session_save_path()”函数或通过创建自己的会话处理程序来更改会话保存路径。