Mail PHP - Sending without information

Asked

Viewed 85 times

0

I made a form in PHP with Captcha do Google. Everything works. If someone sends the email via form, it arrives perfect, has required, etc. The problem is that spans access the email page on the site, example "www.site.com.br/send-email.php".

You can put a code inside the same file preventing them from accessing this page or preventing the code from working because the fields are empty?

That is the code:

 <?


function post_captcha($user_response) {
        $fields_string = '';
        $fields = array(
            'secret' => '____aqui a secret key____',
            'response' => $user_response
        );
        foreach($fields as $key=>$value)
        $fields_string .= $key . '=' . $value . '&';
        $fields_string = rtrim($fields_string, '&');

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
        curl_setopt($ch, CURLOPT_POST, count($fields));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);

        $result = curl_exec($ch);
        curl_close($ch);

        return json_decode($result, true);
    }

    // Call the function post_captcha
    $res = post_captcha($_POST['g-recaptcha-response']);

    if (!$res['success']) {
        // What happens when the CAPTCHA wasn't checked
        echo '<p>Please go back and make sure you check the security CAPTCHA box.</p><br>';
    } else {
        // If CAPTCHA is successfully completed...

        // Paste mail function or whatever else you want to happen here!
        echo '<br><p>CAPTCHA was completed successfully!</p><br>';
    }

    $nome = $_POST['nome'];
    $fone = $_POST['telefone'];
    $email = $_POST['endereco'];
    $assunto = $_POST['assunto'];
    $msg = $_POST['msg'];

    $conteudo = "<table width='600' border='0' cellspacing='2' cellpadding='2'>
                    <tr>
                        <td colspan='1' align='center'><h3><em>Assunto do E-mail</em></h3></td>
                    </tr>

                        <tr>
                            <td width='30%' bgcolor='#f0f0f0'><strong>Nome:</strong></td>
                            <td>$nome</td>
                        </tr>
                        <tr>
                            <td width='30%' bgcolor='#f0f0f0'><strong>Telefone:</strong></td>
                            <td>$fone</td>
                        </tr>
                        <tr>
                            <td width='30%' bgcolor='#f0f0f0'><strong>Email:</strong></td>
                            <td>$email</td>
                        </tr>
                        <tr>
                            <td width='30%' bgcolor='#f0f0f0'><strong>Assunto:</strong></td>
                            <td>$assunto</td>
                        </tr>
                        <tr>
                            <td width='30%' bgcolor='#f0f0f0'><strong>Mensagem:</strong></td>
                            <td>$msg</td>
                        </tr>
                </table>";
    $seuemail = "[email protected]";
    $headers = "MIME-Version: 1.0\r\n"; 
    $headers .= "Content-type: text/html; charset=UTF-8\r\n";
    $headers .= "From:".$email." \r\n"; 
    $assunto = $assunto;

    $enviar = mail($seuemail, $assunto, $conteudo, $headers); 

    if($enviar) {
    echo "<script type='text/javascript'> alert('Contato Enviado com Sucesso!'); window.location.href='contato.php'; </script>";
    }else{
    echo "<script type='text/javascript'> alert('Ocorreu algum erro ao enviar o formul&aacute;rio'); </script>";
    }

    ?>
  • How do you validate Google’s Captcha when sending the email? In the code posted it does not seem to have this check.

  • Hello @Andersoncarloswoss, updated the code! Before the <button> I insert the <div class="g-recaptcha"> and the <script src='https://www.google.com/recaptcha/api.js?hl=pt-BR'></script> But for the tests I am doing with the Lipespry response I removed the captcha.

  • But this way the email will be sent even if the captcha is invalid, because the sending function is outside the if/else. Or you add one die(...) within the if to stop the execution, or place the rest of the code, which makes the upload, inside the else, as the comment itself indicates: Paste mail function or whatever else you want to happen here!.

  • Wow... Simpler than I imagined @Andersoncarloswoss, lack of reading about the code, even being layman in PHP. Thank you so much, that way when the sending page is accessed directly by spans, it says to go back and perform the Captcha.

  • Exactly. The solution given by Lipespry in the answers is interesting, but not completely functional, because it only deals with whether the data is null. If a spam system requests your file with non-null data, the email would be sent as well. Checking the captcha, as said, circumvents this problem.

  • Got it! I also found interesting the answer given by him, some time ago wanted to understand how it works. Anyway, thank you both!

