Preventing SQL Injection in PHP Forms

  • PHP
  • Thread starter bigdawg723
  • Start date
  • Tags
    Php
In summary, the conversation discusses an issue with implementing SecurImage onto a website and difficulty with error handling for the captcha validation. The instructions from PhpCaptcha are provided and the issue ultimately seems to be a problem with the installation or directory structure. The conversation also includes a discussion about the contactProcess() function and suggestions for fixing it.
  • #1
bigdawg723
13
0
Hello All,

First and foremost, thanks for the help in the past. I've got a new issue and I think it's going to be fairly easy! (fingeres crossed)

OK, I'm implementing SecurImage (Phpcaptcha.org) onto my website.

I've got everything installed and working correctly except for error handling. Basically... my form processes everything on a separate PHP page. On my form page, I have the captcha image displaying properly, the input fields inserted properly, and now I just need the validation to work. As it stands, you can input anything into the captcha field and it will send... simply because I can't figure out where to place the error handling code from the CAPTCHA script in my validation page.

Here's what PhpCaptcha has for instruction:

3.The next few steps will vary depending on how form validation is handled in your code.
4.To check if the code is correct, we will make a call to the Securimage class. The following php code should be integrated into the script that processes your form near any error checking that takes place. It should be between <?php ?> tags.

include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
This includes the file that contains the Securimage code and creates a new Securimage object.
5.Next we will actually check to see if the code was correct.

if ($securimage->check($_POST['captcha_code']) == false) {
// the code was incorrect
// handle the error accordingly with your other error checking

// or you can do something really basic like this
die('The code you entered was incorrect. Go back and try again.');
}
The call to the check method checks the generated CAPTCHA code to the code entered by the user. If the code was incorrect, we use die to stop the script from executing and preventing the form from being submitted. The user must go back and try again.

Now... here's where I run into trouble... I keep trying to place that code somewhere in my page... but the entire site goes down each time. I'm messing it up as I don't know where, in the form processing/error handling code, to place it.

Here's the code from my 'form processor' page.

PHP:
//Contact Process
function contactProcess() {
	$name = $_POST['name'];
	$emailAddress = $_POST['email'];
	$phone1 = $_POST['phone1'];
	$phone2 = $_POST['phone2'];
	$phone3 = $_POST['phone3'];
	$phoneNumber = $phone1.'-'.$phone2.'-'.$phone3;
	$orderNumber = $_POST['order'];
	$message = $_POST['message'];
	$subject = $_POST['subject'];
	
	if (!$_POST['name'] || !$_POST['email'] || !$_POST['message']) {
		$msg = "<strong>ERROR: Missing fields. Please fill all required fields and re-submit the form.</strong>";
		} else {
		
	if(empty($_SESSION['proName'])) {
		$sql = "INSERT INTO tbl_contacts(con_name, con_email, con_phone, con_order, con_subject, con_message, con_date) VALUES('$name', '$emailAddress', '$phoneNumber', '$orderNumber', '$subject', '$message', NOW())";
	} else {
		$sql = "INSERT INTO tbl_contacts(con_name, con_email, con_phone, con_order, con_subject, con_message, con_date, con_des_name) VALUES('$name', '$emailAddress', '$phoneNumber', '$orderNumber', '$subject', '$message', NOW(), '".$_SESSION['proName']."')";
	}

	$result = dbQuery($sql);
	
		{
						
			if(empty($_SESSION['proName'])) {
				
				$to = 'name@MYSITE.com';
				/*
				$to  = 'name@MYSITE.com' . ', '; // comma is intentional
				$to .= 'name@MYSITE.com';
				*/
				//$to = 'email@gmail.com';


			} else {
				$selectDes = "SELECT * FROM tbl_distributor WHERE des_lname = '".$_SESSION['proName']."'";
				$queryResult = dbQuery($selectDes);
				$rowDes = dbFetchAssoc($queryResult);
				$to = $rowDes['des_email'];				
			}
			
			
	//////////////////
$frmtd_name = stripslashes($_POST['name']);
$comments = nl2br(stripslashes($_POST['message']));
$submitted_subject = $_POST['subject'];
$subject = 'Web site contact form inquiry';
$message = '
<html>
<head>
  <title>Web site contact form inquiry</title>
</head>
<body>
<div style="font-family:arial; display:block; width:650px; padding:7px; border:solid 1px navy; background-color:#f3f8f8;">
A new inquiry has just been submitted through the website.<br><br>
<strong>Subject:</strong> '.$submitted_subject.'<br>
<strong>Name:</strong> '.$frmtd_name.'<br>
<strong>Email Address:</strong> '.$emailAddress.'<br>
<strong>Phone Number:</strong> '.$phoneNumber.'<br>
<strong>Order Number:</strong> '.$orderNumber.'<br>
<br>
<strong>Message:</strong><br>
'.$comments.'
<br><br>
<small>System Generated Email</small>
</div>
</body>
</html>
';

$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: '.$frmtd_name.' <'.$emailAddress.'>' . "\r\n";


if (mail($to, $subject, $message, $headers)) {
	
	
	
	
	
	///////////////////
			
			
				$msg = "Your message has been successfully sent";
			} else {
				$msg = "<strong>Error: Message could not be sent</strong>";
			}
			
		}
	} // else - if (!$_POST['name'] || !$_POST['email'] || !$_POST['message'])
	return $msg;
}

function stripText($text) {
$text = strtolower(trim($text));
$clean = ereg_replace("[^A-Za-z0-9\_-]", "", $text);
return $clean;
}

