Might be an easy question for you, but I'm breaking my head over this one.
I have a php file that needs to know it's current directory url to be able to link to something relative to itself.
For example, currently I know to get the current directory path instead of the url. When I use this I get the path:
realpath(__DIR__)
result:
/Applications/MAMP/htdocs/mysite/dir1/dir2/dir3
But this would be my desired result:
http://localhost:8888/dir1/dir2/dir3
Note that this is not the location of the current page. The page calls a file from "http://localhost:8888/dir1/dir2/dir3/myfile.php"
And "myfile.php" has the script from above.
-- edit to elaborate more details --
Thanks for your answers. But I get that I need to add more detail.
http://localhost:8888/index.php calls: "http://localhost:8888/dir1/dir2/dir3/myfile.php"
"myfile.php" needs to know it's place in the universe :) "Where am I"
"myfile.php" should know it's url location is "http://localhost:8888/dir1/dir2/dir3/"
Use echo $_SERVER['PHP_SELF'];
For example if the URL is http://localhost/~andy/test.php
The output would be:
/~andy/test.php
That's enough to generate a relative URL.
If you want the directory your current script is running in - without the filename - use:
echo dirname($_SERVER['PHP_SELF']);
In the case above that will give you /~andy (without test.php at the end). See http://php.net/manual/en/function.dirname.php
Please note that echo getcwd(); is not what you want, based on your question. That gives you the location on the filesystem/server (not the URL) that your script is running from. The directory the script is located in on the servers filesystem, and the URL, are 2 completely different things.
There is also a function to parse URL's built in to PHP: http://php.net/manual/en/function.parse-url.php
If your URL is like this: https://localhost.com/this/is/a/url
$_SERVER['DOCUMENT_ROOT'] - gives system path [/var/www/html/this/is/a/url]
$_SERVER['PHP_SELF'] - gives the route of the current file (after the domain name) [/this/is/a/url]
$_SERVER['SERVER_NAME'] - gives the domain name [localhost.com]
$_SERVER['HTTP_REFERER'] - gives the correct HTTP(S) protocol and domain name. [https://localhost.com]
If you would like to get the full url, you can do something like:
echo $_SERVER['HTTP_REFERER'] . $_SERVER['PHP_SELF'];
However, I do believe in this case, that all you need is the relative path.. and in that case you should only need to use $_SERVER['PHP_SELF'];
I've found a solution here:
https://stackoverflow.com/a/1240574/7295693
This is the code I'll now be useing:
function get_current_file_url($Protocol='http://') {
return $Protocol.$_SERVER['HTTP_HOST'].str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(__DIR__));
}
Based on your question, I believe this will get you what your want:
$_SERVER['HTTP_HOST'] . substr($_SERVER['REQUEST_URI'], 0, strrpos($_SERVER['REQUEST_URI'], "/"));
Reference:
$_SERVER['HTTP_HOST'] - In your case this would return: http://localhost:8888
$_SERVER['REQUEST_URI'] - In your case this would return: /dir1/dir2/dir3/myfile.php
With the added substr() and strrpos() methods, you can strip the _myfile.php` off of the end to get the desired result:
http://localhost:8888/dir1/dir2/dir3
Related
I must not be phrasing this question right because I couldn't find an answer to this but surely it's been asked before. How do I get the current filename from a URL if it's the directory's index file?
I.e. This will get index.html if I'm on www.example.com/index.html
$url = basename($_SERVER['REQUEST_URI']);
But that won't work if i'm on www.example.com. The only thing I've come up with so far is something like this:
$url = basename($_SERVER['REQUEST_URI']);
if($url == "") {
$filename = "index.html";
}
But that's obviously a bad solution because I may actually be on index.htm or index.php. Is there a way to determine this accurately?
$_SERVER['SCRIPT_FILENAME'] will determine the full path of the currently executing PHP file. And $_SERVER['SCRIPT_NAME'] returns just the file name.
This is one of the other methods.
$url = basename($_SERVER['REQUEST_URI']);
$urlArray = explode("/",$url));
$urlArray = array_reverse($urlArray);
echo $urlArray[0];
Unfortunately, the $_SERVER array entries may not always be available by your server. Some may be omitted, some not. With a little testing though, you can easily find out what your server will output for these entries. On my servers (usually Apache) I find that $_SERVER['DOCUMENT_ROOT'] usually gets me the base of the URI I'm after. This also works well for me in the production environment I work on (XAMPP). As my URI will have a localhost root. I have seen people encourage DOCUMENT_ROOT before in this situation. You can read all about the $_SERVER array here.
In this example, I get the following results:
echo $_SERVER['DOCUMENT_ROOT'] ; // outputs http://example.com
If you are working in a production environment this is very helpful because you won't have to modify your URL's when you go live:
echo $_SERVER['DOCUMENT_ROOT'] ; // outputs C:/xampp/htdocs/example
'DOCUMENT_ROOT' The document root directory under which the current
script is executing, as defined in the server's configuration file.
You could find the last occurrence of the slash / using strrchr() and simply extract the rest using substr(). The optional parameter in substr() tells where to begin. With one we skip the slash /. If you want to keep it, just set the parameter to 0.
echo substr( strrchr( "http://example.com/index.html" , "/" ) , 1 ) ; // outputs index.html
EDIT: Considering that not every server will provide $_SERVER with entities, my approach might be more reliable. That is, if the URL you pass to strrchr() is reliable. In either case, make sure you test the different outputs from $_SERVER, or your paths you provide.
Below are the relevant lines of code:
update.js
$('#tablePlaceholder').load('updateTable.php');
updateTable.php
$path = $_SERVER['REQUEST_URI'];
Normally $_SERVER['REQUEST_URI'] returns the URL, however in this case, the URI at the moment of the request is technically the PHP file, so what is returned is updateTable.php instead of the actual URL. Is there an alternate command I can use to get the URL instead of URI? I have resorted to storing the URL in a session/global variable to retain access to the actual URL in the PHP file, but it seems there must be a better way, though I have not found it. Any tips would be most welcome!
I was looking at the documentation for the jQuery load() command:
http://api.jquery.com/load/
It looks like I might be able to pass the URL as a string via the data argument?
$_SERVER['REQUEST_URI'] is supposed to give path of current script relative to root and not the full url. If you want to get full url path, take a look at the same question on stackoverflow with the solution also being there
Getting the full URL of the current page (PHP)
I use that function to navigate to another page:
define('WEB_ROOT', '/');
function redirect($location)
{
header('Location: ' . WEB_ROOT . $location);
die();
}
And I deliver it the following address:
$lastPageTransfer=$_SERVER["SCRIPT_NAME"]."?threadID=".$threadID."&page=".$pager->MaxPage;
redirect($lastPageTransfer);
It doesnt matter what the get variables are.. what I get is this:
http://politicalforum/Thread/thread.php%20%20%20?threadID=23&page=4
when the navigation completes and I get an error from google saying it cant find the page.
But I do get it to work, if I put the $lastPageTransfer into an attribute of a link
<a href=...:
http://localhost/PoliticalForum/Thread/thread.php%20%20%20%20?page=2&threadID=23
Another thing to ask.. why are the %20 generated adn how can I prevent it?!?
UPDATE:
I get this:
http://localhost/localhost//PoliticalForum/Thread/thread.php?threadID=23&page=5
when I do this:
$lastPageTransfer=$_SERVER['HTTP_HOST']."/".$_SERVER["SCRIPT_NAME"]."?threadID=".$threadID."&page=".$pager->MaxPage;
%20 is an encoded whitespace. You avoid it by not having whitespaces in your links.
Regarding the link I'll take a shot on that you haven't supplied a host name:
http://politicalforum/Thread/thread.php%20%20%20?threadID=23&page=4
^
which could be:
http://www.example.com/politicalforum/Thread/thread.php%20%20%20?threadID=23&page=4
^^^^^^^^^^^^^^^
Were www.example.com should be your host name. In the case were you use it in a link it's included localhost as hostname automagically. The behavior comes from that when using <a href.. you don't need to have full paths.
From the manual:
HTTP/1.1 requires an absolute URI as argument to ยป Location: including
the scheme, hostname and absolute path, but some clients accept
relative URIs. You can usually use $_SERVER['HTTP_HOST'],
$_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a
relative one yourself
This is called URL encoding/escaping. To fix that, you need to unescape the URL.
I was wondering if it is possible to grab the URL from which a page is accessed? For example say if I have a file index.php. It can be accessed from virtually anywhere, depending on where I placed it. For example:
- http://folder1/index.php
- http://nicefolder1/index.php
Is there anyway I can find out where the page was accessed from? I'd like to perhaps parse that URL and if it was from nicefolder1, I'd like to do something like echo "That was a good location to be executed from" :D! Just something I was curious about ...
$_SERVER['PHP_SELF']
Should have the url you want.
More Info
I am not sure if I understand your question, but here's my take on this:
$_SERVER['HTTP_HOST'] holds the host name, and $_SERVER['REQUEST_URI'] the absolute path to the requested resource. These two, combined with a scheme prefix, gives you the complete URL:
$url = 'http://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
Take a look at the $_SERVER reference on php.net, $_SERVER['PHP_SELF'] should do the trick.
This question already has answers here:
Get the full URL in PHP
(27 answers)
Closed 8 years ago.
In PHP, how can I get the URL of the current page? Preferably just the parts after http://domain.example.
$_SERVER['REQUEST_URI']
For more details on what info is available in the $_SERVER array, see the PHP manual page for it.
If you also need the query string (the bit after the ? in a URL), that part is in this variable:
$_SERVER['QUERY_STRING']
If you want just the parts of URL after http://domain.example, try this:
<?php echo $_SERVER['REQUEST_URI']; ?>
If the current URL was http://domain.example/some-slug/some-id, echo will return only /some-slug/some-id.
If you want the full URL, try this:
<?php echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>
$uri = $_SERVER['REQUEST_URI'];
This will give you the requested directory and file name. If you use mod_rewrite, this is extremely useful because it tells you what page the user was looking at.
If you need the actual file name, you might want to try either $_SERVER['PHP_SELF'], the magic constant __FILE__, or $_SERVER['SCRIPT_FILENAME']. The latter 2 give you the complete path (from the root of the server), rather than just the root of your website. They are useful for includes and such.
$_SERVER['PHP_SELF'] gives you the file name relative to the root of the website.
$relative_path = $_SERVER['PHP_SELF'];
$complete_path = __FILE__;
$complete_path = $_SERVER['SCRIPT_FILENAME'];
The other answers are correct. However, a quick note: if you're looking to grab the stuff after the ? in a URI, you should use the $_GET[] array.
You can use $_SERVER['HTTP_REFERER'] this will give you whole URL for example:
suppose you want to get url of site name www.example.com then $_SERVER['HTTP_REFERER'] will give you https://www.example.com