Send attachment by php form

Asked

Viewed 71 times

0

Hello, I have a PHP file that sends data from my HTML folder via Email. Only that I would like to send attachments also(resume)because it is a page of "Work with us". I’ve seen plenty of tutorials around, but I can’t always understand :( , here’s the PHP code of the current form.

 <?php 

    $nome = $_POST['nome'];
    $email = $_POST['email'];
    $cargo = $_POST['cargo'];
    $cpf = $_POST['cpf'];
    $foto = $_POST['foto'];
    $msg = $_POST['txt'];

    $to ="[email protected]";

    $subject = "Contato - Trabalhe Conosco";

    $body = "Nome: ".$nome."\n".
            "Email: ".$email."\n".
            "Cargo Pretendido: ".$cargo."\n".
            "Cpf: ".$cpf."\n".
            "Foto: ".$foto."\n\n".
            "Mensagem: \n".$msg."\n";

    $header = "From:test@test"."\r\n"."Reply-to:"
               .$email."\r\n";

    if(mail($to,$subject,$body,$header))
    {
        echo "Email enviado com sucesso !";
    }

    else
    {
        echo "O email nПлкo pode ser enviado, tente novamente mais tarde";
    }


?>

1 answer

0

Let’s start with HTML:

In his form you must enter the attribute enctype='multipart/form-data' to send the file to your PHP server and the input type file. So your form that only sends a file will look like this:

 <form method="POST" enctype='multipart/form-data' >
    <input type="file" name="arquivo" id="arquivo"/>
    
    <input type="submit" value="Enviar"/>
</form> 

PHP

In PHP it seems difficult but it’s not, just remember a few steps:

  1. Receives file in a temporary location

  2. Check format, size and etc... (safety issue)

  3. Move to the right place.

    When a user sends a file to the PHP server, the file is saved to the $_FILES global variable, similar to $_GET and $_POST. I will post a code already ready and you check the comments the steps

PHP

    $destino = "uploads/"; // Local onde o arquivo será salvo
    $tamanhoLimite = 15000 // Tamanho maximo do arquivo em bytes
    
    if($_POST['enviar']){
        // Verifica se o  MIME type do arquivo é permitido
        if(strpos($_FILES['arquivo']['type'], "pdf")){ 
            //Move e renomeia o arquivo para o lugar desejado
            move_uploaded_file($_FILES['arquivo']['tmp_name'], $destino.$_FILES['arquivo']['name']);
        }
    }

I recommend you read this page http://php.net/manual/en/function.move-uploaded-file.php

HTML

<form method="POST" enctype='multipart/form-data' >
    <input type="file" name="arquivo" id="arquivo"/>
    
    <input type="submit" name="enviar" id="enviar" value="Enviar"/>
</form> 

Browser other questions tagged

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