Prashant Singh
Prashant Singh

Reputation: 3793

Protecting PHP files from being called by other websites

I have a website which fetches data from some PHP files to display it on the website. However, to protect my data to be used by other people, I wish to protect my PHP file being called by crawlers, bot etc to gather data.

I have prevented it by checking referral URL , but that can be easily by-passed. So, is there any other way to protect my data . I wish that only my website can call to those files.

Thanks !!

Upvotes: 2

Views: 395

Answers (4)

Prashant Singh
Prashant Singh

Reputation: 3793

As suggested by DaveRandom, I finally used a cookie based authentication technique to avoid calling of PHP by other websites.

The server first sets a access code for each valid client. This access code is checked at the beginning of my PHP file.

Cookie is set a max time limit of 5 hrs and cookie is destroyed on window close. This is working pretty fine for me.

Please mention if there is any glitches in this part !!

Upvotes: 0

Matthew Scragg
Matthew Scragg

Reputation: 4638

I have a website which fetches data from some PHP files to display it on the website.

Move the files that contain the data outside of the document root. Assuming that the PHP files are just being accessed by another inside the docroot.

Upvotes: 1

Mike S.
Mike S.

Reputation: 4879

If you have Apache web server and in root directory of your site you create an .htaccess file (dot htaccess with no suffix).

Try this syntax to prevent access to specific file types:

<FilesMatch "\.(htaccess|htpasswd|ini|php)$">
 Order Allow,Deny
 Deny from all
</FilesMatch>

Another way is in all non-index php files you could include something like this:

In index.php, add an access value like this:

$access = 'my_value';

In every other file, include this check before even a single byte is echoed out by php:

if(empty($access)) {
    header("location:index.php"); 
    die();
}

Upvotes: 1

complex857
complex857

Reputation: 20753

Add Basic HTTP authentication in top of your php file:

if ( !isset($_SERVER['PHP_AUTH_USER']) || 
      !isset($_SERVER['PHP_AUTH_PW']) ||
      !($_SERVER['PHP_AUTH_USER'] == 'user' && $_SERVER['PHP_AUTH_PW'] == 'pw'))) {
    header('WWW-Authenticate: Basic realm="Mirkwood"');
    header('HTTP/1.0 401 Unauthorized');
    die();
}

Upvotes: 1

Related Questions