search

Home  >  Q&A  >  body text

Tips to simplify single-file relative path management

<p>How to manage relative paths in a project from a single file, since editing or updating is cumbersome and I would like to have a separate file to handle it. </p> <pre class="brush:php;toolbar:false;">//Redirect to home page if role is user, otherwise redirect to admin dashboard if ($_SESSION['role'] === 'user') { header('location: ./../../index.php'); // this } else { header('location: ./../../admin/index.php'); // this }</pre> <p>Manage paths to a single file for the entire project</p>
P粉649990163P粉649990163478 days ago549

reply all(1)I'll reply

  • P粉340264283

    P粉3402642832023-08-10 10:54:24

    For example, create a new file and name it config.php (or any other name you like) and write these lines in it as follows:

    <?php
      //`__DIR__` 是一个代表当前脚本所在目录的魔术常量
      //根据您的项目结构,调整路径拼接(`BASE_PATH .`)。
        
       define('BASE_PATH', __DIR__ . '/');
    ?>

    Now you can easily include config.php in any file that needs to use the base path!

    <?php
        require_once 'config.php';
    
        if ($_SESSION['role'] === 'user') {
            header('location: ' . BASE_PATH . 'index.php');
        } else {
            header('location: ' . BASE_PATH . 'admin/index.php');
        }
    ?>

    reply
    0
  • Cancelreply