Return to Previous Page when Error

Asked

Viewed 6,726 times

2

Hello, I have an email registration code Newsletter and when putting wrong email or giving some error, I would like that instead of redirecting to the.html registration page, it redirects to the previous page, how can I do this?

The PHP Code looks like this:

    <?php
include("config.php");
$email  = $_POST["e-mail"];
$opcao  = $_POST["opcao"];
$codigo = md5($email);
if($email == ""){
echo "<script>alert('Por favor, digite um email válido.');";
echo "location.href='cadastro.html'</script>";
} [..]

I don’t know if it can be done in JS or only in PHP itself.

Thank you all just for trying to help.

3 answers

3


I think the best way would be using PHP.

if ($email === '') {

    header('location: /index.php');
    exit;
}

Remembering that, to use this form, it is necessary that no content is sent to the browser, by php, before this declaration.

If you want to take the previous page by PHP, you can use the variable $_SERVER['HTTP_REFERER'], that handles the url of the source page of the access.

 header(sprintf('location: %s', $_SERVER['HTTP_REFERER']));
 exit;

In some cases, this variable will not exist, as there will be no source url, for perhaps dealing with a request made directly to this url.

So you can use a fallback.

$fallback = 'index.php';

$anterior = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : $fallback;

header("location: {$anterior}");
exit;

1

Try this:

<?php
include("config.php");
$email  = $_POST["e-mail"];
$opcao  = $_POST["opcao"];
$codigo = md5($email);
if($email == ""){
echo "<script>alert('Por favor, digite um email válido.');";
echo "javascript:history.go(-1)'</script>";
} [..]

0

I know the problem is old, yet I’ll leave an answer as an option if anyone needs.

<?php
//Função para redirecionar a página para o link
function redireciona($link){
     if ($link==-1){
     echo" <script>history.go(-1);</script>";
     }else{
     echo" <script>document.location.href='$link'</script>";
     }
 };
//Cria uma variavel
$link = 'minhapagina.php';

//E aonde quiser chama a função dentro de um if ou qualquer coisa.

// Chama a função
redireciona($link); 
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.