anonymous anonymous - 7 months ago 52
PHP Question

Referring URL Redirect after login

I have the below PHP code:

<?php

// let's add a ref url feature for quick guidance.

$ref = $_SERVER['HTTP_REFERER'];

$actual_link = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]?ref=$ref";

header("Location: $actual_link");

if (empty($ref)) {
# do nothing...
} else {
$redirect_to_ref = header("Location: $ref");
header("Location: test.php");
}

}

?>
<?php

function checkRef() {
if (isset($redirect_to_ref)) {
$redirect_to_ref;
} else {
header("Location: index.php");
}
}

$error = false;
if(isset($_POST['login'])){
$username = htmlspecialchars($_POST['username']);
$password = md5($_POST['password']);
if(file_exists('users/' . $username . '.xml')){
$xml = new SimpleXMLElement('users/' . $username . '.xml', 0, true);
if($password == $xml->password){
session_start();
$_SESSION['username'] = $username;
checkRef();
die;
}
}
$error = true;
}
?>


This code is for a simple xml login script. This will just log the person in, and if the person came from a page that required one to be logged in, but one wasn't, I would like it to add the referrer in the url bar, and upon login success, redirect the user to that referred url. However, this is now giving me an error 500. Please help...

Answer

Try this:

<?php
//GLOBAL FUNCTION TO GET THE CURRENT URL:
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;
}

// USE SESSION TO SET A VARIABLE FOR THE REF. URL:
if (session_status() == PHP_SESSION_NONE  || session_id() == '') {
    session_start();
}
if(isset($_SESSION['ref_url'])){
    header("Location: " . $_SESSION['ref_url']);
    unset($_SESSION['ref_url']);
}



//IN ALL OTHER PAGES; SET THE URL OF THE CURRENT PAGE TO THE $_SESSION['ref_url'] VARIABLE LIKE SO
if (session_status() == PHP_SESSION_NONE  || session_id() == '') {
    session_start();
}
$_SESSION['ref_url'] = curPageURL();

Hope this helps...