Please help me out... I can only imagine it's a fairly simple task... everyone else on PhpCaptcha had no problem installing. I'm not a PHP guy :( .

Thank you,
Josh
 
Technology news on Phys.org
  • #2
I'm not really a PHP guy-- this stuff looks... incorrectly written to me, honestly. I would have expected the contactProcess() routine to return a success or failure, but instead it returns a text message, which means that the caller behaves the same way regardless of success or failure. ... Which, can work, I guess, but is odd.

I would expect that you need to put in an "elsif" clause after the first "if" statement. So, something like this:

Code:
    ...
    $message = $_POST['message'];
    $subject = $_POST['subject'];
    include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
    $securimage = new Securimage();
    
    if (!$_POST['name'] || !$_POST['email'] || !$_POST['message']) {
        $msg = "<strong>ERROR: Missing fields. Please fill all required fields and re-submit the form.</strong>";
    } elseif ($securimage->check($_POST['captcha_code']) == false) {
        $msg = "<strong>ERROR: Incorrect Captcha.</strong>";
    } else {
    ...

But if that doesn't work, then instead, JUST try the "include_once" directive. If that doesn't work, then you've got something wrong with your directory structure, and you should check your HTTP error log for problems, and make sure that "securimage.php" is really where it's supposed to be, and that all the subsequent files are similarly properly placed.

If adding the "include_once" directive works, then try adding the "new Securimage()" line next. If that doesn't work, you've got a problem with your installation, not sure what. Again, check your HTTP error log for potential error messages that could point you in the right direction.

If that part works, then you're probably fine to add in the "elseif" as shown above. But if not, again, check your HTTP error log. It's probably an installation problem with the particular PHP module.

...

But THAT's not why I'm actually writing this. THIS is:

FIX THIS:
Code:
        if(empty($_SESSION['proName'])) {
            $sql = "INSERT INTO tbl_contacts(con_name, con_email, con_phone, con_order, con_subject, con_message, con_date) VALUES('$name', '$emailAddress', '$phoneNumber', '$orderNumber', '$subject', '$message', NOW())";
        } else {
            $sql = "INSERT INTO tbl_contacts(con_name, con_email, con_phone, con_order, con_subject, con_message, con_date, con_des_name) VALUES('$name', '$emailAddress', '$phoneNumber', '$orderNumber', '$subject', '$message', NOW(), '".$_SESSION['proName']."')";
        }

Just for a moment, consider what would happen if some malicious user tried to enter a message text of:

Code:
This is my message';DROP TABLE tbl_contacts;SELECT 'haHA!

Or, which is more often the case, just some text with an apostrophe, which will cause your SQL to fail. Be sure to trap and escape characters which can break your SQL!

DaveE
 
  • #3
DaveE... what do I replace that code with... the one where someone could mess with my SQL? I'm sorry... I'm a super noob at this!

Thanks a ton in advance... I cannot afford to have the entire DB crash!

Josh
 
  • #4
By the way DaveE... you're the man.. that worked for the CAPTCHA... I copied and pasted that code word for word. Thanks a ton!

Please let me know if you have a suggestion to fix that vulnerability regarding the databases!

Josh
 
  • #5
bigdawg723 said:
Please let me know if you have a suggestion to fix that vulnerability regarding the databases!

I'm not a real PHP guy, so I don't know the details-- But I looked it up here:

http://en.wikibooks.org/wiki/PHP_Programming/SQL_Injection

So, it looks like you should use "mysql_real_escape_string()" for each parameter, or re-write the query so that it's parameterized (but I don't know if you need a database object for that-- they show some sort of "DB" library, I'm not sure if that's standard or what).

DaveE
 

1. What is CAPTCHA and why is it important to implement it in PHP?

CAPTCHA stands for Completely Automated Public Turing test to tell Computers and Humans Apart. It is a security measure used to determine whether a user is a human or a computer program attempting to access a website. It is important to implement CAPTCHA in PHP to prevent automated bots from spamming or hacking a website.

2. How does CAPTCHA work in PHP?

CAPTCHA in PHP works by generating a challenge that is easy for humans to solve but difficult for automated bots. It usually involves displaying distorted characters or images that a user must input correctly to prove their human identity. The input is then validated by comparing it to the original challenge, and if it matches, the user is allowed access to the website.

3. What are the different types of CAPTCHA available in PHP?

There are various types of CAPTCHA available in PHP, such as image-based CAPTCHA, audio-based CAPTCHA, mathematical CAPTCHA, and reCAPTCHA. Image-based CAPTCHA displays distorted images of characters or objects that a user must identify and input correctly. Audio-based CAPTCHA presents a series of spoken letters or numbers that a user must listen to and input correctly. Mathematical CAPTCHA requires the user to solve a simple mathematical equation. reCAPTCHA is a more advanced version that uses a combination of image and audio challenges to verify a user's identity.

4. How can I implement CAPTCHA in PHP on my website?

To implement CAPTCHA in PHP on your website, you can use a pre-existing CAPTCHA library or create your own code. First, you need to generate a challenge and display it on the webpage. Then, you need to validate the user input and compare it to the original challenge. If it matches, you can allow the user to access the website. There are many tutorials and resources available online to help you with the implementation process.

5. Are there any security concerns related to implementing CAPTCHA in PHP?

While CAPTCHA is an effective security measure, it is not foolproof. Some advanced bots may still be able to bypass it. Additionally, some users may find it difficult to solve the challenge, which can lead to frustration. It is important to regularly update and improve your CAPTCHA system to ensure maximum security. Additionally, you can use other security measures, such as IP blocking and rate limiting, to further protect your website from automated attacks.

Similar threads

  • Programming and Computer Science
Replies
6
Views
5K
Replies
1
Views
3K
  • Feedback and Announcements
Replies
7
Views
3K
  • Special and General Relativity
Replies
13
Views
2K
Back
Top