Ir para conteúdo
Fórum Script Brasil
  • 0

AJUDA COM FORMULÁRIO


Diego Fernando

Pergunta

Boa tarde a todos!

Baixei um tutorial de formulário com validação e estou com um problema: Ao fazer a validação do formulário preciso redirecionar para uma página de agradecimento, mas ao acrescentar esse redirecionamento ele sobrepõe a validação e vai pra página mesmo com o formulário em branco, e isso não pode acontecer, pode me ajudar????

SEGUE O CÓDIGO ABAIXO

<?php
// If is not empty it sets a header From in e-mail message (sets sender e-mail).
// Note: some hosting servers can block sending e-mails with custom From field in header.
//       If so, leave this field as empty.
define('FROM_EMAIL', '');


define('TO_EMAIL', 'diego@arcanjodesign.com.br');

/**
 * Function for sending messages. Checks input fields, prepares message and sends it.
 */
function sendMessage() {
    // Variables init
    $json = array();
    $token = "9320087105434084715";

    // Retrieving content from send data by form.
    // If you don't want to use filter_input you can use direct access to variable using $_POST['<name_input_name>']
    // e.g. $_POST['email']
    $contact_name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
    $contact_email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    $contact_tel = filter_input(INPUT_POST, 'tel', FILTER_SANITIZE_STRING);
    
    $contact_subject = filter_input(INPUT_POST, 'subject', FILTER_SANITIZE_STRING);
    // Translation value to description
    switch ($contact_subject) {
        case "General":
            $contact_subject = "General";
            break;
        case "Hi":
            $contact_subject = "Say Hi";
            break;
        case "Other":
            $contact_subject = "Other";
            break;
        default:
            $contact_subject = "Not selected";
            break;
    }

    $contact_message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);

    // This field is special, and it's used for anti bot protection.
    $contact_secret = filter_input(INPUT_POST, 'contact_secret', FILTER_SANITIZE_STRING);

    // Decode secret
    $contact_secret = strrev($contact_secret);

    // Token set in JS file have to be the same as in PHP file
    if ($contact_secret !== $token) {
        $json['result'] = 'NO_SPAM';
        header('Access-Control-Allow-Origin: *');
        
        echo json_encode($json);
        die();
        
    }

    // Adding e-mail headers
    $headers = "";
    if (FROM_EMAIL !== '') {
        $headers .= 'From: '.FROM_EMAIL."\r\n";
    }
    $headers .= 'Reply-To: '.$contact_email."\r\n";
    $headers .= 'Content-Type: text/plain; charset=UTF-8'."\r\n";

    /*
     * Formatting message.
     * It can be customizable in any way you like.
     */
    $title = 'EMAIL SITE - '.$contact_name;
    $message = 'Ola,'."\n\n"
        .'Voce recebeu uma nova mensagem do seu site. Verifique os detalhes abaixo:'."\n\n"
                
        .'Nome: '.$contact_name."\n"
        .'E-mail: '.$contact_email."\n"
        .'Telefone: '.$contact_tel."\n"
        
        .'Mensagem:'."\n"
        .$contact_message;


    // Mail it!
    $result = mail(TO_EMAIL, $title, $message, $headers);
    
    // Notify contact form about result of sending.
    if ($result) {
        $json['result'] = 'OK';
        
    } else {
        $json['result'] = 'SEND_ERROR';
        
    }
    
    header('Access-Control-Allow-Origin: *');
    
    echo json_encode($json);
    die();
    
}

/**
 * Function for getting visitor's IP address
 * @return string
 */
function getIp() {
    $ip = '';

    if (getenv('HTTP_CLIENT_IP')) {
        $ip = getenv('HTTP_CLIENT_IP');
    } else if(getenv('HTTP_X_FORWARDED_FOR')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    } else if(getenv('HTTP_X_FORWARDED')) {
        $ip = getenv('HTTP_X_FORWARDED');
    } else if(getenv('HTTP_FORWARDED_FOR')) {
        $ip = getenv('HTTP_FORWARDED_FOR');
    } else if(getenv('HTTP_FORWARDED')) {
        $ip = getenv('HTTP_FORWARDED');
    } else if(getenv('REMOTE_ADDR')) {
        $ip = getenv('REMOTE_ADDR');
    } else {
        $ip = 'N/A';
    }

    return $ip;
}

/*
 * Calling a from only when post request is detected (data was sent by form).
 * Otherwise it returns OK, which can be handy with checking that the script is alive.
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    sendMessage();
    
    die();
    
} else {
    if (function_exists('mail')) {
        die('OK');
        
    } else {
        die('PHP parser works, but <b>mail()</b> function seems to doesn\'t exist');
    }
 
}

Link para o comentário
Compartilhar em outros sites

0 respostass a esta questão

Posts Recomendados

Até agora não há respostas para essa pergunta

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,8k
×
×
  • Criar Novo...