DEV Community

Mohamed Hammi
Mohamed Hammi

Posted on • Edited on

2

Bare-bones file upload in php

HTML Form

/index.html :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <form method="post" action="upload.php" enctype="multipart/form-data">
      <label for="file-label">File : </label>
      <input type="file" name="myfile" id="myfile" />
      <input type="submit" name="submit" id="submit" value="Submit" />
    </form>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

File Upload Handler

/upload.php :

<?php
$tempFile = $_FILES['myfile']['tmp_name'];
$fileName = $_FILES['myfile']['name'];

$fileDestination = __DIR__."/uploads/".$fileName;

copy($tempFile, $fileDestination);

unlink($tempFile);
Enter fullscreen mode Exit fullscreen mode

Note :
An /uploads folder must be created beforehand.

Top comments (3)

Collapse
 
mikeritter profile image
mike ritter

I would add error handling including a line to check if the uploads directory exists first.

Collapse
 
madeinmilwaukee profile image
Chuck Watson

This is not a tutorial. It is a dangerous example of how to do things wrong. Just delete it.

Collapse
 
mohamed_hammi profile image
Mohamed Hammi

This is just an experiment with the language, not a tutorial, so it's not about being right or wrong.

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay