【问题标题】:Session doesn't start in a specific page会话未在特定页面中开始
【发布时间】:2019-06-04 11:36:38
【问题描述】:

编辑:我修好了,问题是<?php 之前的空格。 感谢 cmets。

会话正在除 index.php 之外的所有页面上工作

错误: session_start():当第 13 行的 /home/site/public_html/connection.php 中已发送标头时无法启动会话

connection.php:

<?php

try {
$db=new PDO('mysql:host=localhost;dbname=testdb','testuser','123456');
$db->exec("SET CHARACTER SET utf8"); }
catch(PDOExpception $e) {
echo $e->getMessage(); }

ob_start(); session_start(); # (line 13)

?>

index.php:

<?php
include 'connection.php'; include 'seo.php';
$connect_site=$db->prepare("SELECT * FROM site WHERE id=?");
$connect_site->execute(array(1));
$site=$connect_site->fetch(PDO::FETCH_ASSOC);
?>

<!DOCTYPE HTML>
<html>
<head>
...

【问题讨论】:

  • session_start 应该先行。
  • 错误消息谈到了 connection.php 中的第 13 行,但您向我们展示的内容甚至似乎没有 13 行 - 除非您在 之后有尾随空格/换行符?&gt;。删除那个?&gt;,在脚本文件的最后没有必要 - 而且它经常会导致这样的错误,这就是为什么大多数编码指南都建议这样做。
  • @Jonnix 我试过了,还是一样。
  • 如果您移动了它,您应该至少会收到一条稍微不同的错误消息。

标签: php session header


【解决方案1】:

你必须总是把

session_start();

在所有代码的开头。 不管它是什么,什么都不需要去:)

享受编码!

【讨论】:

  • 它已经在所有页面的顶部。所有页面都包含类似index.php开头的代码结构但其他页面运行良好,index.php没有。
  • 但是在你的代码中它不是第一个所以试试吧,当我说首先它是第一行。
【解决方案2】:

在 connection.php 中更改您的代码

<?php ob_start(); session_start();  ?>
<?php
    try {
      $db=new PDO('mysql:host=localhost;dbname=testdb','testuser','123456');
      $db->exec("SET CHARACTER SET utf8"); }
    catch(PDOExpception $e) {
      echo $e->getMessage(); 
    }
?>

【讨论】:

  • 谢谢老哥,问题是&lt;?php前面的空格。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-05
  • 2017-11-16
相关资源
最近更新 更多