How To Identify The Requested Page In PHP - php

Is there any easy way to identify the file initially handling the request, ignoring get arguments and handling (at least basic) mappings like / to /index.php?
Ideally what I'm looking for is something like $_SERVER['REQUEST_URI'], except it returns the same value regardless of the get arguments and that value is the file requested, not the URI, nor the currently executing file ($_SERVER['PHP_SELF']). In other words, a $_SERVER['REQUESTED_FILE'] or something. I haven't seen anything like that. Does it exist, or do I need to write something manually?
Update
Here are some example URLs paired with what I would like the result to be:
example.com/mypage.php : /mypage.php
example.com/ : /index.php
example.com/foo/?hello=world : /foo/index.php
And these return values are true even in included files. See my answer below before answering, I think I've found what I was looking for.

I decided to test it out myself. The $_SERVER['SCRIPT_NAME'] variable serves up the path to the requested file, even if it's an index file, and without get parameters or anything else. The PHP documentation states this contains the path of the file, but it seems to be relative to the document root, just like PHP_SELF, but without the security vulnerability.
Here is the code I used to test this: https://gist.github.com/dimo414/5484870
The output when requesting example.com/?foo=bar:
__FILE__: /var/www/index.php
PHP_SELF: /index.php
SCRIPT_NAME: /index.php
REQUEST_URI: /?foo=bar
parse_url(REQUEST_URI): /
__FILE__: /var/www/pathtest.php
PHP_SELF: /index.php
SCRIPT_NAME: /index.php
REQUEST_URI: /?foo=bar
parse_url(REQUEST_URI): /
And the output when requesting example.com/index.php/<strong>XSS</strong>:
__FILE__: /var/www/index.php
PHP_SELF: /index.php/XSS # note the XSS exploit (this is bold in browser)
SCRIPT_NAME: /index.php # No exploit here
REQUEST_URI: /index.php/%3Cstrong%3EXSS%3C/strong%3E
parse_url(REQUEST_URI): /index.php/%3Cstrong%3EXSS%3C/strong%3E
__FILE__: /var/www/pathtest.php
PHP_SELF: /index.php/XSS
SCRIPT_NAME: /index.php
REQUEST_URI: /index.php/%3Cstrong%3EXSS%3C/strong%3E
parse_url(REQUEST_URI): /index.php/%3Cstrong%3EXSS%3C/strong%3E
As you can see, $_SERVER['SCRIPT_NAME'] always gives back the file that originally handled the request, i.e. the file in the URL, without any XSS risks.

$_SERVER['PHP_SELF']
Should return the actual script. But there are various methods.
I had a better link to a matrix of all the various file-related environment variables but I can't find it. I'll edit if it turns up.
Edit: I found a nice SO thread that details the differences between them.

Go get file name from the requested URL use following code.
basename($_SERVER['URL']);
basename($_SERVER['REQUEST_URI']);
basename($_SERVER['SCRIPT_NAME']);
basename($_SERVER['SCRIPT_FILENAME']);
basename($_SERVER['REQUEST_URI']);
basename($_SERVER['PATH_TRANSLATED']);
basename($_SERVER['PHP_SELF']);
use any one all all of those in the nested if condition so you will not miss file name any how.

parse_url($_SERVER['REQUEST_URI']) and then pathinfo($path) to get requested filename
$_SERVER['PHP_SELF'] to get real filename
$_SERVER['SCRIPT_NAME'] to get real filename

Its very old question and not very clear too.
What I understood is that you want to know which page is sending request GET/POST. This can be implemented by:
$_SERVER['HTTP_REFERER']
Now, to get the actual page name, write like:
= basename($_SERVER['HTTP_REFERER']);
This will solve you concern.

Related

How to get value after / in URL

