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.