0

I have a text box with submit button.After clicking the submit button i want to check that filename is exist or not and also want to validate filename ( only .php extension is allowed) file extension.

<input type="text" name="textfield1" id="text1" />

<input type="button" value="submit" name="submit" id="submit" onclick="login()"; />

<input type="reset" value="clear" id="reset" name="reset" />
</form>
3
  • what regex will do here? Commented Jul 28, 2014 at 10:44
  • javascript for filename validation Commented Jul 28, 2014 at 10:46
  • there are lots of string methods such as endsWith, indexOf etc. Commented Jul 28, 2014 at 10:47

2 Answers 2

1

Looks like an X-Y problem here. Here's a couple of things you should consider:

  • Checking if a file exists (on the server, presumably) can't reliably be done client-side
  • Any client-side validation is insufficient to say the least. It's not reliable
  • Why regex? There are better tools for the job here. Better, as in: more reliable, easier, and probably faster, too
  • Checking the extension alone won't cut it. The rest of the filename might be invalid, too.

Be that as it may, why not check the last four chars in the file name. Given that you only allow .php extensions, a simple:

var inputVal = inputElem.value.trim();
if (inputVal.substr(-4).toLowerCase() === '.php')

should do just fine. You can do the same thing server-side, too:

if (strtolower(trim(substr($_POST['inputName'], -4))) === '.php')

Of course, you'll still have to check the value the user submitted for other prohibited/tricky chars like quotes, spaces, line-breaks, (back-)slashes, hashes and the like... All in all, I think you'd do well rethinking your approach. Perhaps tell us what it is you're actually trying to do, so we can recommend an alternative to your current solution.

Once you've got that working, checking if a file actually exists can be easily done using the PHP function: file_exists. It returns true if the file exists, fals if not.

Sign up to request clarification or add additional context in comments.

2 Comments

how to check this php is exit or not? if exited that php file reult wants to shows in the same page
@user... erm... file_exists seems pretty self-evident to me, doesn't it? added that to my answer
0

Use ajax to check whether the file name exists or not,and here you want to upload only php files so no need to go for Regular Expression

Please refer the below jsfiddle link

(http://jsfiddle.net/udhaya2006/BKMju/1/)

this will help you for sure

Comments

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.