duangang1991 2016-03-20 12:20
浏览 104
已采纳

PHP require在根文件夹中不起作用

I am using this to require a file when the user clicks the submit button on the form. This code is locaded in blog.php. When I have this file in the folder /includes/, the code works perfectly, but I want this file to be in the root folder. When I add it in the root folder, I get this error:

Warning: require(../includes/addbloguser.php): failed to open stream: No such file or directory in C:\xampp\htdocs\Pentaslash\blog.php on line 27

Fatal error: require(): Failed opening required '../includes/addbloguser.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\test\blog.php on line 27

<?php
    if(isset($_POST["submit"])){

      require '../includes/addbloguser.php';
    }
?> 
  • 写回答

2条回答 默认 最新

  • dongyouzhui1969 2016-03-20 12:59
    关注

    This is a problem induced by using relative filepaths. Your relative filepath worked while the file blog.php was in the folder includes because with ../ you were going one directory up (to your root directory) and then back inside includes. But since you moved the file one directory up (to your root directory) you are going with ../ one directory up, outside of your root directory and then try to go into the folder includes, but the folder doesn't exist in the directory above of your root directory (well, if you have luck it does, but the file doesn't exist or it does but the wrong one).

    To prevent this you should always use absolute filepaths, that way you can move blog.php everywhere as long as your file addbloguser.php stays in the same location.

    A easy way to get the absolute filepath to your project is to define a constant which evaluates to dirname(__FILE__)) in a global file in your project's root directory. That way you can always use the constant to do things with files and prevent to modify files to correct relative filepaths if you change something.

    E.g. global.php is inside your root directory, then you will just write this

    define('IN_DIR', dirname(__FILE__)); //__FILE__ is a magic constant and includes the absolute filepath to the current file -> global.php
    

    And if you now include in blog.php said file global.php (or the other way around) you can use for your filepaths the defined constant and it will look like this

    require IN_DIR.'/path/to/file.php'
    

    In this case that would be

    require IN_DIR.'/includes/addbloguser.php'
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改