dongtang5776 2017-05-04 23:48
浏览 26
已采纳

使用本地服务器和普通服务器上的路径

I have a problem. I want to use a localserver (WAMP) and an online server (000webhost) at the same time. Now there is a problem with my file paths. I can not use normal paths like (../contact.php) because I use php include files and then the path will be different because I include the file over the whole site.

Now I wanted to use absolute paths like (/main/includes/header.inc.php) But the root folder on the online server and local server are different, so that won't work too.

Are there any solutions I can use?

Jelmer

  • 写回答

1条回答 默认 最新

  • dongzhi2014 2017-05-04 23:57
    关注

    Set a web root directory constant ROOT that you can use to load your file paths. For each server set this to their path accordingly. Make sure that is loaded at the top of the first file hit for each request.

    <?php
    define('ROOT', `/var/www/html/site`);
    ...
    

    now load your files with the constant

    include ROOT . '/directory/file.php';
    

    Obviously set constant different for each server.

    You could put your define() in an if statement as well.

    <?php
    if($_SERVER['SERVER_NAME'] === 'localhost'){
        define('ROOT','/wamp/dir/'); //obviously not your actual dir
    }else{
        define('ROOT','/online/dir/'); //obviously not your actual dir 
    }
    

    UPDATE

    Better idea might beusing environment variables instead of conts.

    Setting CONST on every page is a bit tedious. I found this post that explains how to set an environment variable in the .htaccess. that way we only need to set it in once place and can access it in all files.

    eg:

    //.htaccess
    SetEnv ROOT /var_www/html/site/
    

    Now I can get this value with this in all my .php files:

    <?php
    include getenv('ROOT'); . '/directory/file.php';
    

    credit:

    store constant variable on server via .htaccess

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?