PHP Header Redirect, If Variable Then Redirect - php

I want to use one URL to redirect users to various outgoing URLs. For example http://example.com/out.php?ofr=2 where ofr will refer to the appropriate URL the user should be redirected to.
I have the following php code for out.php
Is this acceptable, or is there a more efficient way to accomplish this (assuming there were 10 or so different URLs in the below script)?
<?php
$ofr = $_GET['ofr'];
if ($ofr == 1) {
header('location: http://google.com');
}
elseif ($ofr == 2) {
header('location: http://yahoo.com');
}
else {
header('location: http://msn.com');
}
?>
Edit: Looking at switch statements as suggested, I believe it would look like:
$ofr = $_GET['ofr'];
switch ($ofr){
case 1: header('location: http://example_1.com');
break;
case 2: header('location: http://example_2.com');
break;
default: header('location: http://example_2.com');
break;
}
Does that look correct? Thanks!

First of all I suggest to make a redirect function like so:
function redirect($url)
{
$baseUri=_URL_;
if(headers_sent())
{
$string = '<script type="text/javascript">';
$string .= 'window.location = "' . $baseUri.$url . '"';
$string .= '</script>';
echo $string;
}
else
{
if (isset($_SERVER['HTTP_REFERER']) AND ($url == $_SERVER['HTTP_REFERER']))
header('Location: '.$_SERVER['HTTP_REFERER']);
else
header('Location: '.$baseUri.$url);
}
exit;
}
then in a file called redirectFiles.php make array of the urls that you want to redirect:
$redirecUrls = [
'location: http://example_1.com',
'location: http://example_2.com',
'location: http://example_3.com',
]
then make a function to do the redirecting:
function redirectUrls($index){
if(isset($redirecUrls[ $index])
return redirect($redirecUrls[ $index])
return false;
}
After that you can do something like this:
$ofr = $_GET['ofr'];
if($ofr!='')
redirectUrls($ofr)

Try something like this:
<?php
$ofr=$_GET['ofr'];
$url_array=array([1]=>http://google.com [2]=>http://yahoo.com);
foreach($url_array as $key=>$value)
{
if($ofr==$key)
header('location: ".$value."');
}
?>

Related

Cannot Redirect Using $_SERVER Variables, PHP

I have a PHP application (a request form) that first checks for an active $_SESSION before a user can access the site. Because of the timeout period set for this form there is rarely an active session. Here's the check:
if (isset($_SESSION['samlUserdata'])) {
$attributes = $_SESSION['samlUserdata'];
$user_department = $attributes['department'];
$user_email = $attributes['email'];
$user_employee_id = $attributes['employee_id'];
$user_full_name = $attributes['full_name'];
}
...and here is the else {} that I use to grab the REQUEST_URI:
else {
if (isset($_SERVER['REQUEST_URI'])) {
$referer = $_SERVER['REQUEST_URI'];
$redirect = "https://myinternalwebsite.net$referer";
}
header("Location: https://myinternalwebiste.net/confirm_auth.php?sso");
}
...and last, here is what I do with the $_GET
if (isset($_GET['sso'])) {
if (isset($redirect)) {
$auth->login($redirect);
} else {
$auth->login("https://myinternalwebsite.net/");
}
}
However, once my session is killed I am never properly routed back to the URL set in the ['REQUEST_URI'], I am always just dumped onto the internal site's front page. I have troubleshooted this on and off for some time over the last week, to no avail. I've tried other variables in the $_SERVER array as well, such as ['REDIRECT_URL'].
I'm at a loss, and I'm sure this fairly simple for anyone with more experience than myself... so I am all ears and eager to learn.
EDIT:
Thank you for the comments below. Per your advice I will add the entirety of my code here, removing only the unnecessary parts. (And yes, I appreciate the tip to flip the initial (isset()) to (!isset(). Thank you for that.)
<?php
session_start();
$auth = new OneLogin\Saml2\Auth($saml_settings);
if (isset($_SESSION['samlUserdata'])) {
$attributes = $_SESSION['samlUserdata'];
$user_department = $attributes['department'];
$user_email = $attributes['email'];
$user_employee_id = $attributes['employee_id'];
$user_full_name = $attributes['full_name'];
} else {
if (isset($_SERVER['REQUEST_URI'])) {
$referer = $_SERVER['REQUEST_URI'];
$redirect = "https://example.net$referer";
}
header("Location: https://example.net/confirm_auth.php?sso");
}
if (isset($_GET['sso'])) {
if (isset($redirect)) {
$auth->login($redirect);
} else {
$auth->login("https://example.net/");
}
} else if (isset($_GET['slo'])) {
$auth->logout();
} else if (isset($_GET['acs'])) {
$auth->processResponse();
$errors = $auth->getErrors();
if (!empty($errors)) {
echo '<p>', implode(', ', $errors), '</p>';
}
if (!$auth->isAuthenticated()) {
echo "<p>Not authenticated!</p>";
exit();
}
$_SESSION['samlUserdata'] = $auth->getAttributes();
if (isset($_POST['RelayState']) &&
OneLogin\Saml2\Utils::getSelfURL() != $_POST['RelayState']) {
$auth->redirectTo($_POST['RelayState']);
}
} else if (isset($_GET['sls'])) {
$auth->processSLO();
$errors = $auth->getErrors();
if (empty($errors)) {
echo '<p>Sucessfully logged out!</p>';
} else {
echo '<p>', implode(', ', $errors), '</p>';
}
}
?>

PHP Check if user is logged in with a function

I'm working on a website and the index page checks if the user is logged in or not with this piece of code:
if (!$_SESSION['login'] && $_SESSION['login'] == "") {
include_once($_SERVER['DOCUMENT_ROOT'] . "/login/");
} elseif ($_SESSION['login'] == 1) {
include_once($_SERVER['DOCUMENT_ROOT'] . "/main/");
}
But I want it to look cleaner, then I started wondering if was possible to achieve something like this with a function:
checklogin($_SESSION['login']);
I don't have much experience with functions, so i'm sorry if my question looks stupid, so thanks in advance.
Try this
if(check_login()) {
echo 'You are in!';
} else {
header('Location: login.php');
exit;
}
function check_login () {
if(isset($_SESSION['login'] && $_SESSION['login'] != '') {
return true;
} else {
false;
}
}
Just use empty:
if ( empty($_SESSION['login']) ) {
include_once($_SERVER['DOCUMENT_ROOT'] . "/login/");
} else {
include_once($_SERVER['DOCUMENT_ROOT'] . "/main/");
}
Or condense it:
include_once $_SERVER['DOCUMENT_ROOT'].(empty($_SESSION['login']) ? "/login/" : "/main/");
There is what you need:
function userCheck()
{
return (isSet($_SESSION['login']) && $_SESSION['login']);
}
if(userCheck())
include_once($_SERVER['DOCUMENT_ROOT'] . "/main/");
else
include_once($_SERVER['DOCUMENT_ROOT'] . "/login/");
Disregarding the fact of whether or not your approach makes sense, I think this would do what you expect:
function checklogin($login){
if (!$login && $login == "") {
include_once($_SERVER['DOCUMENT_ROOT'] . "/path/");
}
}
// **** call to the function
checklogin($_SESSION['login']);
// ****
You can use this function:
function checklogin() {
return (isset($_SESSION['login'])) ? true : false;
}
then on pages you want to check whether the user is logged in or not, you can:
if(checklogin() === true){
//here you would put what you want to do if the user is logged in
} else {
//this would be executed if user isn't logged in
header('Location: protected.php');
exit();
//the above would redirect the user
}

Detecting browser language in PHP and redirect

I want to write a simple if statement using HTTP_ACCEPT_LANGUAGE function that redirects based on result of what the users browser language is. I am still a beginner so am obviously keeping it as simple as possible. This is what I have so far but the "if" statement needs work. Can anyone help me with a fix?
<?php
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
if ($lang=german) {
header("Location: http://www.example.com/german/index.html");
} else if ($lang=spanish) {
header("Location: http://www.example.com/spanish/index.html");
}
else if ($lang=french) {
header("Location: http://www.example.com/french/index.html");
}
else if ($lang=chinese) {
header("Location: http://www.example.com/chinese /index.html");
} else {
echo "<html>english content</html>";
}
?>
I don't know what your language literals are, so I'd say make them ISO language codes.
Use a switch statement, this is more readable and smaller:
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
switch($lang) {
case "de-DE":
case "es-ES":
case "cn-CN":
case "fr-FR":
header("Location: http://www.example.com/$lang/index.html");
break;
default:
header("Location: http://www.example.com/en-US/index.html");
break;
}
Further, you are assigning, not comparing. You compare with ==:
if ($lang == "de-DE")
Assuming you always redirect to /language/, you could do it this way:
<?php
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
if ( in_array( $lang,array("german","spanish","french","chinese") ) ) {
header("Location: http://www.example.com/$lang/index.html");
} else {
echo "<html>english content</html>";
}
?>
Also, the comparisons in your if need to be done with ==, it's assignment otherwise!
Try this:
<?php
$path = array(
'en-US' => 'english',
// etc
);
$accepts = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
if (in_array($accepts[0], $path)) { // if path exists for language then redirect to path, else redirect to default path (english)
header('Location: http://www.example.com/' . $path[$accepts[0]] . '/index.html');
} else {
header('Location: http://www.example.com/english/index.html');
}
?>
HTTP_ACCEPT_LANGUAGE returns not "english", but two signs symbol like "en", or region and language symbol like "en_us". You shouldn't use if statement it's hard to read. You should use array (in future you can simple write it to config files, or move to databases).
The proper code should look that:
$default_lang = 'en';
$lang_redirectors = array('de' => 'http://www.example.com/german/index.html',
'en' => 'http://www.example.com/english/index.html');
function redirect($url){
header("Location: " . $url);
}
$hal = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$langs = explode($hal, ',');
foreach($langs as $lang){
$lang_prefix = substr($lang, 0, 2);
if(in_array($lang_prefix, $lang_redirectors)){
redirect($lang_redirectors[$lang_prefix]);
break;
}
redirect($lang_redirectors[$default_lang]);
}
<?php
$browserlang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$lang = $browserlang[0] . $browserlang[1] . $browserlang[2] . $browserlang[3] . $browserlang[4];
if (($lang=="sk_SK") OR ($lang=="sk-SK")) {
header("Location: https://www.example.sk/sk");
}
else if (($lang=="en_EN") OR ($lang=="en-EN") OR ($lang=="en_GB") OR ($lang=="en_US") OR ($lang=="en-GB") OR ($lang=="en-US")) {
header("Location: https://www.example.sk/en");
}
else {
header("Location: https://www.example.sk/en");
}
?>

How do I write a function that tells me that I am currently looking at the homepage (/index.php)?

PHP:
function is_homepage()
{
}
if(is_homepage())
{
echo 'You are on the homepage';
}
else
{
echo 'You are not on the homepage';
}
Explanation:
is_homepage, should work in all these cases:
http://www.domain.com
https://www.domain.com
http://domain.com
http://domain.com/?param=value
http://domain.com/index.php?param=value
Where it shouldn't work:
http://subdomain.domain.com
http://domain.com/otherfile.php?param=value
etc.
do a
print_r($_SERVER);
and you'll see all the data which will help you achieve this.
I would use
$_SERVER['PHP_SELF']
to identify the file\page I'm currently working with.
It depends of course on how your PHP script is laid out. Though the following solution would work in most cases:
$_SERVER['SCRIPT_NAME'] == '/index.php'
function is_homepage()
{
return ( ( $_SERVER['HTTP_HOST'] == 'www.domain.com' || $_SERVER['HTTP_HOST'] == 'domain.com') && substr( $_SERVER['REQUEST_URI'], 0, 9 ) == 'index.php' );
}
if(is_homepage())
{
echo 'You are on the homepage';
}
else
{
echo 'You are not on the homepage';
}

redirecting with if statment based on cookie using header('location:') gives weird error in firefox

I am trying to redirect my visitors to for example http://localhost/site/test.php?lang=en_USbased on the country code in the cookie like this:
if (isset($_COOKIE['country']))
{
$country = $_COOKIE['country'];
header('Location: test.php?lang=en_US');
if ($country == "NO"){
header('Location: test.php?lang=no_NO');
}
}
else
{
header('Location: test.php?lang=en_US');
}
But i get this weird error in firefox: The page isn't redirecting properly
Found a solution:
if (!isset($_GET['lang']))
{
if (isset($_COOKIE['country']))
{
$country = $_COOKIE['country'];
$redirect = "en_US";
if ($country == "NO"){
$redirect = "no_NO";
header('Location: crime.php?lang='.$redirect);
}
if ($country == "EN"){
$redirect = "en_US";
header('Location: crime.php?lang='.$redirect);
}
}
else
{
header('Location: crime.php?lang=en_US');
}
}
The problem is that it is unconditionally redirecting, and always to itself, causing an infinite loop which Firefox detects and stops. You need to add conditions to prevent redirects once the final page has been reached.

Categories