How to upload files using php?

File uploads are a common feature of web applications. PHP's `$_FILES` superglobal helps manage uploaded files.

Example:

  $target_dir = 'uploads/';
  $target_file = $target_dir . basename($_FILES['fileToUpload']['name']);
  move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file);
  

Solution:

Ensure that you validate file types and sizes for security:


  $fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
  if($fileType != 'jpg' && $fileType != 'png') {
      echo 'Sorry, only JPG and PNG files are allowed.';
  }
  

Beginner's Guide to PHP