0

I have an input box where I type the name of the file. I want the input box to require me or other users to input also what type of file it is.

For example, when I just type this_is_name_of_file to the input box and submitted it. It should return false.

Is there a way for it to accept only when I type it as name_of_file.pdf or name_of_file.docx wherein I type the name of file with its file extension.

This is the input tag inside my form:

<label>File Name: </label> 
<input class="input2" type="text" name="filename" 
       placeholder="file.pdf/xlsx/xls/docx" required autofocus><br>

This is my php file:

$FName = $_POST['filename'];
$pdoQuery = "INSERT INTO `report`(`filename`) VALUES (:FName)";
$pdoResult = $pdoConnect->prepare($pdoQuery);
$pdoExec = $pdoResult->execute(array(":FName"=>$FName));
Pankaj
  • 931
  • 8
  • 15

2 Answers2

4

there are few options, but i would go wtih:

$path_parts = pathinfo($_POST['filename']);//spits the variable in to parts to chewck

if(empty($path_parts['extension'])){ //check for extension
    echo 'filename error';
}else{
    $FName = $_POST['filename'];
    $pdoQuery = "INSERT INTO `report`(`filename`) VALUES (:FName)";
    $pdoResult = $pdoConnect->prepare($pdoQuery);
    $pdoExec = $pdoResult->execute(array(":FName"=>$FName));
}
3

If you're happy with browser validation (like how you have required), you could always use a pattern, eg

<form>
<input class="input2" type="text" name="filename" 
       placeholder="file.pdf/xlsx/xls/docx" required autofocus
       pattern=".+\.(pdf|xlsx?|docx)">
<button>Try it</button>
</form>
Phil
  • 157,677
  • 23
  • 242
  • 245
  • 2
    @JustinSaints since this validation can be bypassed, you should always validate server-side as well –  Mar 08 '19 at 01:54
  • You're welcome. Keep in mind, anything client-side can be circumvented so it's always a good idea to back this up with server-side validation as well. Also, if you need case-insensitive checks, see [HTML5 Input Pattern Case-Insensitivity](https://stackoverflow.com/q/23852036/283366) – Phil Mar 08 '19 at 01:55