I am trying to get the value after the / in a URL in PHP.
I have tried using $_GET['va'], but this only works for the following,
http://localhost:8080/default?va=xxx
What I'm trying to get is this,
http://localhost:8080/default/xxx
How do I get the xxx value after a / in PHP.
Any help is greatly appreciated.
Edit
Thanks to everyone who answered, I wasn't very clear in stating what I wanted. It appears what I was looking for is known as a pretty URL or a clean URL.
I solved this by following Pedro Amaral Couto's answer.
Here is what I did;
I modified my .htaccess file on my Apache server, and added the following code.
RewriteEngine On
RewriteRule ^([a-zA-Z0-9]+)$ default.php?page=$1
RewriteRule ^([a-zA-Z0-9]+)/$ default.php?page=$1
Then I modified my default.php file to GET ['page']
<?php
echo $_GET['page'];
?>
And it returned the value after the "/".
You want to make what is called "pretty URLs" (and other names).
You need to configure the HTTP server appropriately, otherwise you'll get a 404 error. If you're using Apache, that means you may configure .htaccess with RewriteEngine module activated. You also need to add regular expressions.
There's already a question in StackOverflow concerning that subject:
Pretty URLs with .htaccess
Here are another relevant articles that may help:
http://www.desiquintans.com/cleanurls
https://medium.com/#ArthurFinkler/friendly-urls-for-static-php-files-using-htaccess-3264e7622373
You can see how it's done in Wordpress:
https://codex.wordpress.org/Using_Permalinks#Where.27s_my_.htaccess_file.3F
If you follow those, you won't need to change the PHP code, you may use $_GET to retrieve "xxx".
You are looking for: $_SERVER['REQUEST_URI']
The URI which was given in order to access this page; for instance, '/index.html'.
basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
So the $_GET global variable is for parsing the query string.
What you're looking for is the $_SERVER['REQUEST_URI'] global variable:
$url = $_SERVER['REQUEST_URI'];
$url will now contain the full URL of your path. You'll need to use explode('/', $url) to break up that full URL into an array of little strings and parse it from there.
Example:
$pieces = explode('/', $url);
// this will get you the first string value after / in your URL
echo $pieces[0];
You can do in 2 ways.
1- do these steps
Get URL
Explode by /
Get Last element of array
2- Add .htaccess and map that value for some variable
RewriteRule ^default/(.*) page.php?variable=$1
and you can get $_GET['variable']

PHP redirect to another website

