简体   繁体   中英

how to send an email when someone logs into mysql

I would like an email sent to me if a someone has logged into the database. My config to connect and log in is below.

     <?php 
session_start();
    require_once('connect.php');

    // Retrieve username and password from database according to user's input
    $input_username = mysql_real_escape_string($_POST['username']);
    $login = mysql_query("SELECT * FROM user WHERE username = '".$input_username."'" ); 

    // Check username and password match
    $row = mysql_fetch_array($login);
    if (mysql_num_rows($login)) {
            if($row['password'] === md5($_POST['password'])){
                 $_SESSION['username'] = $_POST['username']; // store in session
                 $sql = "UPDATE user SET logindate = NOW() WHERE username = '" . mysql_real_escape_string($_SESSION['username']) . "'";
                 mysql_query($sql) or die("Error in SQL: " . mysql_error()); 

    }
    else{
            // Invalid login
            echo header('Location: loginerror.php');
                  exit;
    }
    ?>

You can simply send mails with the PHP mail function.

You may want to add it like this, if you want to recieve an email every time a user logged in:

if ($rowcount == 1) {

    $_SESSION['username'] = $_POST['username'];

    $headers  = "From:Me <no-reply@example.com>\r\n";
    $headers .= "Reply-To: no-reply@example.com\r\n";
    $email_to = "your@emailadress.tld";
    $subject = "Someone logged in!";
    $message = "User ".$_POST['username']." logged in!";
    mail($email_to, $subject, $message, $headers);

    header("Location: securedpage.php");

}

To check whether the mail function was successful or not you can use:

if(mail($email_to, $subject, $message, $headers)) {

    // mail function was successful

} else {

    // error; mail function was NOT successful

}

Edit:

Just a note: You do a query twice and in the second one you don't use escaped data. You should remove your first one and change the second one to the code below. Also use mysql_real_escape string for the password:

$input_password = mysql_real_escape_string($_POST['password']);

$login = mysql_query("SELECT * FROM tbuser WHERE (username = '" . $input_username . "') AND (password = '" . md5($input_password) . "')",$db);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM