I'm creating a basic sign up form, where I want to validate the user input. I've read a LOT of different methods of doing this. First of all, mine is not working because it echoes "Email is valid" when it is not a valid email. I really wish I could figure out the most efficient, succinct way of doing this!
So my two questions are:
1.) Is there something wrong in my code that says it's a valid email even though it isn't?
2.) How can I make this as efficient as possible?
Here is the code:
<?php
include('functions.php');
$server = "localhost";
$auth = "root";
$pass = "password";
$db = "users";
$conn = connect_to_db($server, $auth, $pass, $db);
$signup = isset($_POST['submit']);
$output = NULL;
if( $signup ){
$username = htmlspecialchars($_POST['username']);
$password = md5($_POST['password']);
$email = $_POST['email'];
if( filter_var($email, FILTER_VALIDATE_EMAIL) && !empty($username) && !empty($password) && !empty($email) ){
echo 'Email is valid';
$sql = "SELECT username FROM info WHERE username = '$username'";
$result = mysqli_query($conn, $sql);
if( mysqli_num_rows($result) > 0 ){
echo "Sorry, there is already an account registered with that username";
} else {
$sql = "INSERT INTO info (username, password, date_created) VALUES ('$username', '$password', NOW())";
mysqli_query($conn, $sql);
$output = "<p> Username: $username <br />" . "Password: $password </p>";
}
} elseif ( empty($username) || empty($password) ) {
$output = "<p> Both fields are required </p>";
}
echo $output;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<form method="POST">
<h1>Signup: </h1><br />
Choose a username: <input type="text" name="username" /> <br />
Choose a password: <input type="password" name="password" /> <br />
Enter your email: <input type="email" name="email" /> <br />
<input type="submit" name="submit" value="Signup" />
<p>Already have an account? Login here: <br /> <a href="index.php">Login</a></p>
</form>
</body>
</html>