无法在 PHP 中显示会话消息


unable to show session message in PHP?

我在类文件中设置了会话消息,就像$_SESSION['op_status'] = 'MY MESSAGE HERE';然后重定向页面header("location:news.php");页面重定向到news.php但会话消息没有显示。

配置.php:

<?php
   session_start();
   // DATABASE CONFIURATION GOES HERE
?>

新闻.php:

<?php
  require_once 'config.php';
  require_once 'classes/class.news.php';
  $objNews = new News();
  if(isset($_POST['submit']) && $_POST['submit'] == 'add')
   $objNews->add();
?>
<span class='text-warning'><?php echo $_session['op_status']; ?></span>

班级新闻.php:

public function add() {
  if(){
     // SOME CODE GOES HERE
  } else {
     $_SESSION['op_status'] == 'Already Exist';
  }
}

你需要在 header() 之后使用 exit()。

 $_SESSION['msg']="Hello";
 header("Location: account.php");
 exit();

然后在帐户中.php使用

 echo $_SESSION['msg'];

确保session_start();在要显示/创建会话消息的每个页面上。

与其使用这种方式,我更喜欢使用以下函数。(以区分它是错误消息还是成功,如引导 HTML 标记)

 function _redirect($url=NULL, $message=NULL, $message_type=NULL){
      $_SESSION['sess_flash_message']= array();
      if($message){
          switch($message_type){ 
            case 'success': $_SESSION['sess_flash_message'][] = '<div class="alert alert-success"><button data-dismiss="alert" class="close" type="button">×</button>'.$message.'</div>';break;
            case 'error': $_SESSION['sess_flash_message'][] = '<div class="alert alert-error"><button data-dismiss="alert" class="close" type="button">×</button>'.$message.'</div>';break;
            case 'notice': $_SESSION['sess_flash_message'][] = '<div class="alert alert-info"><button data-dismiss="alert" class="close" type="button">×</button>'.$message.'</div>';break;
            case 'warning': $_SESSION['sess_flash_message'][] = '<div class="alert alert-block"><button data-dismiss="alert" class="close" type="button">×</button>'.$message.'</div>';break;
            default: $_SESSION['sess_flash_message'][] = $message;
          }
      }
    if($url) {
        header("Location: ".$url);
    } else {
        header("Location: ".$_SERVER['HTTP_REFERER']);
    }
     exit();
     ob_flush();    
}

并致电_redirect('login.php','You need to login first!','warning');

你必须改变:

$_session['op_status']

自:

$_SESSION['op_status']

因为$_SESSION是超全局的,必须是大写的。

另作为参考,请参阅:http://php.net/manual/en/language.variables.superglobals.php

你也在这里做一个比较:

$_SESSION['op_status'] == 'Already Exist';

我认为您想分配它,因此将其更改为:

$_SESSION['op_status'] = 'Already Exist';

另外,我希望您在if声明中有一个条件,否则它不起作用。

注意:确保session_start();驻留在使用会话的所有页面中。

<小时 />

旁注:

您可以使用以下命令在测试环境中添加错误报告:

<?php
    ini_set("display_errors", 1);
    error_reporting(E_ALL);
// rest of your code below 
很可能

您尚未开始或继续会话

<?php
session_start();
// your code
?>

另一种选择是通过 URL 传递消息。这是你如何将它们关闭:

$myMessage = "<YOUR MESSAGE HERE>";
header("Location: http://www.somesite.com/news.php?mymessage=" . $myMessage);

然后在新闻上.php:

$theMessage = $_GET['mymessage'];