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


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

$options = [

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

the insert php


include_once 'connect4.php';

$who = $_POST['who'];
$name = $_POST['name'];
$email = $_POST['email'];
$work = $_POST['work'];  

//loop for each added user
    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);
    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.

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