Show 1 more comment

1 answer

1


You can create a function to validate past information via POST:

<?php
function validarPOST( $arg )
{
    if( isset( $_POST[$arg] ) ) //CHECA SE FOI PASSADO VIA POST
    {

        $arg = trim( $_POST[$arg] );

        // CHECA SE O VALOR PASSADO É NULO, VAZIO, FALSO OU ZERO;
        if( $arg == null || empty($arg) || $arg == false )
        {
            return false;
        } else
        {

        return true;

        }

    } else
    {
        return false;
    }
}
?>

Just put your code within one condition:

<?php
if( validarPOST('nome') && validarPOST('telefone') && validarPOST('endereco') && validarPOST('assunto') && validarPOST('msg') )
{
    $nome = $_POST['nome'];
    $fone = $_POST['telefone'];
    $email = $_POST['endereco'];
    $assunto = $_POST['assunto'];
    $msg = $_POST['msg'];

    $conteudo = "<table width='600' border='0' cellspacing='2' cellpadding='2'>
                    <tr>
                        <td colspan='1' align='center'><h3><em>Assunto do E-mail</em></h3></td>
                    </tr>

                        <tr>
                            <td width='30%' bgcolor='#f0f0f0'><strong>Nome:</strong></td>
                            <td>$nome</td>
                        </tr>
                        <tr>
                            <td width='30%' bgcolor='#f0f0f0'><strong>Telefone:</strong></td>
                            <td>$fone</td>
                        </tr>
                        <tr>
                            <td width='30%' bgcolor='#f0f0f0'><strong>Email:</strong></td>
                            <td>$email</td>
                        </tr>
                        <tr>
                            <td width='30%' bgcolor='#f0f0f0'><strong>Assunto:</strong></td>
                            <td>$assunto</td>
                        </tr>
                        <tr>
                            <td width='30%' bgcolor='#f0f0f0'><strong>Mensagem:</strong></td>
                            <td>$msg</td>
                        </tr>
                </table>";
    $seuemail = "[email protected]";
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=UTF-8\r\n";
    $headers .= "From:".$email." \r\n";
    $assunto = $assunto;

    $enviar = mail($seuemail, $assunto, $conteudo, $headers);

    if($enviar) {
    echo "<script type='text/javascript'> alert('Contato Enviado com Sucesso!'); window.location.href='contato.php'; </script>";
    }else{
    echo "<script type='text/javascript'> alert('Ocorreu algum erro ao enviar o formul&aacute;rio'); </script>";
    }
} else
{
    die("Informações faltando ou inválidas!");
}
?>

PS: Basic form! Use this idea to implement a validation as your need.

  • I understood the idea Lipespry! But I couldn’t implement it, I’m a bit of a layman in PHP. The first and second part of the code, I use in send-contact.php? Or the first on the contact page.php? I did the test, I sent a form with all filled and it gave the error message on DIE.

  • If you put those two codes together and replace yours, it’ll already be a hand on the wheel. Then you will research/study on the commands I used for you to improve the code.

  • I joined the two codes and ended up in the error message even when, testing on air and everything. It must be something I wrote wrong here. But thank you very much!

  • Which error message?

  • I joined the two in send-contact.php, right? Then enter the same form, contact.php, type name, address, etc... And I click send, before it appeared "Contact sent successfully", as the alert. Now it ends in "Information missing or invalid!" And it’s the same way it was for me.

  • That means some of the information is not being passed on by $_POST. Do the following: Erase everything and just leave <?php print_r($_POST); ?> on the page you send to debug. Check all the fields and see what’s wrong. If you want, start a chat with me and I’ll help you. Remembering: make a backup of your page!

  • Low reputation yet, can not start chat. hahaha. But so, I did the <?php print_r($_POST); ? > appeared all right! Then I removed the code that you suggested, I left only the sending and sent me in the e-mail all fields, IE, all information is being passed. I put your suggested code again and resumed sending the form, appeared error "Missing or invalid information!" again.

  • I fixed the function. It had an invalid condition. Now it should work. Test there. If it works, mark the answer.

Show 3 more comments

Browser other questions tagged

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