Preg_match and some basic security question

Hello, so I’m testing to add some security to my form. I made a pdo connection as recommended, I dont know if I did it ok.

I also added preg_match for special characters. But it works with the first input but not in the second one.

And how do I disable speacial characters in input fields but allow @ in email input?

This is my connection php

<?php

$link = 'mysql:host=localhost;dbname=security;charset=utf8mb4';
$user = 'root';
$pw = '';

$options = [
    PDO::ATTR_EMULATE_PREPARES   => false, 
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, 
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, 
  ];

try{
    //connection
    $pdo = new PDO($link, $user, $pw, $options);         
    } catch (PDOException $e) {
        print "Something weird happened . . ." . $e->getMessage() . "<br/>";
        die();
    }  
?>

the insert php

<?php

include_once 'connect4.php';

if($_POST){
$who = $_POST['who'];
$name = $_POST['name'];
$email = $_POST['email'];
$work = $_POST['work'];  

//loop for each added user
for($i=0;$i<count($name);$i++)
{
    if($name[$i]!=""  && $email[$i]!="" && $work[$i]!="")
 { 
    //filter speacial characters not allowed
    if (preg_match("%^[A-Za-z0-9-_]{3,10}$%", $_POST["who"], $_POST['email'])) {
    $sql_add = 'INSERT INTO testing (who,email,name,work) VALUES (?,?,?,?)';
    $stmt_add = $pdo->prepare($sql_add);
    $stmt_add->execute(array($who,$email[$i],$name[$i],$work[$i]));    
    
    echo 'Saved';
    echo '<br>';
    echo $who;
    echo '<br>';
    echo $email[$i];
    echo '<br>';
    echo $name[$i];
    echo '<br>';
    echo $work[$i];
    echo '<br><br>';
    
    } else {
    echo 'Special characters and long names not allowed';
    }  
 }

}

}

?>

Any recommendations? What else could I add to make this more secure?

You can start with not outputting internal system errors to the user. That info is useless to the user and only good to hackers.

Php has numerous built-in filters, one being for emails.
https://www.php.net/manual/en/filter.filters.validate.php

Stop creating variables for nothing. You already have the POST variables, use them.

Never ever trust user supplied data. You need to use htmlspecialchars when outputting the user data.

1 Like

Thanks a lot for your answer.

Sponsor our Newsletter | Privacy Policy | Terms of Service