dongshicuo4844 2009-08-16 06:50
浏览 171
已采纳

require_once被忽略了

strange problem with php on windows... my application loads a 'core' file that loads a settings file, registers autoloads, does initialization etc. at the top of the core file I have include_once("config.php"); this works fine for anything in the current directory, if I include the core file from a separate directory though it just silently ignores the include of the config file... has anyone seen this before?

/webroot/core.php

<?php
  require_once "config.php";
  //register autoloads
  //do some initialization... standard stuff
?>

/webroot/config.php

<?php
  define("WEB_ROOT","/webroot");
  define("DB_USER","root");
  // ... more stuff...
?>

/webroot/admin/index.php

<?php
  require_once("../dbconnect.php");
  echo WEB_ROOT;
  // print string literal WEB_ROOT rather than value in config.php
?>

My understanding is that file operations are relative to the directory of the file making the request, shouldn't the require_once("config.php") select the file relative to core.php? This code works just as I'd expect on a mac or Linux but not at all on windows, (if I change the require to use the full path or ../, it works)

The real madness is that the require_once("config.php") doesn't throw any errors but none of the code inside is executed!

  • 写回答

3条回答 默认 最新

  • doutusheng5879 2009-08-16 07:18
    关注

    If PHP silently ignore errors, try to put at the top of file that is requested:

    ini_set('display_errors', 'On');
    error_reporting(E_ALL);
    

    Now all errors should be visible.

    Then the best practice (according to me) is to in file that is requested (not in any of included files) define some constant with full filesystem path for application root. So in index.php if application root is /webroot/admin:

    define('APP_DIR', dirname(__FILE__));
    

    After that when you include something, use this constant. If the directory structure is:

    /webroot/
        admin/
            index.php
        config.php
        core.php
    

    And you want to include config.php into index.php:

    require_once APP_DIR . '/../config.php';
    

    In core.php to include config.php it would be:

    require_once APP_DIR . '/../config.php';
    

    And so on.

    Using absolute filesystem paths will prevent any ambiguities.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据