Php Sql Injection Secure Tags

New Friends! :slight_smile:

The following is my member registration code as of latest.

ISSUE 1:
I get this error:

Parse error: syntax error, unexpected ‘_’ (T_STRING), expecting ‘,’ or ‘)’ in C:\xampp\htdocs\e_id\register_edited.php on line 10

What is wrong ? I copied the “‘images/’_$FILES[‘avatar’][‘name’]);” from a youtube tutorial on how to create feature for your member site members to upload their images. It was working on my site but not now on my xammp.

ISSUE 2:

Is the following ok or have I got them wrong way round ? I mean the real_escape and the strtolower and the strip_tags. Eg.

$member_registration_username = trim(strip_tags(strtolower(mysqli_real_escape_string($conn,$_POST[“member_registration_username”]))));

Any mistakes I made from line 9-22 ?

Question 3:

Looking at my html form, do you spot any errors apart from the outdated tags ? (Will replace them and design with css instead. In the middle of it now).

Question 4:
Should there be 2 equal signs ? Eg. “== 0” (equal to) ? instead of just “=” ?
$member_registration_account_activation = 0;

FULL REG PAGE CODE:

<?php
require "conn.php";
require "site_details.php";

if  (isset($_POST['submit']))
{
	if(!empty($_POST["member_registration_username"]) && !empty($_POST["member_registration_password"])&& !empty($_POST["member_registration_password_confirmation"])&& !empty($_POST["member_registration_email"])&& !empty($_POST["member_registration_email_confirmation"])&& !empty($_POST["member_registration_forename"])&& !empty($_POST["member_registration_surname"]))
	{
		$account_activation_link = "http://www.$site_domain.com/$site-name/activate_account.php?email=$member_registration_email&&member_registration_account_activation_code=$member_registration_account_activation_code";
		$avatar_path = trim(strip_tags(mysqli_real_escape_string($conn,'images/'_$FILES['avatar']['name']);
		$member_registration_account_activation = 0;
		$member_registration_random_numbers = random_int(0, 9999999999);
   		
        $member_registration_username = trim(strip_tags(strtolower(mysqli_real_escape_string($conn,$_POST["member_registration_username"]))));
		$member_registration_password = trim(strip_tags(md5(mysqli_real_escape_string($conn,$_POST["member_registration_password"]))));
        $member_registration_password_confirmation = trim(strip_tags(md5(mysqli_real_escape_string($conn,($_POST["member_registration_password_confirmation"])))));
        $member_registration_forename = trim(strip_tags(mysqli_real_escape_string($conn,$_POST["member_registration_forename"])));
        $member_registration_surname = trim(strip_tags(mysqli_real_escape_string($conn,$_POST["member_registration_surname"])));
		$member_registration_gender = trim(strip_tags(mysqli_real_escape_string($conn,$_POST["member_registration_gender"])));
        $member_registration_email = trim(strip_tags(mysqli_real_escape_string($conn,$_POST["member_registration_email"])));
        $member_registration_email_confirmation = trim(strip_tags(mysqli_real_escape_string($conn,$_POST["member_registration_email_confirmation"]));
		$member_registration_account_activation_code = trim(strip_tags(mysqli_real_escape_string($conn,"$member_registration_random_numbers")));
		
		if (preg_match("!image!", $_FILES['avatar']['type'])) 
		{		
		//copy image to images/ folder.
			if(copy($_$FILES['avatar']['tmp_name'], $avatar_path)) 
			{			
				$_SESSION['avatar']=$avatar_path;
			}
			else
			{
				$_SESSION['message']= "Image could not be uploaded!";
			}
		else
		{
			$_SESSION['message']= "Only gif, jpeg or png files allowed for your avatar!";
			exit();
		}
			
		if($_POST["member_registration_email"] != $_POST["member_registration_email_confirmation"])
		{
			$_SESSION['message']= "Your email inputs do not match! Try inputting again and then re-submit.";
			exit();
		}
        
		if($_POST["member_registration_password_confirmation"] != $_POST["member_registration_password_confirmation"])
		{
			$_SESSION['message']= "Your password inputs do not match! Try inputting again and then re-submit.";
			exit();
		}
	
		//Check for Username match in users	table.	
		$sql = "SELECT * FROM users WHERE Usernames ='".$member_registration_username."'";
		$result = mysqli_query($conn,$sql);
		if(mysqli_num_rows($result)!=0)
		{
			$_SESSION['message']="That Username $member_registration_username is already registered!";
			exit();
		}

		$sql = "SELECT * FROM users WHERE Emails ='".$member_registration_email."'";
		$result = mysqli_query($conn,$sql);
		if(mysqli_num_rows($result)>0)
		{
			$_SESSION['message']="That Email $member_registration_email is already registered!";
			exit();
		}
		
	    $sql = "INSERT INTO users(Usernames,Passwords,Emails,Forenames,Surnames,Genders,Account_Activation_Codes,Account_Activations) VALUES('".$member_registration_username."','".$member_registration_password."','".$member_registration_email."','".$member_registration_forename."','".$member_registration_surname."','".$member_registration_account_activation_code."','".$member_registration_account_activation."')";
        if($sql)
	    {
	        $_SESSION['message']="Data insertion into table success!";
        }
	    else    
	    {
            $_SESSION['message']="Data insertion into table failure!";
	    }
	
	    $to = "$member_registration_email";
	    $subject = "Your $site_name Account Activation!";
	    $body = "$member_registration_forename $member_registration_surname,\n\n You need to click the following link to confirm your email address and activate your account.\n\n\
	    $account_activation_link;
		$from = "$site_admin_email";
	    $headers = "from: $from";
	
	    mail($to,$subject,$body,$headers);
	    $_SESSION['message']="Check your email for further instructions!";
	}
	else
	{
	    $_SESSION['message']="You must fill-in all input fields!";
	}
}

?>
<!DOCTYPE html>
<html>
<head>
<title><?php $site_name ?> Signup Page</title>
  <meta charset="utf-8">
</head>
<body>
<div class = "container">
<form method="post" action="">
<center><h2>Signup Form</h2></center>
<div class="form-group">
<center><label>Username:</label>
<input type="text" placeholder="Enter a unique Username" name="member_registration_username" required [A-Za-z0-9]></center>
</div>
<div class="form-group">
<center><label>Password:</label>
<input type="password" placeholder="Enter a new Password" name="member_registration_password" required [A-Za-z0-9]></center>
</div>
<div class="form-group">
<center><label>Repeat Password:</label>
<input type="password" placeholder="Repeat a new Password" name="member_registration_password_confirmation" required [A-Za-z0-9]></center>
</div>
<div class="form-group">
<center><label>First Name:</label>
<input type="text" placeholder="Enter your First Name" name="member_registration_forename" required [A-Za-z]></center>
</div>
<div class="form-group">
<center><label>Surname:</label>
<input type="text" placeholder="Enter your Surname" name="member_registration_surname" required [A-Za-z]></center>
</div>
<div class="form-group">
<center><label>Gender:</label>
<input type="radio" name="member_registration_gender" value="male" required>Male<input type="radio" name="member_registration_gender" value="female" required>Female</center>
</div>
<div class="form-group">
<center><label>Email:</label>
<input type="email" placeholder="Enter your Email" name="member_registration_email" required [A-Za-z0-9]></center>
</div>
<div class="form-group">
<center><label>Repeat Email:</label>
<input type="email" placeholder="Repeat your Email" name="member_registration_email_confirmation" required [A-Za-z0-9]></center>
</div>
<center><button type="submit" class="btn btn-default" name="submit">Register!</button></center>
<center><font color="red" size="3"><b>Already have an account ?</b><br><a href="login.php">Login here!</a></font></center>
</form>
</div>
</body>
</html>

@uniqueideaman, could you please format your code to make it easier to read? Just highlight all the code in the edit area and select the </> icon, or you could place three backticks (`) on the line before the code and three backticks on the line right after the code.

1 Like

should be
if(copy($_FILES['avatar']['tmp_name'], $avatar_path))

You’ve got a stray $

1 Like

When assigning a value to a variable it is just one = as in:-

$bird = 'chicken' ;

You use two or three = only when doing a comparison between two values, as in:-

if($bird == 'chicken') { $product = 'egg'; }
1 Like

Thanks for teaching me about that </> icon. I will try remembering it next time.

Thanks for bringing that too my attention! :slight_smile:

You mean if I’m comparing if number is higher or lower then I use ==.
But if I want an exact match, like a string, then I use the =.
Right ?
Thanks! But correct me if I’m wrong.
When do you use 3 like so === ?

Well, I guess I don’t have to worry about getting my tags the wrong way round since no one here is complaining. Right ?

$member_registration_account_activation_code = trim(strip_tags(mysqli_real_escape_string($conn,“$member_registration_random_numbers”)));

Should the trim really be at the beginning, before the strip_tag ?
Correct me if I’m wrong. I remember reading few mnths back that the strip tag erases all the symbols that is considered to be an sql command, such as the “?”. Right ? I mean, if all the sql command symbols have been erased then there is no need for prepared statements as the strip_tag is capable enough to prevent sql injection. Right ?

No. == and === test for equality, not unequality.

see post #4.

type-safe comparison.

you want more complaining?

2 Likes

no.

1 Like

Opps! I meant, if you are comparing 2 numbers then you use ==.
Anyway, I have a mysql column “account activation” and the entry is “0”.
When the user clicks the activation link he gets in his email then the “0” is UPDATED by “1”.
Now, if the user tries logging into his account before activating the link he gets in his email then my script checks to see if the entry is “0” or “1”. Here, I used the single equal sign: =.
I guess I should replace it with “==” since you and SamA74 are saying you use the signle equal sign = when assigning a variable. Correct ?

It depends on the language. In SQL you use other comparison operators.

1 Like

If there is a serious danger in my script of getting sql injection or hacking then by all means do complain.

For higher or lower you would use “greater than” > or “less than” < for the comparison.

No, one = is to assign a value. It is not for comparisons. Comparisons and assignments are completely different things.
When I say:-

$bird = 'chicken' ;

It means: I want the value of the variable $bird to be set to the string 'chicken'.
I am setting a value, not comparing.

A comparison checks one value against another and returns a result, usually a boolean (true or false).
It does not set or assign a value.

An exact match is a comparison using ===

See this about comparisons:-

1 Like

Yeah. In Ubot Studio (gui bot building tool) we got the <, >, =, !=, <=, =>.
But no == or ===.
We got the $compare to check for exact matches and the $contains to check for fuzzy matches. php should’ve been easy like that.
Been bot programming since 2011 but I never got round the REGEx, though. Does my head-in!

Ubot Studio is not for PHP. simple as that.

I am now reading this since so many programmers are against me not using Prepared Statements:

The following, however, earlier on did my head in and put me off from php!

http://php.net/manual/en/pdo.prepared-statements.php

If it was me, I’d stay away from fan-based websites unless you know that the website is trustworthy. If the website knows exactly what it is talking about, that’s a fine place to reference, but NOT use as a final product. You need to do your own unit test to see if things work. You can’t just blindly trust a website and then use only that website. You need to compare that website from other sources and see if that website is accurate.

I’d personally stay away from wikihow.com and w3school.com because these 2 website give out very vague information and it’s pretty depressing looking at a large majority of new PHP users going directly to those sources and actually thinking that what they are getting out of these sources are true.

Now, I must say that the link you have above from wikihow is pretty accurate, but they don’t tell the users what the s stands for. You MUST bind the correct data type to the variable or you will screw up your query. Data types are as is

s = string <-- This can be alphanumeric and including special characters
i = integer <-- Only numeric and whole numbers like 0, 1, 2, 3, 4, 5, 6, 7, 8
b = blob <-- Don't really know this one because I don't use it in PHP. I do use it in MySQL, but not PHP.
d = decimal <-- Same thing as integer, but allows whole numbers and decimals like 0.5, 1, 1.5, 2, 3, 3.5, 4, 4.5, 5, 6, 7, 8.5

NOTE


THE ONLY DATABASE API LIBRARY THAT REQUIRES DATA TYPES IS MYSQLI.


With that said, using Prepared Statements is pretty easy. It’s pretty much the same thing you do with regular ->query(...) or _query(...) BUT you don’t LITERALLY stuff the raw data into the sql string like you do with legacy codes.

Here are sample snippets of how to use Prepared Statements in both PDO and mysqli_*.

mysqli_*

$sql = "SELECT id, url, visits FROM visitors WHERE id = ? LIMIT 1"; // SQL Query String
$prepare = $db->prepare($sql); // Prepare the SQL Query String
$prepare->bind_param('i', $id); // Bind the variable $id to the appropriate data type. Since we're grabbing a numeric ID, it makes sense to use the "i" data type rather than the "s" data type.
$prepare->execute(); // Execute the prepared statement
$prepare->store_result(); // Store the prepared statement for later checking

PDO

$sql = "SELECT id, url, visits FROM visitors WHERE id = :id LIMIT 1"; // SQL Query String
$prepare = $db->prepare($sql); // Prepare the SQL Query String
$parameters = array(':id' => $id); // Prepare the :id placeholder with it's appropriate variable.
$prepare->execute($parameters); // Execute the prepared statement

Do you see how they vary depending on which Database API you use? You SHOULD NOT have to do this

$sql = "SELECT id, url, visits FROM visitors WHERE id = '$ID' LIMIT 1" // SQL Query String
                                                             ^

Because that is pretty much the fastest way to get SQL Injected and hacked.

1 Like

You are absolutely correct! Wikihow.com does not explain what the “s” is for and php.net is even worst.
The code you see in wikihow was shown to me by a programmer as an example on how I should do things but I couldn’t figure-out what the “s” was in his code. I checked php.net and their code slightly differed. I was gonna drop by to the programmer and ask him what the “s” is for and tell him that by looking at php.net manual it is seeming to me that his code is slightly different in formatting, (even though his code is more understandable than php.net’s) and so where he got the format from. Wanted to learn his source so I myself can use it without bugging others all the time for help. But then I changed my mind because I thought he might get the wrong end of the stick and think I’m suspecting his code and disrespecting him and so I quit asking him anything and went straight to php.net to learn from there how to BIND things so I don’t have to include $variables in my sql (to prevent sql injection). Php.net did my head in :banghead: and I nearly gave-up on php again. Googled and came across wikihow.com’s tutorial on the subject. They were more clear that php,net but they never mentioned what the “s” was for. Note, on one of their example they use a single “s” while on another double. This was confusing me and I was guessing the “s” meant “string”. But, should the so-called tutorial for beginners really leave things out and give the student the risk of “guessing things wrong” ? I had no choice but to come to the conclusion that there are no real proper tutorials for beginners when it comes to php. I was surprised to read your post though because you sort of read my mind or took the words out of my mouth(so to speak) and realize beginning students would end-up having a lot of questions when tutorial sites like these write half-brained tutorials like that. I can only say that, you should have been the tutor who wrote all these tutorials for beginners as you would’ve tailored your tutorials by answering basic questions that would ordinarily arise in a beginning student’s mind.
If you don’t mind me saying, you could always a tutorial section in this forum. Better, a youtube channel or wp blog or both. I believe you would gain a lot of subscribers.

Anyway, you’ve encouraged me to ask more questions as I won’t be afraid to ask questions in this forum that seem obvious answers. Sometimes, I don’t understand things but I don’t bother asking because I fear the answers maybe obvious (eg. what the “s” or “ss” is for in our example) in these half brained tutorials. Now, I understand other newbies would be in the same boat and they’d too have the same questions and they won’t “obviously” know things when it comes to these half-brained tutorials.

I understand every programmers point. I should not directly use variables in my sql queries but indirectly use them. Learning and then remembering, how to do it is the hard part.

I don’t think it would be that hard to remember now since give us here the definitions of each of these single characters. :grinning:

PS - Don’t bother showing examples of any sql injections to get the passwords from the tbl as I read on the subject few yrs back and recently another programmer showed me an example (he didn’t know I was already in the know).

Hi,

The mysqli_* & pdo examples you showed, I note the “->” and so guessing you coded them in the OOP. May we see some examples in the Procedural way (both mysqli_* & pdo) ?

Thank You!