I`ve finished my website,its a social netwrk web in PHP.
Now before i lunch it,i would like to know what are the precautions i should take to protect it from hackers.
please if any one has idea on what i should do,to protect mysql,and my site as a whole.i will be greatefull if u`ll leave me ur suggestions.

mysql_real_escape_string()

Well for one, I would use mysql_real_escape() on any variable you are passing to MySQL. That should prevent any kind of MySQL injection. I would make sure that your passwords are hashed correctly (using md5() or sha1() ). For added security I would salt your encryptions. See this page for more on salts. Beyond that: Don't store password in cookies (using a unique id or some kind of session id), don't allow code tags (such as <script>) in any kind of use input that will be placed on a page, and be sure that users are authenticated on every page. If you would like, you could give us the address of your site and we can look at some possible security flaws.

thankx guys for replying))
i added the following in my login form.

$user=mysql_real_escape_string($_POST['user']);
$password=mysql_real_escape_string(md5($_POST['password']));

when i try to login in my localhost it works fine.but in server online it doesn`t work.
When i used addslashes instead of mysql_real_escape_string,the function worked in all sectors.
So what is the difference between these two functions,And if iwant to use mysql_real_escape_string how should i make it to work.??

Well this is definitely an improvement! I believe you problem lies in the fact that the passwords in the database aren't hashed using md5(). You need to create a temporary PHP file on your site with just one line of code:

echo md5("password here");

Then all you have to do is go through you your databases passwords and plug them into the md5 function. After that just replace the old password with the new hashed string. (It is important to make sure that the row that holds passwords can handle a hash. If it is a Varchar it needs to be at least 32 in length). Next, you might need to know if your host has magic_quotes_gpc on (Chances are your host has it on). If so, on the server you will need to change the code so that before you mysql_real_escape_string() a string that you pass it through stripslashes:

$user = mysql_real_escape_string(stripslashes($_POST['user']));
$password = mysql_real_escape_string(stripslashes($_POST['password']));

The reason for this is that when magic_quotes_gpc is on, most strings will automatically be escaped already (but not escaped for MySQL!). You will need to use stripslashes() before you use any MySQL escaping functions on it, so that the string is unescaped. This may sound confusing (In fact, it's been deprecated in PHP 5.3 and will be removed in PHP 6), but I believe this could be your solution.

@FlashCreations,in da web when registering i hash the passwords with md5().thats why when login i was using

$user=$_POST['user'];
$password=md5($_POST['password']);

the problem started after i added

mysql_real_escape_string

and how will i know if the magic_quotes_gpc is ON??
also i tested sending comments using
mysql_real_escape_string it worked.
it seems the problem is in the Authorization.
help me in this plz

You will know if magic_quotes_gpc is on by asking your host (If they have the latest version of PHP it shouldn't be!). That might not be it. The only way for us to help you is if you post your code.

here is my login code

<?php  session_start();

 $user=mysql_real_escape_string($_POST['user']);
 $password=mysql_real_escape_string(md5($_POST['password']));
 

//connecting to databases
include"config.php";
 

	   
$query = "SELECT  *FROM login where (user='$user' and password='$password')" ;
$result=mysql_query($query);
if(mysql_num_rows($result)==1) {

$row=mysql_fetch_array($result);
$id=$row['id'];
$user=$row['user'];
$password=$row['password'];
$email=$row['email'];

$_SESSION['id']=$row['id'];
$_SESSION['user']=$row['user'];
$_SESSION['password']=$row['password'];
$_SESSION['email']=$row['email'];
$_SESSION['name']=$row['name'];
$_SESSION['photo']=$row['photo'];

include "index.php";


}else{
include"wronglogin.php";
 }

?>

]

yes that is also a corect statement but u also need to do this for the registration as well because it is actually inserting into the database there is more of a risk

Your code is looking fine. Do you have any issue?

Interesting thread ....

Does this work as well?

$a_user=$_POST['login_username'];
    $a_password=sha1($_POST['login_password']);

    // set up SQL statement
    $query = sprintf("SELECT	*
				FROM	admin_auth
				WHERE	a_user = '%s'
				AND		a_pass = '%s'",
				mysql_real_escape_string($a_user),
				mysql_real_escape_string($a_password));

Sometimes i have feelingz may be something is wrong with the server i`m hosting my website.
How do you guys think??

