Zumorio
Zumorio

Reputation: 17

Not redirecting if key is valid or not

I'm trying to make a sort of beta key system that validates your key in the system and that redirects you if so.

But when filling in the right key or a random value, it redirects you just to the same page without anything behind it like it should do.

<?php

include("config.php");    
echo "Your IP did not match to a beta key, please fill in one below:<br>";
echo '<form method="post" action="key">';
if (isset($_GET["failed"])) echo "That key has already been used or is invalid.<br>";
echo '<br>';
echo '<input type="text" name="key" placeholder="Beta Key" required=""/>';
echo '<br>';
echo '<button type="submit">Submit</button>';
echo '</form>';

if(isset($_POST['key'])) {
    $retrievekey = $con->prepare("SELECT key FROM keys");
    $retrievekey->execute();
    while ($result = $retrievekey->fetch()) {
        if($_POST['key'] == $result['key']) {
            header("Location: http://admin.gta-o.net/keyvalid");
            // do stuff when the key is valid
            die();
        } else {
            header("Location: http://admin.gta-o.net/key?failed=true");
            die();
        }
    }
}

echo "If you're looking for one please contact us on <i>[email protected]</i> with your name and reason.<br>";
echo "Chance on not getting a reply back is big, this means we have rejected your request.";
?>

Here's how it looks like when submitting a key or a random value, notice it also seems to remove the bottom text when submitting.

Thanks

Upvotes: 0

Views: 55

Answers (1)

Kevin
Kevin

Reputation: 41885

On first iteration it just dies if it does not match. It doesn't have a complete loop on all rows.

Just select that particular key. No need to loop every time and check every row:

mysqli

<?php

include 'config.php';

if(isset($_POST['key'])) {

    $retrievekey = $con->prepare("SELECT `key` FROM `keys` WHERE `key` = ?");
    $retrievekey->bind_param('s', $_POST['key']);
    $retrievekey->execute();

    if($retrievekey->num_rows > 0) {
        header("Location: http://admin.gta-o.net/keyvalid");
    } else {
        header("Location: http://admin.gta-o.net/key?failed=true");
    }

    exit;

}

?>

<form method="POST" action=""> <!-- remove that action="key" -->
    <input type="text" name="key" placeholder="Beta Key" required="" /><br/>
    <button type="submit">Submit</button>
</form>

<p>If you're looking for one please contact us on <i>[email protected]</i> with your name and reason</p><br/>
<p>Chance on not getting a reply back is big, this means we have rejected your request.</p>

Sidenote: I don't know if this is PDO or mysqli, but if its PDO:

$retrievekey = $con->prepare("SELECT `key` FROM `keys` WHERE `key` = :key");
$retrievekey->bindParam(':key', $_POST['key']);

Then,

if($retrievekey->rowCount() > 0) {

Important Note:

EDIT: Both key and keys are MySQL reserved keywords so they must be wrapped with backticks in your query.

Upvotes: 1

Related Questions