我有三个 PHP 文件,如下所示:
配置.php
<?php
session_start();
$database_server = "localhost";
$database_name="dbname";
$database_username="root";
$database_password="";
$_SESSION["server"] = $database_server;
$_SESSION["dbname"] = $database_name;
$_SESSION["dbuser"] = $database_username;
$_SESSION["dbpassword"] = $database_password;
?>
db.php
<?php
include("config.php");
session_start();
//config file for database
$con = mysql_connect($_SESSION["server"],$_SESSION["dbuser"],$_SESSION["dbpassword"]) or die(mysql_error());
if ($con)
{
$dbhandler = mysql_select_db($_SESSION["dbname"] , $con) or die(mysql_error());
}
else
{
echo "not possible to connect to database";
}
?>
标题.php
<?php
include ("../config/db.php");
?>
<div class="topbar">
<div class="fill">
<div class="container">
<h3><a href="#">title</a></h3>
<ul>
<li><a href="#">General Config</a></li>
<li class="active"><a href="#">Add title</a></li>
<li><a href="#">title</a></li>
<li><a target="_blank" href="http://www.site.com/">website</a></li>
</ul>
</div>
</div>
</div>
我正在使用 xampp 进行开发,每次尝试运行 header.php 时都会收到以下错误:
Deprecated: Assigning the return value of new by reference is deprecated in C:\xampp\php\PEAR\Config.php on line 80
Deprecated: Assigning the return value of new by reference is deprecated in C:\xampp\php\PEAR\Config.php on line 166
Notice: Undefined index: server in C:\xampp\htdocs\ossila\config\db.php on line 5
Notice: Undefined index: dbuser in C:\xampp\htdocs\ossila\config\db.php on line 5
Notice: Undefined index: dbpassword in C:\xampp\htdocs\ossila\config\db.php on line 5
Notice: Undefined index: dbname in C:\xampp\htdocs\ossila\config\db.php on line 8
说实话我不知道这些问题从何而来? 我使用的是 xampp 1.7.7(最新版本),是因为 xampp 中的一些配置错误吗? 或者我应该使用其他方式来配置 session ?
最佳答案
我在这里发现了一些问题。
您不应在 session 中保存数据库连接。您可以安全地在 config.php 中定义变量并在 db.php 中调用它,只要您在 db.php 中包含 config.php
不要在同一进程中调用 session_start 两次。如果你想安全,请在 PHP 处理的一开始就调用它(可能是包含 header.php 的页面)
应该使用
realpath(dirname(__FILE__))
来包含文件,这样更安全,可以避免很多错误
这是 config.php 文件:
<?php
//session_start(); It doesn't make sense to call that in db.php, call it at the beginning of your page
$database_server = "localhost";
$database_name="dbname";
$database_username="root";
$database_password="";
?>
db.php
<?php
include(realpath(dirname(__FILE__))."/config.php");
$con = mysql_connect($database_server,$database_username,$database_password) or die(mysql_error());
if ($con)
{
$dbhandler = mysql_select_db($database_name , $con) or die(mysql_error());
}
else
{
echo "not possible to connect to database";
}
?>
关于php - 无法弄清楚在 PHP 中使用 include() 无法访问 session 的问题是什么;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9908140/