phpglobal-variablesserver-variables

How to use the path from $_SERVER variable, modify it and assign it to some variable in PHP?


As we know $_SERVER array is wriiten by web server and it's not a good practice to make any change in it. Now the scenario is I'm using this $_SERVER array in my project and I want to temporarily change the value of one of array elements of $_SERVER array. I want to assign this temporarilychanged value to some variable say $redirection_path. How to do this? Following is the array element I have after printing the $_SERVER array:

Array
(
  [SCRIPT_NAME] => /my-project-folder/web/control/login.php
)

Now I want to take the path value from above array and change it to following value:

$redirection_path = /my-project-folder/web/control/modules/bakery/cake.php

But while doing this the actual $_SERVER array should not get affected. How should I do this in an optimum manner? Thanks in advance.


Solution

  • Use dirname to extract the parent path of $_SERVER['SCRIPT_NAME'] and append your new subpath to it.

    $redirection_path = dirname($_SERVER['SCRIPT_NAME']).'/modules/bakery/cake.php';