如果我使用相对路径,当我需要包含常量的php文件时,我遇到了问题。当我将其更改为绝对路径时,它运行良好,但我不想在它处于此状态时将其部署到生产中。我得到的错误是:
注意:使用未定义的常量DB_SERVER - 在第10行的C:\ xampp \ htdocs \ photoGallery \ includes \ database.php中假设为“DB_SERVER”
注意:使用未定义的常量DB_USER - 在第10行的C:\ xampp \ htdocs \ photoGallery \ includes \ database.php中假定为“DB_USER”
注意:使用未定义的常量DB_PASS - 在第10行的C:\ xampp \ htdocs \ photoGallery \ includes \ database.php中假定为“DB_PASS”
有三个文件: database.php,需要config.php - >它们都位于名为“includes”
的同一目录中并且有index.php,它位于一个名为'public'
的级别的目录中config.php中的代码
// Database Constants
defined('DB_SERVER') ? null : define("DB_SERVER", "localhost");
defined('DB_USER') ? null : define("DB_USER", "ugallery");
defined('DB_PASS') ? null : define("DB_PASS", "ugallerypword");
defined('DB_NAME') ? null : define("DB_NAME", "photo_gallery");
database.php中的代码
require_once("config.php");
class MySQLDatabase {
private $connection;
function __construct() {
$this->open_connection();
}
public function open_connection() {
$this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if(!$this->connection) {
die("Database connection failed: ".mysql_error());
} else{
$db_select = mysql_select_db(DB_NAME, $this->connection);
if(!$db_select) {
die("Database selection failed: ".mysql_error());
}
}
}
public function close_connection() {
if(isset($this->connection)) {
mysql_close($this->connection);
unset($this->connection);
}
}
public function query($sql) {
$result = mysql_query($sql, $this->connection);
$this->confirm_query($result);
return $result;
}
private function confirm_query($result) {
if(!$result) {
die("Database query failed: ".mysql_error());
}
}
public function mysql_prep( $value ) {
$magic_quotes_active = get_magic_quotes_gpc();
$new_enough_php = function_exists( "mysql_real_escape_string" ); // i.e. PHP >= v4.3.0
if( $new_enough_php ) { // PHP v4.3.0 or higher
// undo any magic quote effects so mysql_real_escape_string can do the work
if( $magic_quotes_active ) { $value = stripslashes( $value ); }
$value = mysql_real_escape_string( $value );
} else { // before PHP v4.3.0
// if magic quotes aren't already on then add slashes manually
if( !$magic_quotes_active ) { $value = addslashes( $value ); }
// if magic quotes are active, then the slashes already exist
}
return $value;
}
}
$database = new MySQLDatabase();
index.php中的代码
<?php require_once("../includes/database.php"); ?>
<?php
if(isset($database)) { echo "true";} else { echo "false";}
echo "<hr />";
echo $database->mysql_prep("It's working");
?>
如果我将database.php中的require_once更改为
require_once($_SERVER['DOCUMENT_ROOT']."/photoGallery/includes/config.php");
然后一切正常。
有关为何发生这种情况的任何线索?
答案 0 :(得分:1)
使用php5.3及以上版本中的 DIR 解决了这个问题
在database.php文件中
require_once(__DIR__."/config.php");