Well, it doesn't appear anything is wrong. (I do agree, you should use mysql_real_escape_string() in your registration script too). I must say, it is a huge security flaw to save passwords and other sensitive data in a SESSION variable. It would be much better if you have each user a unique key that changed every few minutes and stored that in a SESSION variable instead of the password. Since you code looks fine to me, what errors/problems are you seeing with this script?

the error i`m seeing in this script is

}else{
include"wronglogin.php";//the wrong login
 }

i also added in mysql_real_escape_string() in the registration and it gave me one error. see my registration code below

<?php
$name=$_POST['name'];
$user=$_POST['user'];
$email=$_POST['email'];
$country=$_POST['country'];
$passreal=$_POST['password2'];
$password=md5($_POST['password']);
$password2=md5($_POST['password2']);
$location=$_POST['location'];
$family=$_POST['family'];
$names="$name $family";
$age=$_POST['age'];
$gender=$_POST['gender'];
$relation=$_POST['relation'];
$agree=$_POST['agree'];
//check if username contains space
if(false !== strpos($user, ' '))
{    echo '<font color=brown>Sorry, the username should not contain any spaces.</font></br>';
echo"you can use the underscore (_) to separate</br> or the minus (-) sign.</br>";
     echo"<center><a href=sinup.php> < < BACK </a></center>";
exit();
}
//check if username is greater than 25 character 
	if (strlen($user)>20)
{
echo "<font color=brown>Length of username is too long!</font></br>";
echo"it should not be longer than 20 characters<br>";
 echo"<center><a href=sinup.php> < < BACK </a></center>";
exit();
}
//check if email is valid
function isEmail($email) {
return preg_match('/^[-0-9A-Z_\.]{1,50}@([-0-9A-Z_\.]+\.){1,50}([0-9A-Z]){2,4}$/i', $email);
}
$err = '';
if ( !isEmail($_POST['email']) ) $err .= '<font color=brown>Your Email address must be valid!<br/><a href=sinup.php> < < BACK </a> </font>';

if ($err){ echo $err;
exit();

}
//check if all datas where posted.
if(!$name||!$password||!$family||!$country||!$user||!$email||!$location||!$relation||!$password2||!$gender||!$age){
 echo "<center><b><font color=blue size=>Fill all the required Fields.</font></b><br>";
 echo "<font color=blue >Go back and complete<br><a href=sinup.php><< BACK </a></font><br></center>";
  exit();
	  }
	  
	  if($password!=$password2){
	  echo"<center><font color=brown>Password You gave does Not match</font></center>";
	  echo"<center><form action=sinup.php method=post><input type=submit value='OKEY'></form></center>";
	  exit();
	  }
	  
if(!$agree){
echo"<font color=brown>you must agree the term of service to register</font>";
exit();
}	  
///connecting to databases
include"config.php";
	  
  $check=mysql_query("SELECT user FROM login WHERE user='$user'");
  $rows=mysql_num_rows($check);
  if($rows==0){
        //$query="INSERT INTO login(name,family,male,female,user,email,country,password) VALUES('$name','$family','$male','$female','$user','$email','$country','$password')";
  
	   $query="INSERT INTO login SET name='$names',age='$age',location='$location',passreal='$passreal',relation='$relation',gender='$gender',user='$user',email='$email',country='$country',password='$password',date=CURDATE()";
        $prove="INSERT INTO profile SET names='$names',ages='$age',locations='$location',passreal='$passreal',relations='$relation',genders='$gender',users='$user',emails='$email',countrys='$country',passwords='$password',online='offline',dates=CURDATE()";     
		$result=mysql_query($query,$dbcnx);
		$result1=mysql_query($prove,$dbcnx);
			if($result||$result1){
echo"You registered successfully";
}
?>

After adding mysql_real_escape_string() the error comes in

//check if all datas where posted.
if(!$name||!$password||!$family||!$country||!$user||!$email||!$location||!$relation||!$password2||!$gender||!$age){
 echo "<center><b><font color=blue size=>Fill all the required Fields.</font></b><br>";
 echo "<font color=blue >Go back and complete<br><a href=sinup.php><< BACK </a></font><br></center>";
  exit();
	  }

which shows like i escaped some inputs.

I don't think you understand where you are supposed to escape the string. The function should be used right before the variable is inserted into the database. This was if a user didn't fill out a field, they won't have to wait for the escaping of all the variables before they are validated (It could save a few milliseconds, but probably won't matter that much). Where you are getting the error, I would use:

if(empty($name)||empty($password)||empty($family)||empty($country)||empty($user)||empty($email)||empty($location)||empty($relation)||empty($password2)||empty($gender)||empty($age)){

ok i will try it.
i`ll inform you.