I have a directory named "goto" and a file inside called index.php. Currently the following is inside the index.php file:
<?php
$url = $_GET['url'];
header("Location: $url");
?>
At the moment to redirect to another URL I have to type this into the address bar:
http://mysite.com/goto/?url=http://google.com
I would appreciate it if you could tell me how I could change that URL so that I could redirect the user to a website by typing this into the address bar:
http://mysite.com/goto/http://google.com
Use mod_rewrite and .htaccess to rewrite http://mysite.com/goto/http://google.com as http://mysite.com/goto/?url=http://google.com
RewriteEngine On
RewriteRule ^goto/(.+)$ /goto/?url=$1 [L]
Depending on your server configuration you may need to include a / in your rewrite path (i.e., ^/goto/(.+)$).
Unless you want to become a malware hub, I would wholeheartedly recommend you not doing this.
If you wish to allow redirect in such a manner, using http://mysite.com/goto/google and then work out the domain from a whitelist of available, allowed, destinations.
You will need to parse the data which could be a little tricky because you have to differentiate the difference between your URL and the other URL.
My suggestion is to not do so because the second that header is launched you will not see the url and it be better for you to just pass it as a get statement or a post.
EDIT
If you're determined then parse_url() is what you want. :)
#ide's method would work ... but you could also have the PHP script examine $_SERVER['PATH_INFO'], which is how that part of the URL would get passed to the CGI script.
(although, if there's a question mark in there, you'll also have to either make sure it's URI encoded, or also get the QUERY_STRING; you'll also lose any part after a hash, but you'd have the same problem with your current scheme)

Accessing the rewritten URI in a php script

So I have a .htaccess file which is performing a rewrite from /testscript1.php/testvar1/testvar2 to
/testscript2.php/testvar3/testvar4
(this is an over simplification but you get the idea).
Now though in my testscript2.php script when i access the $_SERVER['REQUEST_URI'] variable i see /testscript1.php/testvar1/testvar2 rather than /testscript2.php/testvar3/testvar4 which is what I am looking for. i.e $_SERVER['REQUEST_URI'] contains the uri before the rewrite.
My question is simply, is there a way to access the rewritten uri?
Try using phpinfo() to get a view on what $_SERVER looks like on a rewritten page. Apache supplies quite a lot of info that may be useful.
On my test server, I get the following which may help you:
$_SERVER["REDIRECT_QUERY_STRING"]
$_SERVER["REDIRECT_URL"]
$_SERVER["QUERY_STRING"]
$_SERVER["REQUEST_URI"]
$_SERVER["SCRIPT_NAME"]
$_SERVER["PHP_SELF"]
I would expect that at least one or a combination of those should be able to reliably give you the information you're looking for.
Cheers.
If you’re using the path info to pass an additional path, you can strip that suffix from PHP_SELF:
substr(parse_url($_SERVER['PHP_SELF'], PHP_URL_PATH), -strlen($_SERVER['PATH_INFO']))
Or simply use SCRIPT_NAME since PHP_SELF = SCRIPT_NAME + PATH_INFO. Just take a look at the various values in $_SEVER.

Use .htaccess to change the url PHP sees

I want to use htaccess to not only choose the script that processes the request, but also to change the request uri as php sees it. Can this be done?
For example:
RewriteRule /funstuff/ funstuff.php
...How can I change that RewriteRule or otherwise change my .htaccess file to get funstuff.php to think that the original request url was actually http://www.example.com/funstuff.php and not http://www.example.com/funstuff/?
The best I can see is
$_SERVER["SCRIPT_NAME"] or $_SERVER["PHP_SELF"]
(Both should be fine)
in conjunction with
$_SERVER["QUERY_STRING"]
to get the full request. There seems to be no ready-made REQUEST_URI for this.

Return current web path in PHP

Currently developing a PHP framework and have ran into my first problem. I need to be able to drop the framework into any folder on a server, no matter how many folders deep, and need to find that directory to use as a base URL.
For example, it currently works if I put the framework in the root of the server (http://cms.dev/), but if I were to put it in http://cms.dev/folder/ it does not work.
There are four existing answers, but they all seem to deal with file paths, and you're asking about a base URL for web requests.
Given any web request, you get a bunch of keys in $_SERVER that may be helpful. For example, in your mock example, you might have the following:
http://cms.dev/folder/ — $_SERVER['REQUEST_URI'] == /folder/
http://cms.dev/folder/index.php — $_SERVER['REQUEST_URI'] == /folder/index.php
http://cms.dev/folder/index.php/some/pathinfo — $_SERVER['REQUEST_URI'] == /folder/index.php/some/pathinfo
http://cms.dev/folder/some/modrewrite — $_SERVER['REQUEST_URI'] == /folder/some/modrewrite
Thinking critically, how would you pull out the base URL for any given subrequest? In certain cases you can look at $_SERVER['REQUEST_URI'] and strip off trailing elements if you know how deep in your hierarchy the request is. (For example, if your script is two folders deep, strip off the last two path elements.) When PATH_INFO or mod_rewrite are in use, things become less clear: as longer and longer URLs are provided, there is no clear indication where the paths end and the dynamic URL begins.
This is why WordPress, MediaWiki, phpBB, phpMyAdmin, and every application I've ever written has the user manually specify a base URL as part of the application configuration.
__FILE__ is a magic constant that returns the entire path of the current script. Combine with dirname and add ".." appropriately. It's more reliable than getcwd, since it cannot change during execution.
You can then strip off the web root, to get the relative path to your script (should map to URL). There are many $_SERVER variables that have this information. I suggest using the file system to determine:
If your script is publicly accessible?
At which depth / URL prefix?
Then combine with your base URL. If your script's path ==
/home/public/foo_1/script.php
... and your $_SERVER['DOCUMENT_ROOT'] ==
/home/public
Then you can rewrite your URL as /foo_1/script.php. You don't need the fully qualified URL, unless you want it. This technique works best if you execute it from a central location, like an autoloader.
In order to make urls work check the base tag:
<base href="http://cms.dev/folder/" />
If the PHP file paths are the issue go with Pestilance's advice:
dirname(__FILE__) // returns the directory of current file
Theres a bunch of useful stuff available for things like this in the $_SERVER array. Do a var_dump($_SERVER); to see which element(s) of the array you need.
dirname(__FILE__);
basename(__FILE__);
print_r($_SERVER);
pathinfo('www/htdocs/index.html');
realpath('../../dir1/');
parse_url('http://username:password#hostname/path?arg=value#anchor');
What you are looking for is the WEBROOT of your application based on your description. The checked answer is, by far, the closest answer.
The easiest way to identify the webroot is to have it be user defined, as was mentioned by Annika and noted in a comment.
However, there is a bit of information that was overlooked:
If you are trying to identify the location of the webroot, which coincidentally is also the top level of your framework, then you could use something like this:
$web_only_path = dirname($_SERVER['PHP_SELF']);
This will only work if your rewrite conditions are implemented correctly.
If they are in an htaccess file, no sweat.
However, if they are in an apache conf file. Then they must be contained within a container for the SERVER variable to store and return the proper information after working through the redirects when dealing with the SEO friendly URLs.
See:SCRIPT_NAME and PHP_SELF with mod_rewrite in .conf
To get the current path of the file you must use:
$path=getcwd();
This will return you if in windows for example C:\blah\blah\blah with no file name.
Sounds like you are looking for the relative path.
$_SERVER['SCRIPT_FILENAME']
should do the trick. The php.net site has good documentation on what is available to that http://php.net/manual/en/reserved.variables.server.php
Also, if you are ever curious about what else is there, and what the values are
<?php print_r($_SERVER); ?>
will tell you more that you thought you could know.
function GetCurrentWebDir() {
$CurrentPath = substr(
$_SERVER['SCRIPT_URL'], 0,
strlen($_SERVER['SCRIPT_URL']) - strlen(
strrchr($_SERVER['SCRIPT_URL'], "\\")
)
);
$CurrentFileName = basename(__FILE__);
return substr_replace(
$CurrentPath, '', -strlen($CurrentFileName),
strlen($CurrentFileName)
);
}
echo 'current dir:'.GetCurrentWebDir();`
cp:/apps/PHP/testtesttesttesttesttesttesttesttesttesttest.php
fn:testtesttesttesttesttesttesttesttesttesttest.php
len:48
current dir:/apps/PHP/
Use dirname(__PATH__) to fetch the parent directory path.

Categories