I'm just wondering if this has any merit from a security standpoint. Say I have a PHP script that needs to get some stuff from the database. Is it safer all around to write it out in PHP and use a prepared statement that way, is it safer to encapsulate everything in a MySQL stored procedure, or can I actually get any security benefit from using a PHP prepared statement to call a MySQL stored procedure that has a prepared statement in it. Or does it not really matter as long as I user a prepared statement somewhere? Something like the following, but maybe a bit more complex:
PHP:
require 'path/to/login_utils.php';
try {
$username = sanitize_validate_username($_POST['username']); // custom cleaning function from login_utils
$pdo = connect_to_database(); // custom connection function from login_utils
$select = "SELECT `password`
FROM `tbl_login`
WHERE `username`=:username;";
$prepared = $pdo->prepare($select);
$prepared->bindValue(":username", $username);
$prepared->execute();
$result = $prepared->fetchAll(PDO::FETCH_ASSOC);
$prepared->closeCursor();
if (isset($result) && count($result) > 0) {
$password = $result['password'];
}
} catch (PDOException $e) {
die $e->getCode() . ': ' . $e->getMessage();
} finally {
if (isset($pdo)) {
unset($pdo);
}
}
$userpass = $_POST['userpass'];
if (!isset($password) || !password_verify($userpass, $password)) {
die 'Invalid username and password combo';
}
start_authenticated_session(); // custom session starting function from login_utils
echo 'You have been logged in';
exit;
But what if instead of dynamically making that SELECT in PHP, I put it behind a stored procedure with something like this?
MySQL:
DELIMITER $$
CREATE PROCEDURE usp_GetUserPassword(IN @username VARCHAR(255))
this_proc: BEGIN
IF @username IS NULL
THEN LEAVE this_proc;
END IF;
DECLARE @password VARCHAR(64);
PREPARE get_password
FROM 'SET @password = (
SELECT `password`
FROM `tbl_login`
WHERE `username`=?
);';
EXECUTE get_password USING @username;
DEALLOCATE PREPARE get_password;
SELECT @password;
END$$
DELIMITER ;
and then called it in my PHP script, replacing the first SELECT with this:
$select = "CALL usp_GetUserPassword(:username);";
or something like that, and I continued on to prepare and execute $select
in PHP, even though the stored procedure has a prepared statement inside. Would that add any extra security?