Tycoon Talk
Become a Big fish!
The number 1 forum for online business!
Post topics, ask questions, share your knowledge.
Tycoon Talk is part of Freelancer.com - find skilled workers online at a fraction of the cost.

PHP Forum


You are currently viewing our PHP Forum as a guest. Please register to participate.
Login



Freelance Jobs

Reply
Is this script secure from sql injection attacks? Also spam?
Old 07-14-2010, 12:02 PM Is this script secure from sql injection attacks? Also spam?
Super Talker

Posts: 106
Trades: 0
It's a script to allow people to sign a petition. It contains some sanitizing of the bariables but I don't know if this is enough.

Also, i want to prevent spam (have included sessions so cant sign more than once if a session still exists) but I want to stop people from posting html links and images if possible but don't know how.

Many Thanks.

Code:
<?php
session_start();
?>

<?php

//-------------------------------
function win_checkdnsrr($host, $type='MX') {
    if (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN') { return; }
    if (empty($host)) { return; }
    $types=array('A', 'MX', 'NS', 'SOA', 'PTR', 'CNAME', 'AAAA', 'A6', 'SRV', 'NAPTR', 'TXT', 'ANY');
    if (!in_array($type,$types)) {
        user_error("checkdnsrr() Type '$type' not supported", E_USER_WARNING);
        return;
    }
    @exec('nslookup -type='.$type.' '.escapeshellcmd($host), $output);
    foreach($output as $line){
        if (preg_match('/^'.$host.'/',$line)) { return true; }
    }
}

// Define
if (!function_exists('checkdnsrr')) {
    function checkdnsrr($host, $type='MX') {
        return win_checkdnsrr($host, $type);
    }
}
/**
Validate an email address.
Provide email address (raw input)
Returns true if the email address has the email
address format and the domain exists.
*/
function validEmail($email)
{
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
                 str_replace("\\\\","",$local)))
      {
         // character not valid in local part unless
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}


//-------------------------------


$msg = '';
// Establish MySQL connection
$conn = mysql_connect("localhost", "");
if (!$conn) {
  $msg = '['.__LINE__.'] Our site is temporarily unavailable.  Please contact us for additional assistance.';
}
// Connect to database
$rs = mysql_select_db("fp", $conn);
if (!$rs) {
  $msg = '['.__LINE__.'] Our site is temporarily unavailable.  Please contact us for additional assistance.';
}





// check to see if user already exists

$email = trim($_POST['email']);
if(!validEmail($email)) {
echo '<font color="#ffffff">You have entered an invalid email address - please press back and enter your email address again.</font>';
}
else {

if(isset($_POST['Submit']) && strlen($msg) == 0) {
  $sql = "SELECT '' FROM signatures";
  $sql .= " WHERE email LIKE '".mysql_real_escape_string(trim($_POST['email']))."' ";
  $sql .= " LIMIT 0,1";

  $result = mysql_query($sql, $conn);

  // Check for whether or not the query returns a result -- a result implies that the email was found
  if(!$result || mysql_num_rows($result) > 0) {
    // Email address already exists, so inform user
    $msg = 'Your have already signed this petition - the email address given already exists';
  } else {
    // Sanitize variables
    $fullname = mysql_real_escape_string(trim($_POST['name']));
    $email = mysql_real_escape_string(trim($_POST['email']));
    $country = mysql_real_escape_string(trim($_POST['country']));
    $comments = mysql_real_escape_string(trim($_POST['comments']));


// check if session already exists - if so, dont allow user to sign petition twice

if (isset($_SESSION['exists']))
{

echo "<font color='#ffffff'> You have already signed this petition</font>";
}

else { //begin else for session

$_SESSION['exists'] = 'youexist';


    // Create the SQL insert query
    $sql = "INSERT INTO signatures (fullname, email, country, comments) VALUES ('". $fullname. "', '". $email ."', '". $country ."', '". $comments . "')";
    $rs = @mysql_query($sql, $conn);

    // Check for errors
    if (mysql_errno($conn) == 0) {

	$sql = "SELECT '' FROM signatures";
        $result = mysql_query($sql, $conn);
	$num_rows = mysql_num_rows($result);


      // Insert was successful, so display success message

      $msg = 'Thank You, your entry has been saved.';
      $msg.= '<a href="php_paging.php">View Signatures</a>';


    } else {
      // An error occurred, so inform the user politely
      $msg = 'There was an error with your signature.  Please notify us at admin and we\'ll be happy to help:';
      $msg .= '<br>'.mysql_error($conn);
    }

  }


}
echo "<font color='#ffffff'>$msg; <br/><br/></font>";
echo "$num_rows people have signed this petition\n";

}//session exists bracket 2

}



?>
gh05 is offline
Reply With Quote
View Public Profile
 
 
Register now for full access!
Old 07-15-2010, 10:07 AM Re: Is this script secure from sql injection attacks? Also spam?
Super Talker

Posts: 106
Trades: 0
btw, I realise there is a lot of code there but it's really just the last bit (inputting into the database) which i need help with. I just want to make sure hackers can't delete entries from my database and that spammers can't repeatedly post junk into it.
Any help will be much appreciated!
Thanks.
gh05 is offline
Reply With Quote
View Public Profile
 
Old 07-21-2010, 12:45 AM Re: Is this script secure from sql injection attacks? Also spam?
vivekar's Avatar
Webmaster Talker

Posts: 612
Trades: 0
Code:
$sql = "SELECT '' FROM signatures";
        $result = mysql_query($sql, $conn);
    $num_rows = mysql_num_rows($result);
I suggest to use the following code to get the number of records.
Code:
SELECT count(1) FROM signatures
Avoid using "SELECT * FROM". It is not recommended.

To thwart spam, a CAPTCHA is required.
__________________

Please login or register to view this content. Registration is FREE
(Active since 2003) |
Please login or register to view this content. Registration is FREE
vivekar is offline
Reply With Quote
View Public Profile Visit vivekar's homepage!
 
Reply     « Reply to Is this script secure from sql injection attacks? Also spam?
 

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off





   
RSS Feed  Feeds: RSS   JS   XML
RSS Feed  Feeds for this forum: RSS   JS   XML



Page generated in 0.19010 seconds with 12 queries