For me to easy browse the right file before uploading, this what i want to accomplish. How to do that?
My input codes:
Inside the form are two inputs. And with likely similar filename. Submit button will trigger the "uploadnow" function.
<td>UPLOAD#1: AGL_001.txt <input type="file" name="upload1" id="upload1"></td>
<td>UPLOAD#2: AGL_0001.txt <input type="file" name="upload2" id="upload2"></td>
function uploadnow(){
$allowed_upload1 = ['AGL_001.txt']; // added
$allowed_upload2 = ['AGL_0001.txt']; //added
if(isset($_FILES['upload1']['name'])){
//$errors= array();
$file_name = $_FILES['upload1']['name'];
$file_size =$_FILES['upload1']['size'];
$file_tmp =$_FILES['upload1']['tmp_name'];
$file_type=$_FILES['upload1']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['upload1']['name'])));
//$img_loc = $file_name.'.'.$file_ext;
if (in_array($file_name, $allowed_upload1)) {
move_uploaded_file($file_tmp,"uploads/".$file_name);
} else {
$message = "Sorry, wrong filename on UPLOAD#1";
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
if(isset($_FILES['upload2']['name'])){
//$errors= array();
$file_name = $_FILES['upload2']['name'];
$file_size =$_FILES['upload2']['size'];
$file_tmp =$_FILES['upload2']['tmp_name'];
$file_type=$_FILES['upload2']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['upload2']['name'])));
//$img_loc = $file_name.'.'.$file_ext;
if (in_array($file_name, $allowed_upload2)) {
move_uploaded_file($file_tmp,"uploads/".$file_name);
} else {
$message = "Sorry, wrong filename on UPLOAD#2";
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
}
I believe you can't preset the filename client-side, but you can constrain accepted file types with accept attribute on your input (thought it's tough to predict all mime types .txt comes with):
<input type="file" accept="text/plain">
or more general
<input type="file" accept="text/*">
Though this is not a bullet proof solution and you can foul the browser.
You can implement a JavaScript solution, which will listen to input changes and validate filename.
To do it server side, just check the value of $_FILES[$input_name]['name'] (or $_FILES[$input_name][$index]['name'] for a file input with multiple attribute)
$allowed_filenames = [
'AGL_001.txt',
];
if(isset($_FILES['upload1']['name'])){
//$errors= array();
$file_name = $_FILES['upload1']['name'];
$file_size =$_FILES['upload1']['size'];
$file_tmp =$_FILES['upload1']['tmp_name'];
$file_type=$_FILES['upload1']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['upload1']['name'])));
//$img_loc = $file_name.'.'.$file_ext;
if (in_array($file_name, $allowed_filenames)) {
move_uploaded_file($file_tmp,"uploads/".$file_name);
} else {
// log an error
}
}
Related
I need to get this script to check if the uploaded file is a video file or not and whether the file size is too big or not over the limit. Therefore, need to replace the getimagesize with something else that gets the video file size. How can I accomplish this? Which function to use here? getvideosize function does not exist.
This is where I am stuck.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check whether the file was uploaded or not without any errors.
if(!isset($_FILES["id_verification_video_file"]) &&
$_FILES["id_verification_video_file"]["Error"] == 0)
{
$Errors = Array();
$Errors[] = "Error: " . $_FILES["id_verification_video_file"]
["ERROR"];
print_r($_FILES); ?><br><?php
print_r($_ERRORS);
exit();
}
else
{
//Feed Id Verification Video File Upload Directory path.
$directory_path = "uploads/videos/id_verifications/";
//Make Directory under $user in 'uploads/videos/id_verifications'
Folder.
if(!is_dir($directory_path . $user)) //IS THIS LINE CORRECT ?
{
$mode = "0777";
mkdir($directory_path . $user, "$mode", TRUE); //IS THIS LINE
CORRECT ?
}
//Grab Uploading File details.
$Errors = Array(); //SHOULD I KEEP THIS LINE OR NOT ?
$file_name = $_FILES["id_verification_video_file"]["name"];
$file_tmp = $_FILES["id_verification_video_file"]["tmp_name"];
$file_type = $_FILES["id_verification_video_file"]["type"];
$file_size = $_FILES["id_verification_video_file"]["size"];
$file_error = $_FILES['id_verification_video_file']['error'];
$file = $_FILES["id_verification_video_file"]["name"];
// in PHP 4, we can do:
$fhandle = finfo_open(FILEINFO_MIME);
$mime_type = finfo_file($fhandle,$file); // e.g. gives "video/mp4"
// in PHP 5, we can do:
$file_info = new finfo(FILEINFO_MIME); // object oriented approach!
$mime_type = $file_info->buffer(file_get_contents($file)); // e.g. gives
"video/mp4"
switch($mime_type) {
case "video/mp4":
// my actions go here...
}
// Let's assume that the name attribute of the file input field I have
used is "id_verification_video_file"
$tempFile = $_FILES['id_verification_video_file']['tmp_name']; // path of
the temp file created by PHP during upload. I MOST LIKELY GOT THIS LINE
WRONG AT THE END PART. HOW TO CORRECT THIS ?
$videoinfo_array = getimagesize($tempFile); // returns a false if not a
valid image file
if ($videoinfo_array !== false) {
$mime_type = $videoinfo_array['mime'];
switch($mime_type) {
case "video/mp4":
// your actions go here...
move_uploaded_file("$file_tmp", "$directory_path" . "$user/" .
"$file_name"); //IS THIS LINE CORRECT ?
//Notify user their Id Verification Video File was uploaded successfully.
echo "Your Video File \"$file_name\" has been uploaded successfully!";
exit();
}
}
else {
echo "This is not a valid video file";
}
}
}
?>
<form METHOD="POST" ACTION="" enctype="multipart/form-data">
<fieldset>
<p align="left"><h3><?php $site_name ?> ID Video Verification Form</h3></p>
<div class="form-group">
<p align="left"<label>Video File: </label>
<input type="file" name="id_verification_video_file"
id="id_verification_video_file" value="uploaded 'Id Verification Video
File.'"></p>
</div>
</fieldset>
<p align="left"><button type="submit" class="btn btn-default"
name="id_verification_video_file_submit">Submit!</button></p>
</form>
</body>
</html>
<?php
include 'footer_account.php'; //Required on all webpages of the Site.
?>
Best I done so far is above. I'd appreciate if you guys can add the correct lines where they should be and add comments so I can easily spot your changes and learn from the corrections.
EDIT:
Folks, I managed to fix a lot of things on my current update. But, one new problem. The move_uploaded_file() is failing. Why is that ? Do have a look. I actually wrote my questions to you in my code's comments in CAPITAL. If you could kindly answer these questions then I'd be grateful and hopefully we could close this thread as SOLVED asap.
<?php
//Required PHP Files.
include 'header_account.php'; //Required on all webpages of the Site.
?>
<?php
if (!$conn)
{
$error = mysqli_connect_error();
$errno = mysqli_connect_errno();
print "$errno: $error\n";
exit();
}
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check whether the file was uploaded or not without any errors.
if(!isset($_FILES["id_verification_video_file"]) &&
$_FILES["id_verification_video_file"]["Error"] == 0)
{
$Errors = Array();
$Errors[] = "Error: " . $_FILES["id_verification_video_file"]
["ERROR"];
print_r($_FILES); ?><br><?php
print_r($_ERRORS);
exit();
}
else
{
//Feed Id Verification Video File Upload Directory path.
$directory_path = "uploads/videos/id_verifications";
//Make Directory under $user in
'uploads/videos/id_verifications' Folder if it doesn't exist.
if(!is_dir("$directory_path/$user")) //IS THIS LINE CORRECT ?
{
$mode = "0777";
mkdir("$directory_path/$user", $mode, TRUE); //IS THIS
LINE CORRECT ?
}
//Grab Uploading File details.
$Errors = Array(); //SHOULD I KEEP THIS LINE OR NOT ?
$file_name = $_FILES["id_verification_video_file"]["name"];
$file_tmp = $_FILES["id_verification_video_file"]
["tmp_name"];
$file_type = $_FILES["id_verification_video_file"]["type"];
echo "File Type: $file_type<br>"; //Outputs: "". WHY $file_type SHOWS
BLANK VALUE WHEN UPLOADING VIDEO FILES ? WORKS WITH OTHER FILES, LIKE
JPEG.
$file_size = $_FILES["id_verification_video_file"]["size"];
$file_error = $_FILES['id_verification_video_file']['error'];
echo "File Name: $file_name<br>"; //Outputs: "id_check.mp4"
//Grab Uploading File Extension details.
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
echo "File Extension: $file_extension<br>"; //Outputs: "mp4"
if(file_exists($directory_path . "$user/" . $file_name))
//WHICH LINE IS CORRECT ? THIS ONE OR THE NEXT ONE ?
//if(file_exists($directory_path . $user . '/' . $file_name))
//WHICH LINE IS CORRECT ? THIS ONE OR THE PREVIOUS ONE ?
{
$Errors[] = "Error: You have already uploaded a video
file to verify your ID!";
exit();
}
else
{
//Feed allowed File Extensions List.
$allowed_file_extensions = array("video/mp4");
//Feed allowed File Size.
$max_file_size_allowed_in_bytes = 1024*1024*1; //Allowed
limit: 100MB.
$max_file_size_allowed_in_kilobytes = 1024*1;
$max_file_size_allowed_in_megabytes = 1;
$max_file_size_allowed =
"$max_file_size_allowed_in_bytes";
//Create a fileinfo respource.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
//Apply the fileinfo resource and the finfo_file()
function to the uploading given file.
$mime = finfo_file($finfo,$file_name);
//Close the fileinfo resource.
finfo_close($finfo); echo "Mime: $mime<br>"; //exit;
//Outputs: video/mp4
//Verify File Extension.
//if(!in_array($file_extension, $allowed_file_extensions))
die("Error 1: Select a valid video file format. Select an Mp4 file.");
//Verify MIME Type of the File.
if(!in_array($mime, $allowed_file_extensions)) die("Error 2:
Select a valid video file format. Select an Mp4 file.");
elseif(!in_array($file_type, $allowed_file_extensions))
die("Error 3: There was a problem uploading your file $file_name! Make
sure your file is an MP4 video file. You may try again."); //IS THIS LINE
CORRECT ?
//Verify File Size. Allowed Max Limit: 1MB.
if($file_size>$max_file_size_allowed) die("Error 4: Your
Video File Size is larger than the allowed limit of:
$max_file_size_allowed_in_megabytes.");
//Move uploaded File to newly created directory on the
server.
if(!move_uploaded_file($file_tmp,
"$directory_path/$user/$file_name")) die("Error 5: Your file failed to
upload! Try some other time.");
else
{
move_uploaded_file($file_tmp,
"$directory_path/$user/$file_name"); //WHY IS NOT THIS LINE OF CODE
MOVING THE FILE TO DESTINATION ?
//Notify user their Id Verification Video File was
uploaded successfully.
echo "Your Video File \"$file_name\" has been uploaded
successfully!";
exit();
}
}
}
}
?>
<form METHOD="POST" ACTION="" enctype="multipart/form-data">
<fieldset>
<p align="left"><h3><?php $site_name ?> ID Video Verification Form</h3>
</p>
<div class="form-group">
<p align="left"<label>Video File: </label>
<input type="file" name="id_verification_video_file"
id="id_verification_video_file" value="uploaded 'Id Verification Video
File.'"></p>
</div>
</fieldset>
<p align="left"><button type="submit" class="btn btn-default"
name="id_verification_video_file_submit">Submit!</button></p>
</form>
</body>
</html>
<?php
include 'footer_account.php'; //Required on all webpages of the Site.
?>
I get echoed when trying to upload an mp4 file:
Error 3: There was a problem uploading your file id_check.mp4! Make sure your file is an MP4 video file. You may try again.
Should I set the folder permissions to 0644 from 0777 ? I am being told I should not allow any files to be executable in the folder by users (file uploaders) and so I should set it to readable & writeable only to "0644". I need your expert opinion on this.
I need to upload several images, I have 2 problems, the first one that does not allow me to upload 2 or more files when it is from the cell phone (here something important, if it is from the cell phone you must open the camera and if it is in PC it must show the window of file selection, this works fine, but with the cell phone it only leaves one, so far I have only tried it on Android using Crhome) and the second detail is with the first element is not saved and if it is just a file because it does not either, it seems that it does not take position [0], when I put more than one image, the first does not save and the others are saved correctly. I've been trying for a while and I do not see the problem. Annex the structure of my files:
\camera
└───uploads
└───index.php
└───upload.php
index.php :
<html>
<head>
<meta charset="UTF-8">
<title>upload</title>
</head>
<body>
<form action="upload.php" method="post" multipart="" enctype="multipart/form-data">
<input type="file" name="img[]" accept="image/*" id="capture" capture="camera" multiple >
<input type="submit">
</form>
</body>
</html>
And upload.php :
<?php
echo '<pre>';
$img = $_FILES['img'];
if(!empty($img))
{
$img_desc = reArrayFiles($img);
print_r($img_desc);
foreach($img_desc as $val)
{
$newname = date('YmdHis',time()).mt_rand().'.jpg';
move_uploaded_file($val['tmp_name'],'./uploads/'.$newname);
}
}
function reArrayFiles($file)
{
$file_ary = array();
$file_count = count($file['name']);
$file_key = array_keys($file);
for($i=0;$i<$file_count;$i++)
{
foreach($file_key as $val)
{
$file_ary[$i][$val] = $file[$val][$i];
}
}
return $file_ary;
}
?>
This works for me, Hop this will solve your second problem.
if (isset($_FILES['Gallery']) && is_array($_FILES['Gallery'])) {
$errors= array();
foreach($_FILES['Gallery']['tmp_name'] as $key => $tmp_name ) {
$file_name = $key.$_FILES['Gallery']['name'][$key];
$file_size =$_FILES['Gallery']['size'][$key];
$file_tmp =$_FILES['Gallery']['tmp_name'][$key];
$file_type=$_FILES['Gallery']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
if (empty($errors)==true) {
if (is_dir('uploads')==false) {
mkdir('uploads', 0700); // Create directory if it does not exist
}
if (file_exists("uploads/".$file_name)==false) {
move_uploaded_file($file_tmp,"uploads/".$file_name);
chmod("uploads/".$filename, 0777);
$Gallery_Link = "uploads/".$file_name;
} else { // rename the file if another one exist
$Gallery_Link = "uploads/".time()."_".$file_name;
rename($file_tmp,$Gallery_Link) ;
}
} else {
echo $errors;
}
}
}
This code used to work and now I can't figure why it won't upload, I don't receive errors, I also don't receive any echo's or var_dumps back at all, it's simply like the button only refreshes the page. (Just for clarification there is alot more code doing alot of stuff, but this is the cause of my issue as I isolated it into another project with below code, which gave me the same results).
All it is meant to be doing is creating a folder named by the "ItemName", then it should be moving the images into that new named folder.
Thank you in advance, this problem has been hindering me for a few days now...
HTML PAGE
<form id="newsell" enctype="multipart/form-data" method="post">
<input type="text" class="css-input" name="ItemName" value="">
<input name="file[]" type="file" id="file" multiple />
<input type="submit" name="Upload" class="css-input1" value="Upload">
<?php
if ($_POST['Upload']) {
require_once("random.php");
}
?>
random.php
$MyLocation = "MyName"; // this comes from db, for this case just hardcode
$ItemName1 = htmlspecialchars($_POST["ItemName");
$ItemName = strip_tags($ItemName1);
$parentDir = "C:/wamp/www/HOME/uploadimages/".$MyLocation;
echo "Does it exist...." . $parentDir . "/" . $ItemName;
if(!is_dir($parentDir)) { // Check if the parent directory is a directory
echo "Apologies, something has gone wrong.";
RandError(); // POPUP
die();
}
if(!is_writable($parentDir)) { // Check if the parent directory is writeable
echo "Apologies, something has gone wrong.";
RandError(); // POPUP
die();
}
if(mkdir($parentDir . "/" . $ItemName) === false) { // Create the directory
echo "File apparently exists...." . $parentDir . "/" . $ItemName;
ExistingSaleName(); // POPUP
die();
}
// die('Created directory successfully'); // Success point
echo "AFTER INSERTION";
movefiles();
}
function movefiles() {
$MyLocation = "MyName";
echo "In movefiles";
$ItemName1 = htmlspecialchars($_POST["ItemName"]);
$ItemName = strip_tags($ItemName1);
extract($_POST);
if (extract($_POST) === null) { // trying to fault find here, but never returns anyway due to some kind of bug as at one point it was returning a null value
echo "PROBLEM...";
}
$error=array();
$extension=array("jpeg","jpg","png");
$res = ("C:/wamp/www/HOME/uploadimages/". $MyLocation. "/" . $ItemName);
foreach($_FILES["file"]["tmp_name"] as $key=>$tmp_name) {
$file_name=$_FILES["file"]["name"][$key];
$file_tmp=$_FILES["file"]["tmp_name"][$key];
if (!(($_FILES["file"]["type"][$key] == "image/png") || ($_FILES["file"] ["type"][$key] == "image/jpeg") || ($_FILES["file"]["type"][$key] == "image/jpg"))) {
die("Only the .jpg / .jpeg / .png file's were uploaded.");
} else {
echo "SHIT";
}
var_dump($file_tmp);
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
$count;
//check if file exist
if (!file_exists($res . "/" . $file_name)) {
sleep(2);
if (isset($_FILES["file"]["tmp_name"][$key])) {
move_uploaded_file($_FILES["file"]["tmp_name"][$key], $res);
++$count;
if ($count >=5) {
// go_to(); // This goes onto the next function
die ("First 5 images are uploaded, <br/> 5 images maximum.");
}
} else {
echo "It exited HERE...";
}
} else {
ExistingSaleName();
die();
}
}
}
I have create simple code to upload multiple images. Changes it yours.
<?php
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
$desired_dir="user_data";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==false){
move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
}else{ // rename the file if another one exist
$new_dir="$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
mysql_query($query);
}else{
print_r($errors);
}
}
if(empty($error)){
echo "Success";
}
}
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" multiple/>
<input type="submit"/>
I would like to show the errors next to input field. I tried echoing the error but it just displays the word Array. How can I show the error next to input field? Also I would like to let the user upload 5 photos and only the first photo is required. I mean the user can upload 5 photos but all the 5 photos aren't required only one. is that possible? thanks
<?php
$out['error'][]=''; //this is what I added
function uploadFile ($file_field = null, $check_image = false, $random_name = false) {
//Config Section
//Set file upload path
$path = 'productpic/'; //with trailing slash
//Set max file size in bytes
$max_size = 2097152;
//Set default file extension whitelist
$whitelist_ext = array('jpg','png','gif');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/png','image/gif');
//The Validation
// Create an array to hold any output
$out = array('error'=>null);
if (!$file_field) {
$out['error'][] = "Please specify a valid form field name";
}
if (!$path) {
$out['error'][] = "Please specify a valid upload path";
}
if (count($out['error'])>0) {
return $out;
}
//Make sure that there is a file
if((!empty($_FILES[$file_field])) && ($_FILES[$file_field]['error'] == 0)) {
// Get filename
$file_info = pathinfo($_FILES[$file_field]['name']);
$name = $file_info['filename'];
$ext = $file_info['extension'];
//Check file has the right extension
if (!in_array($ext, $whitelist_ext)) {
$out['error'][] = "Invalid file Extension";
}
//Check that the file is of the right type
if (!in_array($_FILES[$file_field]["type"], $whitelist_type)) {
$out['error'][] = "Invalid file Type";
}
//Check that the file is not too big
if ($_FILES[$file_field]["size"] > $max_size) {
$out['error'][] = "We are sorry, the image must be less than 2MB";
}
//If $check image is set as true
if ($check_image) {
if (!getimagesize($_FILES[$file_field]['tmp_name'])) {
$out['error'][] = "The file you trying to upload is not an Image, we only accept images";
}
}
//Create full filename including path
if ($random_name) {
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$out['error'][] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
} else {
$newname = $name.'.'.$ext;
}
//Check if file already exists on server
if (file_exists($path.$newname)) {
$out['error'][] = "The image you trying to upload already exists, please upload only once";
}
if (count($out['error'])>0) {
//The file has not correctly validated
return $out;
}
if (move_uploaded_file($_FILES[$file_field]['tmp_name'], $path.$newname)) {
//Success
$out['filepath'] = $path;
$out['filename'] = $newname;
return $out;
} else {
$out['error'][] = "Server Error!";
}
} else {
$out['error'][] = "Please select a photo";
return $out;
}
}
?>
<?php
if (isset($_POST['submit'])) {
$file = uploadFile('file', true, false);
if (is_array($file['error'])) {
$message = '';
foreach ($file['error'] as $msg) {
$message .= '<p>'.$msg.'</p>';
}
} else {
$message = "File uploaded successfully";
$sub=1;
}
echo $message;
}
?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
<?php
ini_set( "display_errors", 0);
if($sub==0)
{
?>
<input name="file" type="file" size="20" /><span><?php echo $out['error'] ;?></span> //It displays here just the word Array
<input name="submit" type="submit" value="Upload" />
<?php
}
?>
</form>
Because $out['error'] is an array, echoing it will output Array, as you noticed. To output it as a string you'll need to convert it first; one option to do so is using implode. I'd suggest using <br> as the 'glue' so that each error will show on a different line.
So,
<input name="file" type="file" size="20" /><span><?php echo implode('<br>', $out['error']) ;?></span>
<input name="submit" type="submit" value="Upload" />
However, perhaps a better solution would be to store the error as a string ($out['error'] = 'There was an error' rather than $out['error'][] = 'There was an error') and using a proper control structure to ensure that once an error is found the validation check ends and the form with the error message is output.
For the control structure you could do:
if ($first_check)
{
$out['error'] = 'First error message';
}
elseif ($second_check)
{
$out['error'] = 'Second error message';
}
else
{
$out['success'] = 'Success message';
}
My website having uploading profile image section for members and i've used the following code.
Form Code
<form action="send.php" method="post" enctype="multipart/form-data" name="send" id="send">
Your Image : <input type="file" name="pic" id="pic"/>
<input type="Submit" name="Submit" value="Submit"/>
</form>
PHP Code send.php
$ImageName = $_FILES[pic][name];
if(!empty($ImageName) && $_FILES[pic][type] == "image/jpeg" || $_FILES[pic][type] == "image/png" || $_FILES[pic][type] == "image/gif" || $_FILES[pic][type] == "image/bmp"){
$t = time();
$NewImageName = "$t$ImageName"; // image new name
copy($_FILES[pic][tmp_name], "users/$NewImageName"); // copy it to directory
} else {
echo "no upload done";
}
But someone by using firefox extension manage to bypass it and uploaded php file
Who uploaded the file to my website sent me message said "you only check for type !"
and said " i used firefox extension that can fake input fields and passed PHP file ".
So my question how do i protect my image upload form of the above code ? ~ thanks
First I don't think that's is the valid format to read $_FILE variable
$ImageName = $_FILES[pic][name];
You should use
$ImageName = $_FILES['pic'][name];
Then I think it is improbable that someone can fake a server side check.
Try to hack this, I use a *PATHINFO_EXTENSION* as mentioned in PHP.net Manual
$validFormat = array("jpg","JPG","jpeg","JPEG","png","PNG","gif","GIF");
$path = pathinfo($_FILES['pic']['name'], PATHINFO_EXTENSION);
if(in_array($path, $validFormat)){
// it's okay
}else{
// Error
}
I'm working with this code since I discovered pathinfo a while ago and nobody hack it..
The "type" entries in the $_FILES array are indeed just values that the client sent. Do not trust them.
files are executed as php not based on the MIME type given by the client (or the MIME type that is recognized from their data), but simply by their extension.
$imageName = $_FILES['pic']['name'];
if (isset($imageName)) {
$ext = pathinfo($imageName, PATHINFO_EXTENSION);
if (in_array(strtolower($ext), array('jpg', 'jpeg', 'gif', 'png', 'bmp')) {
$t = time();
$newImageName = $t . basename($imageName);
copy($_FILES['pic']['tmp_name'], 'users/' . $newImageName);
}
} else {
echo 'no upload done';
}
Note the invocation to pathinfo to get the extension, and basename to avoid path traversal attacks.