Fetch file path from input type="file"

Asked

Viewed 1,094 times

0

Good afternoon, for some time I have a problem, I have the following input of type file, to get some file any.

<form class="form-signin" method="post" action="?classe=Usuario&acao=pegaFoto">
      <div class="form-label-group">
           <input type="file" name="usuario[foto]" required>
      </div>
      <button class="btn btn-lg btn-primary btn-block text-uppercase" type="submit">Enviar</button>
<form>

When you click to give Ubmit, it will enter the same page, if there is any file inside the user[photo], it will call the function pegaFoto() in the controller.

public function pegaFoto(){
    $usuario = new Usuario();
    if( isset( $_POST['usuario'])){
        $usuario->foto($_POST['usuario']);
        $usuario->pegaFoto();
    }
    require_once 'views/view_foto.php';
}

This function of the controller calls the model’s call function() and also calls the photo() function where I would like to save the file path.

public function foto($usuario){
    $this->foto = $usuario['foto'];
}
public function pegaFoto(){
    //coloquei o echo só para ver o que estava puxando
    echo $this->foto;
}

But the way I did, it just takes the name of the file chosen, I wonder if somehow I could take the file path.

  • 1

    Files sent to PHP are in $_FILES, not in $_POST. You moved the file to a definitive location before treating it or you don’t need it?

  • I’ve never seen $_FILES, I’ll take a look here, you don’t need the definitive location, I just wanted to find the way for now.

  • 1

    To send files ( $_FILES ) via your form, add the enctype="Multipart/form-data", e.g.: <form action=".. /. /" method="post" enctype="Multipart/form-data">

1 answer

1


First you need to get the file that comes in $_FILES[ ], Unlike other input types, files are sent to the PHP server through $_FILES, with it you can recover name, format, the file itself and etc.

An example upload would look like this:

//Pegando extensão do arquivo
$extencao = strtolower(substr($_FILES['arquivo']['name'],-4)); 

//Definindo um novo nome para o arquivo
$new_name = "novo_nome_do_arquivo" . $ext; 

//Diretório para uploads
$dir = 'uploads/'; 

// salva o arquivo no dietório
move_uploaded_file($_FILES['arquivo']['tmp_name'], $dir.$new_name); 

Now the file has been saved and the path is what you set in $dir.

For more information see the documentation:

https://www.php.net/manual/en/reserved.variables.files.php

https://www.php.net/manual/en/function.move-uploaded-file.php

https://www.php.net/manual/en/features.file-upload.php

Browser other questions tagged

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