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));

2 Answers 2

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));
}
Sign up to request clarification or add additional context in comments.

Comments

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>

2 Comments

@JustinSaints since this validation can be bypassed, you should always validate server-side as well
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.