Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent direct url access to php file

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 ?

like image 906
It Assistors Avatar asked Nov 30 '15 13:11

It Assistors


People also ask

Are PHP files secure?

PHP is as secure as any other major language. PHP is as secure as any major server-side language. With the new PHP frameworks and tools introduced over the last few years, it is now easier than ever to manage top-notch security.


3 Answers

You can do it with PHP

<?php
    /* at the top of 'check.php' */
    if ( $_SERVER['REQUEST_METHOD']=='GET' && realpath(__FILE__) == realpath( $_SERVER['SCRIPT_FILENAME'] ) ) {
        /* 
           Up to you which header to send, some prefer 404 even if 
           the files does exist for security
        */
        header( 'HTTP/1.0 403 Forbidden', TRUE, 403 );

        /* choose the appropriate page to redirect users */
        die( header( 'location: /error.php' ) );

    }
?>
like image 135
Professor Abronsius Avatar answered Oct 26 '22 22:10

Professor Abronsius


Put this code at the top of check.php:

if(!isset($_SERVER['HTTP_REFERER'])){
    // redirect them to your desired location
    header('location:../index.php');
    exit;
}

If the user access check.php by type the URL directly, it will redirect them to your desired location.

like image 21
Westly Tanbri Avatar answered Oct 26 '22 22:10

Westly Tanbri


Try this in Root/.htaccess :

RewriteEngine on


RewriteCond %{REQUEST_METHOD} !^POST$
RewriteRule ^php/check.php$ - [NC,R=404,L]

This will return 404 not found if check.php is not accessed by form post method.

like image 21
Amit Verma Avatar answered Oct 27 '22 00:10

Amit Verma