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
}
}