upload a file in php in php

To upload a file using PHP, you need to create an HTML form that includes a file input field, and then handle the file upload in the PHP script that receives the form submission.

Here's an example HTML form:

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

The enctype="multipart/form-data" attribute is necessary to allow file uploads.

And here's an example PHP script that handles the file upload:

main.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['file'])) {
  $file = $_FILES['file'];

  // Check for errors
  if ($file['error'] != UPLOAD_ERR_OK) {
    die("Upload failed with error code " . $file['error']);
  }

  // Check the file type
  $finfo = finfo_open(FILEINFO_MIME_TYPE);
  $mime_type = finfo_file($finfo, $file['tmp_name']);
  if ($mime_type != 'image/jpeg' && $mime_type != 'image/png' && $mime_type != 'image/gif') {
    die('Invalid file type');
  }

  // Move the uploaded file to its final destination
  $destination = 'uploads/' . $file['name'];
  if (!move_uploaded_file($file['tmp_name'], $destination)) {
    die('Failed to move uploaded file');
  }

  echo 'File uploaded successfully.';
}
?>
732 chars
26 lines

This script first checks for any errors during the file upload, then checks the file type to make sure it's an image (in this example), and finally moves the uploaded file to a specified directory.

Note that you'll need to make sure the destination directory is writable by the web server process.

related categories

gistlibby LogSnag