I want to print out the current URL path, but my code doesn't work propperly.
I use this in my file.php
echo "http://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];
When i open the url http://sub.mydomain.com/file.php it seems to work fine, and it prints "http://sub.mydomain.com/file.php"
But if i remove the .php extension so the url will be http://sub.mydomain.com/file instead, it prints "http://sub.mydomain.com/sub/file.php"
which is wrong.
It prints the subdomain twice, and I don't know why?
In my .htaccess file, I have a rewrite that makes it possible to removes .php extensions.
Anyone who can/want to help me please? :)
You need
$_SERVER['REQUEST_URI']
instead of$_SERVER['SCRIPT_NAME']
, cos$_SERVER['SCRIPT_NAME']
will always give you the file which is working at the moment.From manual:
I suppose this helps you getting current URL fully.
Notice: DO NOT RELY ON CLIENT'S
HTTP_HOST
, USESERVER_NAME
INSTEAD! SEE: What is the difference between HTTP_HOST and SERVER_NAME in PHP?Security Warning
You need to filter (sanitize)
$_SERVER['REQUEST_URI']
if you use it in anywhere (to print or store in database), cos it's not safe.Hence, always filter user inputs before using them. At least use
htmlspecialchars
,htmlentities
,strip_tags
etc..Or something like this;