Contact form get email address from DB

Hello,
I need a contact form who get email address from sql because each page I have different email address, I tried:

REPLACE THIS:

<?php 
$email ='yourname@your-website.com';// <<===  your email address

By THIS:

<?php
$sql_email = "SELECT EMAIL FROM USERS WHERE ID = '$_GET[get_id]'";

$query = mysql_query($sql_email)or die(mysql_error());

while($r = mysql_fetch_assoc($query )){
    $email = $r['EMAIL'];
}

But it’s get only the ID, now I need the email address. Any ideia?

$sql_email = "SELECT 
EMAIL FROM 
USERS WHERE ID = '" .  $_GET[get_id] . "'";

http://php.net/manual/en/language.operators.string.php

I think that is your problem.


$sql_email = "SELECT EMAIL FROM USERS WHERE ID = '$_GET[get_id]'";
$query = mysql_query($sql_email)or die(mysql_error());
if(mysql_num_rows($query) >= 1){
    $r = mysql_fetch_assoc($query);
    $email = $r['EMAIL'];
}
else{
    echo "no record found with the id provided";
}

This should be enough if the field ‘EMAIL’ is really holding the email address in the table although the query formation can be changed to make it secure. To make sure, just use a condition if it is returning some rows or not or just echo $sql_email variable and run the query outside PHP (phpmyadmin or any mysql client) and see if that works.

This is the complete working code of contact form with CAPTCHA:

<?php
$sql_email = "SELECT EMAIL FROM LISTINGS WHERE ID = '$_GET[get_id]'";
$query = mysql_query($sql_email)or die(mysql_error());
if(mysql_num_rows($query) >= 1){
   $r = mysql_fetch_assoc($query);    
   $email = $r['EMAIL'];
}
else
{    
    echo "no record found with the id provided";
} 	
	$name = $_POST['name'];
	$visitor_email = $_POST['email'];
	$user_message = $_POST['message'];
	///------------Do Validations-------------
	if(empty($name)||empty($visitor_email))
	{
		$errors .= "\
 Name and Email are required fields. ";	
	}
	if(IsInjected($visitor_email))
	{
		$errors .= "\
 Bad email value!";
	}
	if(empty($_SESSION['6_letters_code'] ) ||
	  strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
	{
	//Note: the captcha code is compared case insensitively.
	//if you want case sensitive match, update the check above to
	// strcmp()
		$errors .= "\
 The captcha code does not match!";
	}
	
	if(empty($errors))
	{
		//send the email
		$to = $email;
		$subject="New form submission";
		$from = $email;
		$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
		
		$body = "A user  $name submitted the contact form:\
".
		"Name: $name\
".
		"Email: $visitor_email \
".
		"Message: \
 ".
		"$user_message\
".
		"IP: $ip\
";	
		
		$headers = "From: $from \\r\
";
		$headers .= "Reply-To: $visitor_email \\r\
";
		
		mail($to, $subject, $body,$headers);
		
		header('Location: thank-you.html');
	}
}

