PHP script is used in a HTML form to allow users for uploading a file from a folder or server. Whenever user do so initially the file is in the temporary directory after it will relocated into the target destination. The uploaded file could be anything like file,image or any document.
Following are the line code that will explain how a IMAGE will be uploaded into the server by using PHP. Here we use a global variable $_FILES which contains all the necessary information regarding the image.
FOR EXAMPLE:
$_FILES['filename']['name'] − the actual name of the uploaded file.
$_FILES['filename']['size'] : the size in bytes of the uploaded file.
$_FILES['filename']['type'] : type of the uploaded file.
$_FILES['filename']['error']: error code associated with this file upload.
<?php
if ('POST' === $_SERVER['REQUEST_METHOD']) {
if(isset($_FILES['file']) && !empty($_FILES['file'])){
$errors= array();
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
$file_type = $_FILES['file']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['file']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152) {
$errors[]='Image size must be atmost 2 MB';
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp,"images/".$file_name);
echo "<script>alert('Image uploaded successfully')</script>";
//echo "<img src='images/$file_name'>"; //uploaded image will be shown in this img tag
}else{
echo "<script>alert('".$errors."')</script>";
}
}
else{
echo "<script>alert('Please select a image')</script>";
}
}
?>
<html>
<head>
<style type="text/css">
img{width: 100%;height: 400px;display: block;margin-top: 10px}
input{border: none;padding: 10px; border-radius: 0;background-color: #ccc}
form{box-shadow: 0px 0px 2px #000;display: inline-block;padding: 10px; border-radius: 3px}
</style>
</head>
<body>
<form action = "" method = "POST" enctype = "multipart/form-data">
<input type = "file" name = "file">
<input type = "submit" value="Upload">
<img src="<?php echo $_FILES['file']['name']; ?>" alt="uploaded image will be shown here"><!-- uploaded image will be shown in this img tag -->
</form>
</body>
</html>
0 Comment(s)