Code sur écran d'ordinateur

PHP – How to load a FILE in PHP from a form

To find out how to load a file in PHP from a form, you have to start by formatting the form correctly. It is mandatory to use the post method as well as the multipart/form-data enctype, otherwise PHP will not receive the necessary data.

<form action="/" method="post" enctype="multipart/form-data">
    <input type="file" name="namefile" />
    <input type="submit" value="ok" />
</form>

In PHP, to retrieve the data, you have to use $_FILES.

print_r($_FILES);

By doing this, we get different information

Array (
   [namefile] => Array (
      [name] => myfile.xml
      [type] => text/xml
      [tmp_name] => /tmp/phpCGlZPa
      [error] => 0
      [size] => 577059 ) )

From this moment on you can perform all the desired actions, such as saving the file on the server or parsing it like an XML.