How can PHP be used to securely store and retrieve activation codes in a MySQL database?
To securely store and retrieve activation codes in a MySQL database using PHP, you can use methods such as hashing the activation codes before storing them, using prepared statements to prevent SQL injection attacks, and implementing proper error handling to ensure data integrity.
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Generate and hash activation code
$activation_code = "your_activation_code";
$hashed_code = password_hash($activation_code, PASSWORD_DEFAULT);
// Store hashed activation code in database
$stmt = $conn->prepare("INSERT INTO activation_codes (code) VALUES (?)");
$stmt->bind_param("s", $hashed_code);
$stmt->execute();
// Retrieve hashed activation code from database
$stmt = $conn->prepare("SELECT code FROM activation_codes WHERE id = ?");
$id = 1;
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$retrieved_code = $row['code'];
// Verify activation code
if (password_verify($activation_code, $retrieved_code)) {
echo "Activation code is valid";
} else {
echo "Activation code is invalid";
}
// Close database connection
$conn->close();
Keywords
Related Questions
- What are some best practices for efficiently extracting specific content within HTML tags using preg_match_all in PHP?
- Are there any differences in PHP versions that may impact the way form data is accessed using $_POST and $_GET variables?
- What are common mistakes to avoid when handling session data in PHP?