-1

I have a php script that contains login and logout links that i want to use in my whole website. The intention is to have a variable that contains the URL that can be used through the entire site and never changes with the current page location

Using $_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']) i get:

localhost/~MyName/MySite/current_folder

and it changes depending on the current location

Using __DIR__ i get:

/Users/MyName/Sites/MySite/php

Where "php" is the folder that contains the script

What i'm searching is:

localhost/~MyName/MySite/php

Where i'm in local, and:

https://www mysite com/php

Where i'm on the internet

I want the path to be stored in a variable and used in the script:

<?php
   echo ("<a href= '$path . /logout.php'> Logout </a>");
?>
F.T.
  • 3
  • 1
  • 6
  • you want the path or the url? Two different animals. And what's wrong with the first attempt? – Jeff Oct 12 '18 at 17:22
  • i need a string to put in Logout The first attempt gives me the current dir not the dir of my php folder – F.T. Oct 12 '18 at 17:26
  • and the php folder is what? The doc root? Or is localhost your doc root? – Jeff Oct 12 '18 at 17:33
  • I think you should just set the virtual host to `localhost/~MyName/MySite/` and go with `$_SERVER['SERVER_NAME'] . "/php"` – Jeff Oct 12 '18 at 17:34
  • the php folder is in my root (root/php) and contains the script – F.T. Oct 12 '18 at 17:36
  • if it was the root, then `$_SERVER['REQUEST_URI']` would not include `~MyName/MySite/` – Jeff Oct 12 '18 at 17:59
  • Possible duplicate of [Get the full URL in PHP](https://stackoverflow.com/questions/6768793/get-the-full-url-in-php) – miken32 Oct 12 '18 at 18:04

1 Answers1

0

place in your webroot index.php file at the top

define('URL', filter_var(rtrim('http'.(((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443) ? 's' : '').'://'.$_SERVER['SERVER_NAME'].str_replace('\\', '/', dirname($_SERVER['PHP_SELF'])), '/').'/', FILTER_SANITIZE_URL));

in an MVC setup, this will allow URL to always equal your web root.

Chad
  • 1,139
  • 17
  • 41
  • Note that `$_SERVER['SERVER_NAME']` is based on user-supplied data so can't always be trusted. `$_SERVER['PHP_SELF']` is subject to XSS attacks, though in this context the risk is limited. – miken32 Oct 12 '18 at 18:19
  • The $_SESSION method that you give me works for me.. However if someone accesses my site from another page all links doesn't work. – F.T. Oct 12 '18 at 18:56