Skip to content

Instantly share code, notes, and snippets.

@no1k
Last active December 24, 2023 09:38
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save no1k/8492575 to your computer and use it in GitHub Desktop.
Save no1k/8492575 to your computer and use it in GitHub Desktop.
Single image upload PHP
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Single Upload Form with PHP</title>
</head>
<body>
<form method="POST" action="upload.php" enctype="multipart/form-data">
<label for="file"> Pick a file : </label>
<input type="file" name ="file">
<input type="submit" value = "Upload">
</form>
</body>
</html>
<?php
//Check if the file is well uploaded
if($_FILES['file']['error'] > 0) { echo 'Error during uploading, try again'; }
//We won't use $_FILES['file']['type'] to check the file extension for security purpose
//Set up valid image extensions
$extsAllowed = array( 'jpg', 'jpeg', 'png', 'gif' );
//Extract extention from uploaded file
//substr return ".jpg"
//Strrchr return "jpg"
$extUpload = strtolower( substr( strrchr($_FILES['file']['name'], '.') ,1) ) ;
//Check if the uploaded file extension is allowed
if (in_array($extUpload, $extsAllowed) ) {
//Upload the file on the server
$name = "img/{$_FILES['file']['name']}";
$result = move_uploaded_file($_FILES['file']['tmp_name'], $name);
if($result){echo "<img src='$name'/>";}
} else { echo 'File is not valid. Please try again'; }
?>
@Chameer
Copy link

Chameer commented Oct 30, 2017

Helpful code...Thanks

@spukkyw0w
Copy link

html, no?

@bpluhar
Copy link

bpluhar commented Feb 26, 2018

@spukkyw0w it is HTML

@CreativeGP
Copy link

how about using in_array( , , true) ?

@edulecca
Copy link

thank you, simple !

@JeniaPlakhotnyk
Copy link

thank you, really helpful

@hafsaptech12
Copy link

its help ful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment