0

How do I get the URL of the currently executing PHP script?

For example, the URL http://www.domain.com/folder/script.php sends a request to /var/www/domain/folder/script.php.

In script.php, I want to echo http://www.domain.com/folder/ (not /var/www/domain/folder/, not http://www.domain.com/folder/script.php). What is the simplest way to do this?

3 Answers 3

2

It is not that sophisticated, but here it goes:

<?php
    $scriptFolder = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on')) ? 'https://' : 'http://';
    $scriptFolder .= $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']);
    echo $scriptFolder;
?>
Sign up to request clarification or add additional context in comments.

2 Comments

A better solution might use $_SERVER[’SCRIPT_NAME’] instead of $_SERVER['REQUEST_URI']. And what about "https://"?
@powerboy: did you read the PHP documentation pertaining to $_SERVER? I believe php.net and its comments cover everything you're asking.
2

A simple Google search would have answered your question. Here's the result.

http://php.about.com/od/learnphp/qt/_SERVER_PHP.htm

2 Comments

$_SERVER[’PHP_SELF’], $_SERVER['REQUEST_URI'] and $_SERVER[’SCRIPT_NAME’] return path with script file name instead of the path alone. I want to know if there is a variable set to the path alone.
See solution by Mihai Iorga below. PHP doesn't come with that function out of the box, but with about half a minute of time, you can get the desired functionality. That takes less time than posting on SO.
0

I was looking for an answer for this question, it seems there isn't an easy one.

Then it hit me: it is because it is not always possible to get the current script url.

PHP can include a file anywhere in the file system, as long as the user running the process has access to it, it will work. But then, that means it is possible to include scripts outside the webserver's root directory - hence impossible to have a url. I believe that is the reason there is not straight forward function to do that.

2 Comments

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
Well, it is a question without an answer, and I explain why I think it is the case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.