hey guys!i came out with the solution..
the problem was with the Database connection.This function mysql_real_escape_string requires a database connection .
in my code i were establing the connection after the POST[].
Thankx all for Contribution.

@FlashCreations You talked about giving each user a unique key which will be changing every time.
how is it possible??

Well for the users table in your MySQL database add a new column called session id. When the user logs in, create a long random string (unique key) to save as a cookie on the user's computer and in the user's row in the MySQL database (You would put it in the column you created for the unique keys). Then on every page where you authenticate the user, add code to create a new random string (unique key) and change the key in the cookie and the database to the new one you just created. This way you won't need to store a password in a cookie. You will only need to store the username and the unique key as a cookie on the user's computer (and add a column to your users table for the keys). To authenticate, check the username and the unique key and then regenerate the unique key.

how is it possible that someone was able to insert Javascript in the database while i used mysql_real_escape_string

<script>alert('helloo my friend')</script>

HOW CAN I AVOID THIS ISSUE??
my current code is

$comment=mysql_real_escape_string($_POST['comment']);

I NEED YOUR HELP THIS ISSUE OF SQL INJECTION.

It's very possible. mysql_real_escape_string() only escapes special characters such as " and ' that can make your queries vulnerable to a MySQL injection. Inserting script into a query is not MySQL injection as it doesn't affect the database. The danger is when other people view a page that uses this content. The script can get cookies from the user such as password and username and send them to script on their site that saves them. To protect again this all you have to do is escape < and > with their HTML equivalents ( &lt; and &gt; ):

$comment=mysql_real_escape_string(str_replace("<", "&lt;", str_replace(">", "&gt;", $_POST['comment'])));

Thats not sql injection. It's called xss.

You need to run the data through the php function htmlentities().

thankx for your suggestions,i will work on it.

i tried

$comment=mysql_real_escape_string(str_replace("<", "&lt;", str_replace(">", "&gt;", $_POST['comment'])));

and htmlentities() they are doing the same thing.
Is the anything more i should take care of ???

You probably should use htmlentities as it is a function that is packaged with PHP and therefore does a lot more then replace the < and >. In fact, htmlentities escapes all characters that have HTML "entity equivalents" (&gt; or &lt; for example). Since htmlentities does a lot more then my two str_replaces, I would use htmlentities. Off the top of my head, I can't think of anything else if you've tried something similar to my unique key system (and removed that cookie that stores the user's password!).

Is there a way someone could use GET OR REQUEST ,TO harm my site?
bcoz up to this moment,i were just dealing with the inputs POST.

As long as you don't use the $_GET[] variable without sanitizing or replacing html entities you should be safe. If you don't use it, there's no way for it to be hacked!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.