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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化