How to retrieve the URL of a page using PHP? - php

Newbie question here, is there any inbuilt PHP tag that can be used to retrieve the URL of a page and echo it on the screen?
Thanks.

Echos the URL of the current page.
$pageURL = (#$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
if ($_SERVER["SERVER_PORT"] != "80")
{
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}
else
{
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
echo $pageURL;

If your web server runs on standard ports (80 for HTTP or 443 for HTTPS) this would work:
getservbyport($_SERVER['SERVER_PORT'], 'tcp') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']

Take a look at the $_Server variable. Specifically you probably want the REQUEST_URI value.

$base_url = _SERVER["HTTP_HOST"];
$url_path = _SERVER["REQUEST_URI"];
echo $base_url.$url_path;
Assuming the requested page was http://sample.org/test.php, you would get:
sample.org/test.php
You would have to add more $_SERVER variables to get the scheme (http://). REQUEST_URI also leaves any GET variables intact, so if the page request was http://sample.org/test.php?stuff=junk, you would get:
sample.org/test.php?stuff=junk
If you wanted that left off, use $_SERVER['PHP_SELF'] instead of REQUEST_URI.
If you want a really easy way to see which global variables are available, create a page with the following:
<?php
phpinfo();
?>
and put that script in any directory you are curious about. Not only will you see all sorts of neat info, you will also see how various factors such as HTTP vs HTTPS, mod_rewrite, and even Apache vs IIS can set some global variables differently or not at all.

Related

The $_GET at # (example.com/#dfsqf) [duplicate]

Is there a way to get the entire URL used to request the current page, including the anchor (the text after the # - I may be using the wrong word), in included pages?
i.e. page foo.php is included in bar.php. If I use your solution in foo.php, I need it to say bar.php?blarg=a#example.
No, I am afraid not, since the hash (the string including the #) never gets passed to the server, it is solely a behavioural property of the browser. The $_SERVER['REQUEST_URI'] variable will contain the rest however.
If you really need to know what the hash is, you will have to use the document.location.hash JavaScript property, which contains the contents of the hash (you could then insert it in a form, or send it to the server with an ajax request).
// find out the domain:
$domain = $_SERVER['HTTP_HOST'];
// find out the path to the current file:
$path = $_SERVER['SCRIPT_NAME'];
// find out the QueryString:
$queryString = $_SERVER['QUERY_STRING'];
// put it all together:
$url = "http://" . $domain . $path . "?" . $queryString;
echo $url;
// An alternative way is to use REQUEST_URI instead of both
// SCRIPT_NAME and QUERY_STRING, if you don't need them seperate:
$url = "http://" . $domain . $_SERVER['REQUEST_URI'];
echo $url;
You can't - you'll have to write the value of the hash to a cookie via Javascript to send it to the server on the subsequent request.
You can pass up the full URL, including the anchor (the part after the #), using a Javascript onload function that sends that URL to an Ajax endpoint.
This example show's full URL request with port or https
function curPageURL() {
$pageURL = 'http';
if(isset($_SERVER["HTTPS"]))
if ($_SERVER["HTTPS"] == "on") {
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
}
return $pageURL;
}
usage : echo curPageURL();
It is true that you can't pass hash data to server. but sometimes what you want is get some url with '#blablabla' from the server, like when you share link to someone with '#', but the site need to login. below is another way to think, maybe not vary detailed.
First, sometimes you want to share your link with '#',like:
www.so.com#lala
First, you can change your url use javascript and pass some data with '?' and '#' at the same time, like:
www.so.com?foo=lala&&flag=hash#lala
then, as the '#' nerver pass to the server, but you can get the data from $_GET[''],like:
if($_GET['flag'] === 'hash'){
// base url
$_SESSION['url'] = strtok('http://'.$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"],"?");
// hash data
$_SESSION['hash'] = $_GET['foo'];
}
then, you can do everything with the '#' data, if you want to pass it to client, you can:
$url = $_SESSION['url']."#".$_SESSION['hash'];
header("Location:".$url);
At last, the url is back
Syntax Error is right.
And what I'd like to do is intercept the #foo from the call dosomething.org/page.php#foo and act as if I'd found a dosomething.org/page.php?x=foo call. Yes, this may function on the client but it's theoretically available at the server.
Why do I want this? Because people have old links stashed in their emails and I want to handle them differently.
You can pass the anchor using rawurlencode funcion.
Basically you just need to do something like this:
bar.php?blarg=a<?php echo rawurlencode('#blahblahblah')?>

Test if a php include is called from a local file

I have a php include with one function in it, I need to ensure that it can only be executed by inclusion within a local file and not from any external source.
What is the best method of testing for this?
-thanks
-sean
UPDATE:
thanks, here is some more info,
- I can't move it outside the webroot, I'm updating an existing site
- testing for REMOTE_ADDR will always return the clients ip
- the only way I want this file called is by: include_once "sendmail.php";
I see two cases of your problem:
File can be accessed over http with any browser. In that case you can define a CONST in your main application and then chek it in includes:
main file:
define('MY_APP', true);
included file:
if (!defined('MY_APP') || MY_APP !== true) {
die('Access denied');
}
File can be accessed via file system (from nearby virtual host for example). Than you can use SERVER_NAME and REQUEST_URI checks.
Forget testing. Just keep the file outside the webroot.
If it can't be served over HTTP then it can't be used externally.
(Although, if it just contains a function, and no statements that execute automatically, then any external request is going to end up with a blank HTTP response unless the server starts serving up PHP files as plain text)
If you always include and execute it from the same file you could make a URL check in your function.
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
//Your included function:
function doSomething() {
if (curPageUrl() == "http://www.yourwebsite.com/function.php") {
... execute code...
}
}
You can use the $_SERVER array to return the IP of the caller.
$callerIP = $_SERVER['SERVER_ADDR'];
You can than check if the $callerIP is localhost.

get URL of parent page inside when inside an iframe

I have an iframe (iframe.php) inside my main page (index.php). I want to echo the URL of the main page inside the iframe. I know how to echo the URL of any page but not when it is inside an iframe. When i try this, it is echoing only the URL of the iframe and not of the main page. It sounds simple but not able to figure it out.
REASON: the reason why i chose php and why i am trying to do this is, i need to verify the URL from which this page is being accessed... do not want the iframe to be accessed unless the user is in index.php and reject the user from accessing it if he is not in the iframe of the main page.
You can use
$_SERVER["HTTP_REFERER"]
to read the parent.
It work for me.
The javascript code can't talk easily with PHP
The ?from=
PHP has no idea about an iframe, it's just served as another page and interpreted by the browser...
You could do something like...
<iframe src="frame.php?from=<?php echo currentPageURL() ?>">
Then inside the iframe, you can access $_GET['from']. Just make sure you verify, as that would be insecure.
Here is the code I typically use to return the current page URL:
function currentPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
Try this in iframe:
<script type="text/javascript">alert(top.location.href);</script>
I think it should work. :-)

PHP External Link Help

Hi I have the following page which sets a cookie with the current URL and also a simple external link.
<?php
function pageURL()
{
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on")
{
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80")
{
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}
else
{
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
$CurrentPage = pageURL();
setcookie('linkback', $CurrentPage);
?>
<p>External Link</p>
What I want to do is using PHP add a prefix to all external links so that they have have the following structure:
localhost/outgoing?url=http://www.google.com/
This loads up an outgoing page like so:
<?php
if(!isset($_GET['url']))
{
header('HTTP/1.0 404 Not Found');
}
?>
<h1>Warning! Now leaving website</h1>
<ul>
<li><a title="Return to Website" href="<?php if(isset($_COOKIE['linkback'])) { echo $_COOKIE['linkback']; } else { echo 'http://localhost:8888/creathive/'; } ?>">Return to Website</a></li>
<li><a title="Continue to <?php echo $_GET['url']; ?>" href="<?php echo $_GET['url']; ?>">Continue to <?php echo $_GET['url']; ?></a></li>
</ul>
The idea is that using the cookie set in the previous page I can have a simple back button, and also grab the url from the query and allow the user to continue after being warned they are leaving the site.
The problems I have are:
1.) Prefixing external URLS so that they go to the outgoing page
2.) The isset on the top of the outgoing page is supposed to be throwing a 404 if a user visits the outgoing page without a url query string but isn't
3.) Need to make sure that URLS are valid so for example prevent this for happening: localhost/outgoing?url=moo
You will need to replace every external URL in your code according to the new scheme. There is no way doing this automaticalle for all outgoing links.
This is because, if the user clicks on an external URL, the request is not sent to your server, but the external one.
Edit:
The only thing you could do is caching all your output with ob_start() and then replace all links using a regexp, before printing them on your page.
But the better solution would be to replace all links yourself.
Can you elaborate?
Isset isnt exactly the "right" tool. try arrya_key_exists('url', $_GET)…. Code like this should do ya.
function haveUrl() {
if (array_key_exists('url', $_GET)) {
$url = $_GET['url'];
if (!empty($url)) return true;
}
return false;
}
You can simply check to see if they start with http:// or https://... This may be done best with a regex…. something like…
function validUrl($url) {
if (preg_match('\^(http:\/\/|https:\/\/)\mi', $url) {
if (preg_match('\localhost\mi', $url) return false;
else return trus;
}
return false;
}
1) I would create a class for all links, and use something like $links->create("http://...")
and there you place the redirection and everything you might need.
3)
You could use the code in the following link:
link text
1.) Prefixing external URLS so that they go to the outgoing page
You need a DOM tool for this. For instance SimpleXML or Simple HTML DOM parser or any of it's kind to manipulate the outgoing links on the page you are rendering. (Find more available options in this question.)
Optimally, you will cache the results of this operation as it can be quite expensive (read: slow) and update the cached version on update or after a defined period of time.
2.) The isset on the top of the outgoing page is supposed to be throwing a 404 if a user visits the outgoing page without a url query string but isn't
Yes it does, but you need to stop execution after this point if you don't want to render the rest of the page. A 404 error can - and should! - have a page body, it's a response like any other HTTP response.
3.) Need to make sure that URLS are valid so for example prevent this for happening: localhost/outgoing?url=moo
Even if you do so - and indeed you should, nothing will prevent anyone from accessing localhost/outgoing?url=foo by manual URL manipulation. Url parameters, or any other user input can never be trusted. In other words you need to check the outgoing url in the outgoing-script no matter what.
And don't forget to sanitize rigourously! Functionality such as this is screaming to be abused.

$_SERVER['REQUEST_URI'] wrong value

I'm using this variable to get the current page URL, like this:
$request = $_SERVER["REQUEST_URI"];
$page = (is_ssl() ? 'https' : 'http').'://';
if ($_SERVER["SERVER_PORT"] != "80")
$page .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$request;
else $page .= $_SERVER["SERVER_NAME"].$request;
The app. I doing this for is public, and the problem is that on some sites (very rare) this variable returns the entire URL, including the domain name, not just the requested page. Is this a server misconfiguration?
It could be somewhere in your code (or 3rd party package) is changing this variable.
You could grep.
grep -r -E '\$_SERVER\[[\'"]?REQUEST_URI[\'"]?\]\s?=[^=]+?'
That regex should find where $_SERVER['REQUEST_URI] is being assigned, and not just used normally or testing for equality, for example. Note too I removed the -i flag because PHP variables are case sensitive and so are array keys.

Categories