I have a php file say "check.php" in my website and it is executed when a form is submitted.
say my website is "myweb.com" and the php file is in a directory "PHP"
I want to prevent direct url access to the "check.php" file i.e. if anyone types the url "myweb.com/PHP/check.php" ,then the php file should not be executed and it should return a error message instead.
I tried to prevent the access by setting a rule in .htaccess ,but it blocks the php even when I try to submit the form.
.htaccess rule :
RewriteEngine on
RewriteCond %{THE_REQUEST} \.php[\ /?].*HTTP/
(.*)\.php$ /index.html [L]
Is there any possible way to do it ?
You can do it with PHP
this is what google uses in their php examples
Try this in Root/.htaccess :
This will return 404 not found if check.php is not accessed by form post method.
Put this code at the top of check.php:
If the user access check.php by type the URL directly, it will redirect them to your desired location.
I tried the selected answer but i ran into some issues implementing it, specially if i wanted to return values from functions inside the PHP file using GET with Ajax.
After doing quite an extensive research on other solutions (and a little testing of my own), i came up with the following code:
I found that the code above worked as i wanted and i don't think it would have any problems with multiple browser like the other answer was pointed out to have. I also don't think it would have any security issues, but i could be wrong (please tell me if i am (and why)), i'm relatively new to web programming.
Just add that code on top of every file you would want to block direct URL access (before everything, even requires, includes and session_starts) and you are good to go.