2013-09-24 4 views
1

Я задал несколько вопросов об этом фрагменте кода на этом сайте.

В принципе, моя база данных не обновляется, когда я использую - $ id = $ GET _ ['id']; (вверху кода ниже). Идентификатор передается на эту страницу с предыдущей страницы - URL страницы «http: // www.21orange.com/CCC/changepassword.php?id=1». В моей базе данных есть поле «id».

Когда я меняю приведенную выше строку кода на - $ id = '1' - код работает отлично и база данных обновляется. Он перестает работать, когда я использую $ GET _ ['id']. Почему это?

// First we execute our common code to connection to the database and start the session 
require("common.php"); 

    $id = $_GET['id']; 

// This if statement checks to determine whether the registration form has been submitted 
// If it has, then the registration code is run, otherwise the form is displayed 
if(!empty($_POST)) 
{ 
    // Ensure that the user has entered a non-empty password 
    if(empty($_POST['password'])) 
    { 
     die("Please enter a password."); 
    } 

    // Ensure that the user has entered a non-empty username 
    if(empty($_POST['confirmpassword'])) 
    { 
     // Note that die() is generally a terrible way of handling user errors 
     // like this. It is much better to display the error with the form 
     // and allow the user to correct their mistake. However, that is an 
     // exercise for you to implement yourself. 
     die("Please confirm your password."); 
    } 

    if ($_POST['password'] == $_POST['confirmpassword']) { 

    // An INSERT query is used to add new rows to a database table. 
    // Again, we are using special tokens (technically called parameters) to 
    // protect against SQL injection attacks. 
    $query = "UPDATE Staff SET password=:password, salt=:salt WHERE id=:id"; 

    // A salt is randomly generated here to protect again brute force attacks 
    // and rainbow table attacks. The following statement generates a hex 
    // representation of an 8 byte salt. Representing this in hex provides 
    // no additional security, but makes it easier for humans to read. 
    $salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647)); 

    // This hashes the password with the salt so that it can be stored securely 
    // in your database. The output of this next statement is a 64 byte hex 
    // string representing the 32 byte sha256 hash of the password. The original 
    // password cannot be recovered from the hash. 
    $password = hash('sha256', $_POST['password'] . $salt); 

    // Next we hash the hash value 65536 more times. The purpose of this is to 
    // protect against brute force attacks. Now an attacker must compute the hash 65537 
    // times for each guess they make against a password, whereas if the password 
    // were hashed only once the attacker would have been able to make 65537 different 
    // guesses in the same amount of time instead of only one. 
    for($round = 0; $round < 65536; $round++) 
    { 
     $password = hash('sha256', $password . $salt); 
    } 

    try 
    { 
     // Execute the query to create the user 
     $stmt = $db->prepare($query); 
     $stmt->execute(array(
     'password' => $password, 
     'salt' => $salt, 
     'id' => $id)); 
    } 
    catch(PDOException $ex) 
    { 
     // Note: On a production website, you should not output $ex->getMessage(). 
     // It may provide an attacker with helpful information about your code. 
     die("Failed to run query: " . $ex->getMessage()); 
    } 

    // This redirects the user back to the login page after they register 
    header("Location: stafflist.php"); 

    // Calling die or exit after performing a redirect using the header function 
    // is critical. The rest of your PHP script will continue to execute and 
    // will be sent to the user if you do not die or exit. 
    die("Redirecting to stafflist.php"); 

} 

die("Passwords do not match."); 
} 

Я новичок в php, поэтому простите мою наивность. Постскриптум Я знаю, что метод, который я использую, довольно старая школа, но это всего лишь тест.

Спасибо, Джо

+0

Вызывает ли ошибка, используя одно из сообщений об ошибке или просто не работает? – Mike

+1

Почему вы используете 'GET' для' id', но 'POST' для всего остального? – Sirko

+2

Горячий совет: ** включить отчет об ошибках ** - добавить 'ini_set ('display_errors', 1); error_reporting (E_ALL); 'в начало вашего скрипта. –

ответ

1

Вы не можете сделать как GET и POST в одном HTTP Request.

Однако, вы можете использовать скрытое поле ввода, чтобы обойти это ограничение:

В вашей HTML-разметки, вы можете добавить следующее:

<input type="hidden" name="id" 
      value="<?php echo htmlspecialchars($_GET['id'], ENT_QUOTES); ?>" /> 

И ваш $_GET['id'] должен работать нормально.

+0

Это прекрасно, именно то, что я искал. Большое спасибо – JoeMorgan

+0

@JoeMorgan: Рад, что я мог бы помочь! :) –

+0

Вы помещали параметр в форму «действие» в виде www.21orange.com/CCC/changepassword.php?id=1. Да, вы не можете делать GET и POST в запросе, но вы можете иметь как $ _GET, так и $ _POST со значениями. – DavidLin

0

Чтобы avoide этой ошибки

Undefined index: id in /home/content/47/11368447/html/CCC/changepassword.php on line 6 

первого испытание, если index существует:

if(isset($_GET['id'])) { 
    $id = $_GET['id']; 
} else { 
    // here you can set a value for the id 
} 

В противном случае, вы можете добавить свой $id вар в вашем, если тесте:

if(!empty($_POST) && $id) 
{ 
    //... 
} 
+0

Хорошо, я заменил $ ID = $ _GET ['id']; с приведенным выше. Теперь я получаю ту же ошибку, но в другой строке - «id» => $ id)) ;. – JoeMorgan

+0

это нормально. 'id' не определен в этой строке. См. Мой обновленный ответ! –

+0

, но теперь я не могу использовать $ id где-нибудь в моем коде. Как я могу получить $ id для равного id, отправленного с предыдущей страницы? – JoeMorgan

0

Похоже, вы передаете «id» на URL-адрес действия, но по какой-то причине переменная $ _GET не имеет этого. Пожалуйста, проверьте дважды:

  1. Вы действительно передаете 'id' на URL? Пожалуйста, убедитесь.

  2. Проверьте, есть ли в нем переменная $ _GET в коде common.php.

  3. Это сценарий за настройками перезаписи (например, в .htaccess)? если да, параметры $ _GET могут исчезнуть из-за неправильных настроек перезаписывания. Вы можете протестировать его, поставив print_r ($ _ GET); вначале и непосредственно посетите этот сценарий (GET вместо POST)

+0

(Как указано ниже), когда я повторяю $ id в верхней части страницы, он отображается правильно, после того, как он получает, это URL-адрес. Он просто не использует $ id в запросе – JoeMorgan

0

$ id = $ _GET ['id']; первая проверка есть какое-либо значение в $ ид напечатать $ ID через эхо

+0

Когда я повторяю $ id, он отображает правильный идентификатор в верхней части страницы. – JoeMorgan

Смежные вопросы