PHP and Javascript - Hosting and opening files in other formats besides PDF

1

I created a way to host presence list files in events on my client's website. Here is the code:

<b>Arquivo da lista de presença (PDF):</b>
<?php if($evento['arquivo'] == '1'){
    echo '<a href="http://meusite.com.br/upload/wt_eventos_lista_presenca/'.$evento['id'].'.pdf" target="_blank" style="color: red">Download</a><br>';
}
else {?>
    <form id="form<?php echo $evento['id']; ?>" action="hospedaarquivo?valor=<?php echo $evento['id']; ?>" method="post" enctype="multipart/form-data">
                <input type="file" name="arquivo<?php echo $evento['id']; ?>" id="arquivo<?php echo $evento['id']; ?>" class="validate[required] text-input" accept="pdf" />
                <input type="submit" name="fileEnvia" value="Enviar Arquivo" style="cursor: pointer; width: 100px;" />
    </form>
<?php }?>

And the function hosting the file is

public static function HospedaArquivo(){
    $nome = 'arquivo' . $_SESSION['idTemp'];
    if(isset($_FILES[$nome]))
    {
        date_default_timezone_set("Brazil/East"); //Definindo timezone padrão

        $ext = strtolower(substr($_FILES[$nome]['name'],-4)); //Pegando extensão do arquivo
        $new_name = $_SESSION['idTemp'] . $ext; //Definindo um novo nome para o arquivo
        $dir = 'upload/wt_eventos_lista_presenca/'; //Diretório para uploads

        if(move_uploaded_file($_FILES[$nome]['tmp_name'], $dir.$new_name)){
            echo "<script>alert('Upload feito com sucesso!');</script>";
            $sql = Doctrine_Query::create()
            ->update('WtEducEventos')
            ->set('arquivo', '?','1')
            ->where('id = ?',$_SESSION['idTemp']);
            $sql->fetchArray();
        }
        else {
            echo "<script>alert('Erro no upload');</script>";
        }
    }
    else{
        echo "<script>alert('Não há arquivo selecionado');</script>";
    }
}

But I restricted the part of HTML to accept PDF only to get easier after downloading. If I want him to accept JPG, for example, how can I make him check if the file is PDF or JPG? I do some other integration with the MySQL database (if it has the file, is 1 if it does not have 0 the value of the "file" field)?

    
asked by anonymous 09.12.2016 / 18:39

1 answer

2

With JavaScript, you can get the file type and check if it has the PDF or JPEG type using files[0].type in the change event of the input :

document.getElementById("arquivo").addEventListener("change", function(ev) {
  var tipo = ev.target.files[0].type;
  document.getElementById("tipo").innerHTML = tipo;
  if (tipo.indexOf("jpeg") !== -1 || tipo.indexOf("pdf") !== -1) {
    console.log(tipo);
    alert("Arquivo válido")
  } else {
    alert("Arquivo inválido");
  }
})
<input id="arquivo" type="file" />
<br/>
<span id="tipo"></span>
    
09.12.2016 / 19:11