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

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')?>

Related

php url redirect to home page

Well, I don't know if I made a title properly but I've got a lil php script out there and I am wondering if there might be possibility when user go to this url:
siteurl.com/index.php?token=J55OSGTTk3W7mRcuq54006w7ROv
to get automatically only /index.php without the content that he copy/pasted in this case
?token=J55OSGTTk3W7mRcuq54006w7ROv
Hope it is possible. Cheers.
Yes. Issue a Location header and use parse_url() to get the parts you need.
$url = "http://siteurl.com/index.php?token=J55OSGTTk3W7mRcuq54006w7ROv";
$parsed = parse_url($url);
$redirect = $parsed["scheme"] . "://" . $parsed["host"] . $parsed["path"];
header("Location: $redirect");
Maybe explode($url,"?")[0]. If there's no question mark, then it should return an array of length one. If there is, you'll only get everything before the '?'.

Redirect all GET queries from one site to another

Suppose I want to redirect all GET queries from one site to another, using PHP.
POST queries do not exist in the system.
For example, when the user connects to
www.mysite.com/index.php?action=myAction&pageno=2
I want him to be redirected to:
www.mySecondSite.com/index.php?action=myAction&pageno=2
I can get write a hard-coded code for each and every possible $_GET variable (myAction and pageno in my example), but it does not sound like a reasonable solution. Also, I've seen this solution which involves modifying the configuration of the Apache server. Suppose I can't change the server configuration.
For sure, there must be a way to get all of the variables and their values, and redirect it to another site.
First of all you need to get complete URL, for example for my local server:
http://localhost/server_var.php?foo=bar&second=something
Try printing $_SERVER variable with print_r():
print_r( $_SERVER);
You should get result like this:
Array
(
...
[REQUEST_URI] => /server_var.php?foo=bar&second=something
...
)
For more info take a look at manual page, so now you have your URL:
$url = 'http://www.mySecondSite.com' . $_SERVER['REQUEST_URI'];
And you can use header() to redirect your request:
header( 'Location: ' . $url);
I recommend taking look at HTTP status codes, 3xx ones, whether you want to use 302 Found (the default) or 307 Temporary Redirect...
The second special case is the "Location:" header. Not only does it
send this header back to the browser, but it also returns a REDIRECT
(302) status code to the browser unless the 201 or a 3xx status code
has already been set.
So you can do this:
header('HTTP/1.0 307 Temporary Redirect');
header( 'Location: ' . $url);
Write this php code at the top of the index.php page before your html tag.
<?
$newUrl = "www.mySecondSite.com/index.php";
if (!empty($_GET)){
$parameter = $_GET;
$firstTime = true;
foreach($parameter as $param => $value){
if ($firstTime) {
$newUrl .= "?" . $param . "=" . $value;
$firstTime = false;
} else {
$newUrl .= "&" . $param . "=" . $value;
}
}
}
header("Location: ".$newUrl);
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
Redirecting in .htaccess would be the way to go, but if you say you can't change that you can insert a conditional header with a 301 code in your index.php file:
http://php.net/manual/en/function.header.php
You have the contents of the query string available in $_SERVER['QUERY_STRING']

Better way to do this in PHP

I currently have my htaccess file set to remove the file type so
www.example.com/home.php
would become,
www.example.com/home
I need to compare the url with one that I have saved in the database, I do this by,
if ($_SERVER['QUERY_STRING']) {
$pageURL = str_replace('.php', '?', 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'] . $_SERVER['QUERY_STRING']);
}
else {
$pageURL = substr('http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'], 0, -4);
}
When I save the url in the database it gets saved as the current page url after the htaccess file has removed the .php, it is inserted using jquery ajax.
When I come to compare it, I need this to make it match in php as php doesn't take into account the htaccess changes.
Is there a better way to do this?
You can do:
$pageURL = rtrim($_SERVER['REQUEST_URI'], '.php');
This would give your url with .php removed whenever it appears at the end of the url.
Look into the parse_url() function. You can use it to parse the URL into parts then modify the path component (e.g. remove .php). Then you can rebuild the URL from those parts using the http_build_url() function.
Seems to me that combining John's suggestion above of using parse_url() along with using pathinfo() would be best -- trimming, truncation with substr, etc. isn't always as elegant as pathinfo().

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.

How to retrieve the URL of a page using 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.

Categories