get uploaded file in forms in php

In order to get the uploaded file in forms in PHP, you can use the $_FILES global variable.

First, ensure that your form has the enctype attribute set to multipart/form-data. This tells the browser to encode the data as a form that can handle file uploads.

main.php
<form action="upload.php" method="POST" enctype="multipart/form-data">
  <input type="file" name="myFile">
  <input type="submit" value="Upload">
</form>
154 chars
5 lines

Next, in the PHP script that the form submits to (upload.php in the example above), access the uploaded file using the $_FILES global variable. There are several values that you can access for each uploaded file, but most commonly you'll want to access the tmp_name value, which is the temporary location on the server where the uploaded file was stored.

main.php
<?php
if ($_FILES["myFile"]["error"] == UPLOAD_ERR_OK) {
  $tmp_name = $_FILES["myFile"]["tmp_name"];
  $name = $_FILES["myFile"]["name"];
  move_uploaded_file($tmp_name, "uploads/$name");
}
?>
194 chars
8 lines

The above code first checks if there were any errors during the upload. If there were none (UPLOAD_ERR_OK), it gets the temporary file name and the original file name. It then moves the uploaded file to a permanent location (in this case, a directory named 'uploads' in the same directory as the PHP script).

Note that you should always perform validation and security checks on uploaded files to prevent malicious files from being uploaded to your server.

related categories

gistlibby LogSnag