Back to Previous Page when you get Error

2

Hello, I have an e-mail newsletter code and when I enter the wrong email address or give some error, I would like instead of redirecting to the registration.html 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 do not know if it can be done in JS or just in PHP itself.

Thank you all for trying to help.

    
asked by anonymous 16.03.2016 / 12:40

2 answers

3

I think the best way would be to use PHP.

if ($email === '') {

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

Remember 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 get the previous page through PHP, you can use the $_SERVER['HTTP_REFERER'] variable, which treats 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 not be the source url, because it may be a request made directly to that url.

So you can use a fallback.

$fallback = 'index.php';

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

header("location: {$anterior}");
exit;
    
16.03.2016 / 12:44
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>";
} [..]
    
16.03.2016 / 12:45