// Function to validate against any email injection attempts
function IsInjected($str)
{
  $injections = array('(\
+)',
              '(\\r+)',
              '(\	+)',
              '(%0A+)',
              '(%0D+)',
              '(%08+)',
              '(%09+)'
              );
  $inject = join('|', $injections);
  $inject = "/$inject/i";
  if(preg_match($inject,$str))
    {
    return true;
  }
  else
    {
    return false;
  }
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>
<head>
	<title>Contact Us</title>
<!-- define some style elements-->
<style>
label,a, body 
{
	font-family : Arial, Helvetica, sans-serif;
	font-size : 12px; 
}
.err
{
	font-family : Verdana, Helvetica, sans-serif;
	font-size : 12px;
	color: red;
}
</style>	
<!-- a helper script for vaidating the form-->
<script language="JavaScript" src="scripts/gen_validatorv31.js" type="text/javascript"></script>	
</head>

<body>
<?php
if(!empty($errors)){
echo "<p class='err'>".nl2br($errors)."</p>";
}
?>
<div id='contact_form_errorloc' class='err'></div>
<form method="POST" name="contact_form" 
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>"> 
<p>
<label for='name'>Name: </label><br>
<input type="text" name="name" value='<?php echo htmlentities($name) ?>'>
</p>
<p>
<label for='email'>Email: </label><br>
<input type="text" name="email" value='<?php echo htmlentities($visitor_email) ?>'>
</p>
<p>
<label for='message'>Message:</label> <br>
<textarea name="message" rows=8 cols=30><?php echo htmlentities($user_message) ?></textarea>
</p>
<p>
<img src="captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' ><br>
<label for='message'>Enter the code above here :</label><br>
<input id="6_letters_code" name="6_letters_code" type="text"><br>
<small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small>
</p>
<input type="submit" value="Submit" name='submit'>
</form>
<script language="JavaScript">
// Code for validating the form
// Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
// for details
var frmvalidator  = new Validator("contact_form");
//remove the following two lines if you like error message box popups
frmvalidator.EnableOnPageErrorDisplaySingleBox();
frmvalidator.EnableMsgsTogether();

frmvalidator.addValidation("name","req","Please provide your name"); 
frmvalidator.addValidation("email","req","Please provide your email"); 
frmvalidator.addValidation("email","email","Please enter a valid email address"); 
</script>
<script language='JavaScript' type='text/javascript'>
function refreshCaptcha()
{
	var img = document.images['captchaimg'];
	img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>
<noscript>
Code from the <a href='http://www.html-form-guide.com/contact-form/html-contact-form-captcha.html'
>php contact form</a> article.
</noscript>
</body>
</html>

You need to seriously look at SQL Injection and why you should NEVER use unsanitized variables in code.
At the very least you should be using mysql_real_escape_string($_GET[‘value’]) or you leave yourself wide open to exploitation or a pretty simple empty databse :nono:

Thank you SpikeZ for the advice, but i’m not programmer, I don’t know PHP and I use similar code for youtube videos. Please can you explain with more details about how sinitize my code? Today my sql is empty but I hope soon it will be full and I can’t the risk.

$sql_email = "SELECT EMAIL FROM LISTINGS WHERE ID = '$_GET[get_id]'";
$query = mysql_query($sql_email)or die(mysql_error());
if(mysql_num_rows($query) >= 1){
   $r = mysql_fetch_assoc($query);    
   $email = $r['EMAIL'];
}
else
{    
    echo "no record found with the id provided";
}

Read the following page for security issues that may come along your programming script page.
http://php.net/manual/en/security.database.sql-injection.php

For now you can just be safe enough if you use mysql_real_esacpe_string($_GET[‘get_id’])


$get_id = mysql_real_esacpe_string($_GET['get_id']);
$sql_email = "SELECT EMAIL FROM LISTINGS WHERE ID=' . $get_id . '";
$query = mysql_query($sql_email)or die(mysql_error());
if(mysql_num_rows($query) >= 1){
   $r = mysql_fetch_assoc($query);    
   $email = $r['EMAIL'];
}
else{    
    echo "no record found with the id provided";
}

Sorry in my last post the spelling of the function is wrong. This should be mysql_real_escape_string().

My script is not working anymore…

Please take a look what the developer of my contact form says about email injection:

http://www.html-form-guide.com/contact-form/html-contact-form-captcha.html

But, I’m really scared about what spikeZ says:

exploitation or a pretty simple empty database

Why God just don’t kill bad people and leave us working in peace?

Injection protection is actually just a side effect of doing it properly (which you weren’t). To illustrate:

SELECT * FROM table WHERE field = '$value'

Now if
$value = “O’Rielly”;
Then you end up with

SELECT * FROM table WHERE field = 'O'Rielly'

You can see from the syntax highlighter that there is something wrong. There are certain characters that need to be escaped when used in a mysql query, that is the reason you use mysql_real_escape_string. As a bonus, attackers can no longer inject malicious code into your query :slight_smile:

Ooh, I like questions like this - my answer is that there is no God.

Back to the issue at hand though, for the best example of why you need to learn about the dangers with SQL, and what you can do to protect yourself and your database, please have a good read of SQL Injection Attacks by Example