how to validate format and size of uploaded file via php
<?php
if (isset($_POST["upload"])) {
// Get Image Dimension
$fileinfo = @getimagesize($_FILES["file-input"]["tmp_name"]);
$width = $fileinfo[0];
$height = $fileinfo[1];
$allowed_image_extension = array(
"png",
"jpg",
"jpeg"
);
// Get image file extension
$file_extension = pathinfo($_FILES["file-input"]["name"], PATHINFO_EXTENSION);
// Validate file input to check if is not empty
if (! file_exists($_FILES["file-input"]["tmp_name"])) {
$response = array(
"type" => "error",
"message" => "Choose image file to upload."
);
} // Validate file input to check if is with valid extension
else if (! in_array($file_extension, $allowed_image_extension)) {
$response = array(
"type" => "error",
"message" => "Upload valiid images. Only PNG and JPEG are allowed."
);
echo $result;
} // Validate image file size
else if (($_FILES["file-input"]["size"] > 2000000)) {
$response = array(
"type" => "error",
"message" => "Image size exceeds 2MB"
);
} // Validate image file dimension
else if ($width > "300" || $height > "200") {
$response = array(
"type" => "error",
"message" => "Image dimension should be within 300X200"
);
} else {
$target = "image/" . basename($_FILES["file-input"]["name"]);
if (move_uploaded_file($_FILES["file-input"]["tmp_name"], $target)) {
$response = array(
"type" => "success",
"message" => "Image uploaded successfully."
);
} else {
$response = array(
"type" => "error",
"message" => "Problem in uploading image files."
);
}
}
}
?>
Are there any code examples left?
New code examples in category PHP
-
PHP 2022-03-27 22:40:03 index:of curiosa 2019 mp4
-
PHP 2022-03-27 22:35:13 Dijkstra’s algorithm php
-
PHP 2022-03-27 22:35:12 get_declared_classes
-
PHP 2022-03-27 22:30:23 php move index of a value to first position in array
-
PHP 2022-03-27 22:25:01 wordpress get_date
-
PHP 2022-03-27 21:30:38 php shorten string with dots
-
PHP 2022-03-27 21:10:46 php header 500
-
PHP 2022-03-27 21:05:06 laravel schedule run
-
PHP 2022-03-27 20:25:12 Get page title, excerpt or content by id
-
PHP 2022-03-27 20:00:27 php convert date from dd/mm/yyyy to yyyy-mm-dd