tags:

views:

94

answers:

2

Hi, when I connect to my database I include('connect.php') the document to connect. Now I want to do it a bit more safe. Is it possible to check that the one that want to include the connect.php is from my domain. Like:

if($_SERVER["HTTP_REFERER"] == "mydomain.com"){
    $link = mysql_connect("localhost","user","password"); 
    mysql_select_db("dbname");
}

And if this is possible, how do I check that $_SERVER["HTTP_REFERER"] == mydomain.com, when $_SERVER["HTTP_REFERER"] can return mydomain.com/page.php?

+5  A: 

This is not a problem to be solved within PHP. If somebody can include the file just like that, the server security is already screwed up. It's the job of the web server to prevent serving of raw PHP files and the job of the OS security and user settings to prevent file inclusion by unauthorized users/processes. If someone gets enough access to the file to be able to include it, they have enough access to just read it, in which case none of the security measures you put in the file will be executed.

In summary: Don't worry about it. :)

EDIT:

Something like this:

RewriteEngine On
RewriteRule ^connect.php /index.php [R]

That might change with your particulars tough, look through the myriad of questions about this topic.

deceze
Ok. But anyway I want user who go directly to mybomain.com/connect.php to be redirected to index.php.
Johan
The best is to put these non-user-accessible library files into their own directory and protect it with an `.htaccess` file.
deceze
Yes, I know that now, but not when I started this project, so it's too late now.
Johan
You can still protect the single file with an `.htaccess` directive a la "redirect all requests for `connect.php` to `index.php`".
deceze
Ok, good. I don't know how to write the code fore .htaccess. Do you?
Johan
@deceze: Better yet: have the library be in a map above the web root. This way, if a accidental server misconfiguration has happened, your sourcecode is still save from being accessed through http.
fireeyedboy
Yes of course, very true.
deceze
+1  A: 

It seems to me that you've doing it backwards.

The easier way to secure your connect.php is to move it one folder upwards (outside the web root) and use include('../connect.php') instead of include('connect.php'). Do just that and you're safe (regarding connect.php, at least).

HTTP_REFERER has nothing to do with security. Checking for it will just cause the visitor to receive a Database connection error instead of the requested page if the check fails. It will fail every time:

  1. somebody comes to your site following a link on another site (including Google and co.)
  2. somebody comes to your site clicking on a browser bookmark
  3. somebody comes to your site typing the address directly in the address bar

Somehow I don't believe this is something you may want.

djn