How to create a redirect? - php

How do I create a php which redirects with use of the URL. I.e. - Redirect-To.com/Change.php?=Google.com Then goes to google etc
I'm wanting to create a php page where a user goes to
Redirect-To.com/Change.php?=Google.com
or
Redirect-To.com/Change.php?=Youtube.com
or
Redirect-To.com/Change.php?=Yahoo.com
Then the visited page redirects to Google or whatever page is after ?=

This is basically what URL shorteners do, except they lookup the destination from a database and probably store some tracking information.
Check out the header function that lets you set HTTP headers. You want to set a 302 redirect, which means moved temporarily, and a Location header to set the new location.
http://php.net/manual/en/function.header.php
header('HTTP/1.1 302 Moved Temporarily');
header('Location: ' . $newLocation');
301 is another common redirect code, but it means "Moved Permanently" and a lot of browsers will cache that status and not hit your website if the person clicks your link again.
The HTTP spec says you should give the full URL with the redirect, though most browsers will work without it.
You may also want to white list destinations; a user might follow a link to your site and be redirected to a site owned by a a malicious third party. Thinking they were in the confines of your site, they may enter information or perform actions allowing the third party to gain access to their data.

In the URL, values without keys will be ignored, so you should write:
...change.php/?redirect=http://www.google.com
Then you can access the "redirect to" address with $_GET['redirect'].
To redirect to a given address, you can use to Location header (make sure nothing is sent to the output before calling the function):
header('Location: ' . $_GET['redirect']);
You have to start the redirecting URL with "http(s)://" like I wrote above.
If you want to stop the script (as it does not stop immediately after the redirect function), you have to call the die() or the exit() function.
(If a shorter URL is better for you, the URL can be just ...change.php/?http://www.google.com, then you can access the address with $_SERVER['QUERY_STRING'].)

Related

How can I redirect a user to a www domain in PHP without the http?

I have a website (let's call it www.mywebsite.com) that allows users to enter a URL that other users on my website can be redirected to. If a user types in a full URL like so https://www.google.com then all is well because my header() function will redirect to exactly that.
However when a user enters in www.google.com or even google.com then the header() function will attempt to redirect to this https://www.mywebsite.com/www.google.com.
Remember, I can't fully format the user's URL myself because the program doesn't know whether the website is https:// or http:// and if you get this wrong the user can end up at a non existent page.
What I need is a method of telling PHP to just go to the URL specified without relativity to my website almost like the a user had typed it in the URL bar themselves.
Any ideas?
You should only redirect to the http:// if you don't know the protocol because it is REALLY the responsibility of the receiving website to have a redirect setup form HTTP to HTTPS.
Therefore if the user doesn't specify a protocol, you simply add the non-secure http protocol and it should get redirected to the correct page.
You should not be inserting www at all if the user hasn't put that in.
Notwithstanding all this, you could always perform a check yourself in your own code to see which protocols exist at the other end, but you should probably simple enforce the user supply it in the first place

PHP Header Location Breaking Google Analytics Goal?

Our website is currently using Google Universal Analytics to track goal conversions from our own private domain and a 3rd party payment processor. Currently our goal flow is:
/cart -> /checkout -> /receipt
On the /cart page which resides on our private domain, the user clicks "checkout". When they do, it goes to /precheckout which is a preprocessing script which finishes with header("Location: external.com/checkout"); exit;
Our suspicions lead us to believe that it's this intermediary page that is breaking our funnel. From what I understand, when header("Location: "); is used and no data is sent to the browser, that it should simply follow the redirect. What is happening?
I'm willing to bet that the server changing the location is causing the browser to not send the "Referer" header.
Try header('Referer: /cart'); in the /checkout.
Since the user is not clicking on anything in between precheckout and checkout, you need to manually set it. If the user isn't always going to be clicking that link to get to the checkout page (i.e. bookmarking it), it may be better to set a session variable to determine if they just came from the cart and if they did use the header code above.
The 301 redirect is the preferred way to redirect URLs, since it informs search engines that the URL has moved for good, and search engines should put the new URL page in the search results instead of the old URL page and transfer the new URL page, the page rank of the old URL page.
The 301 redirect can be done across domains or on the same domain.
Google ""analytics"" recommends to use 301 redirect.
<?php
// PHP permanent URL redirection
header("Location: http://www.example.com/new-page.php", true, 301);
exit();
?>
https://www.rapidtables.com/web/dev/url-redirect.html

PHP redirect with Range (byte-serving) passthrough

I have some PHP code which frequently serves page redirects to clients via the header('Location: x') function. The header redirect works fine; I have no output before the Header function, and the user is successfully redirected to the new page. Some of the clients that connect have HTTP byte range requests tied to them, with the intent to only grab a certain portion of the requesting file that I redirect to.
I need to preserve this range request when sending to the new site; the site I redirect to should also see the range info in their headers, and be able to correctly process the user's request.
I understand that I can see the byte range that they're requesting in my PHP code by looking at $_SERVER['HTTP_RANGE'], but I'm unable to think of a way to pass this range to the redirecting site in their headers. I'm pretty sure trying to implement via the header function is wrong, since it will set the headers of my own page. Instead, I need to be able to set the headers that are sent to the page that I'm redirecting to.
Does anybody have any ideas on how to implement this?
If you don't actually need to redirect the user to another site, but just need to give them content from another site, you might want to use cURL functions to where you can set the Content-Range header on the request, get the result, and then serve it up to the end user.

PHP 301 Redirect - collect referrer

I'm doing a 301 redirect on site A to site B - when the user arrives at site B it needs to find the page the user came from. This doesn't seem to be working though:
$_SERVER['HTTP_REFERER']
whereas if I do a link to the page
go
I get the referrer through. Is there a reason it doesn't come through after the redirect? If so can anyone offer any advice on how to do this. I want to avoid at all costs having a query string on the redirect.
Is there maybe another header I need to send with the page that redirects?
Thanks for any advice!
The thing is, the HTTP_REFERER is site A. That's just how a 301 works.
That said, the easy way to do this is to take the url of the referrer to site A onto the end of site B's URL as a variable. Then, at site B, any time you have a referral from site A, you can have it.
<?php
header("Location: http://site-b.com/?ref="
.urlencode($_SERVER['HTTP_REFERER']),TRUE,301);
?>
Then of course at site B, access urldecode($_GET['ref']) for your referrer.
However... if you're looking to avoid _GET variables, you have a few options.
A) Collect the _GET request, then re-munge the URL -- IE have site B redirect to a "clean" version of itself.
B) Have your redirecting page make a curl or stream_get_contents over to a "collection" page prior to issuing a header(), where you collect and store the any session information (like the refererer) and have it prepared to be processesed when they redirect.
You could try adding a CGI query string to the end of your URL when doing the redirect -- eg
http://www.site-b.com?redirectfrom=www.site-a.com
site-b.com would ignore the URL parameter, but it would be recorded in the logs and would be accessible from within PHP.
You can do it with javascript. Use the following script, but it between <head> and </head>
<script type="text/javascript">
location.href='http://www.site-b.com';
</script>
This will of course not make a proper HTTP 301 redir, but I just tested it, and it will send the referer (the referer being site-a).

How to identify if referrer is a 301 redirect

I'm implementing a slug system for my website at the moment. I plan to redirect invalid slugs to the correct on that is stored in the database.
E.g.
http://example.com/11/wrong-slug
Hit db, check if 11's slug is wrong-slug if not do 301 redirect
http://example.com/11/right-slug
Detect 301 and inform user that they followed an invalid link
Is it possible to identify the 301 redirect preferably using PHP so I can ask the user to update there bookmark etc.
Thanks,
Jamie.
Alternatively you could append a GET parameter to your url (if you don't mind that), and check for it in your PHP script. Something like:
http://example.com/11/right-slug?corrected-from=http://example.com/11/wrong-slug
On the same note you can use the session or cookies, but you must take care to remove them after detection.
Several solutions come to mind:
You could try with get_headers() ah no, it dispatches a request to the URL, which is not what you want
Since you are redirecting and testing for the redirect from the same machine anyway, you could simply write a message about the wrong slug into the user's session and display it the next time the view template is rendered. Many frameworks have a flash messenger component, that allow you do that easily, e.g. with Zend Framework you would use the following code in your controller action
$flashMessenger = $this->_helper->getHelper('FlashMessenger');
$flashMessenger->addMessage('We did something in the last request');
Instead of redirecting immediately when a wrong slug is found, you just render a View template that tells your user about the wrong slug and then use a meta or javascript redirect from the template. Optionally, you'd also write a plain link with the right slug to the template.
And finally, you could also inject a custom header into the redirect via header(), which can then be read from your script. won't work either, because they will be lost once the browser got the redirect from the server
A solution might be to check the $_SERVER['HTTP_REFERER'] in the "new" page : if it is set and corresponds to the "old" page, it's probably because your user has been redirected -- which means you might want to display your message.
But note that the Referer is sent by the user's browser, and can be either disabled or forged -- so it's OK to use it to enhance the experience, but you must not rely on it for anything critical.
Found a working solution:
Start session.
Check session, if $_SESSION['INVALID_SLUG'] exists display message then unset session
else
Retreive slug from database e.g. /11/right-slug
Get current URI e.g. /11/wrong-slug
Compare, if different set $_SESSION['INVALID_SLUG'] and redirect to correct page
Any feedback?
I realise this will not detect a 301 redirect itself more detect a trigger assosiated with the redirect.
Thanks for all the help.
I think the only useful option is to use a cookie.
When a URL with the wrong slug is requested, set a cookie for that URL without the slug:
$path = substr($_SERVER['REQUEST_URI'], 0, strrpos($_SERVER['REQUEST_URI'], '/')+1);
setcookie('wrong-slug', 1, 0, $path);
Then test if such a cookie exists and display your message:
if (isset($_COOKIE['wrong-slug'])) {
echo 'The location of this resource has changed. Please update your bookmarks.';
}

Categories