PHP - Help With Understanding Password_hash
Hi.
I've been trying to understand the concept of password_hash but so far it has eluded me!
registration
<?php if(isset($_POST['submit'])){ $name = $_POST['name']; $email = $_POST['email']; $password = $_POST['password']; //$pass_hash = PassHash::hash($_POST['password']); $hash = password_hash($password, PASSWORD_BCRYPT); $stmt = $pdo->prepare("INSERT INTO hash_test(name, email, password) VALUES(:name, :email, :password)"); $stmt->execute(array( ':name' => $name, ':email' => $email, ':password' => $hash )); if ($stmt->rowCount() ==1){ echo "Registration Successful"; }else{ echo "There was a problem taking your request"; } } ?>The registration is working fine and all fields are inserted. The problem is when loggin in, its giving me an error : unknown variable which is the $hash. The verify parameter is thus: password_verify($password, $hash) I believe the $password is the users password for login, now how/when/where do assign a value to $hash? since in my db i have email(username) password. Do i need to store the hash separately on the db? Can someone please enlighten me more my login code <?php if(isset($_POST['login'])){ $password = $_POST['password']; $stmt = $pdo->prepare("SELECT email, password FROM hash_test WHERE email=:email AND password=:password"); $stmt->execute(array( ':email' => $_POST['email'], ':password' =>$password )); //if ($stmt->rowCount() ==1){ if (password_verify($password, $hash)) { /* Valid */ echo "Right"; } else { /* Invalid */ echo "wrong"; } //} } ?>THANKS Similar TutorialsI copied the code for password_hash at php.net: <?php /** * In this case, we want to increase the default cost for BCRYPT to 12. * Note that we also switched to BCRYPT, which will always be 60 characters. */ $options = [ 'cost' => 12, ]; echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options); ?> and changed it for use in my login page:
$options = ['cost' => 12,]; $user = mysqli_real_escape_string($db_link,$_GET['username']); $pass = password_hash($_GET['password'], PASSWORD_BCRYPT, $options); but my page keeps saying invalid user/pass. Upon echoing the $pass I find that the result changes EACH time. so I created a test page that runs the code from php.net (verbatim code) 20x and I got: [pre]
$2y$10$Nlf0J520viR4C5jd3nIdd.6M3OMKACx503Jm3PiXDYZIs.13XAheq [/pre] Is password_hash broken? or am I mistaken to think that it's supposed to return the same output everytime fror the same input? Edited March 17, 2019 by Karaethontypos corrected I've been puzzling over this all morning. No matter what I do i keep getting these errors: Quote
[01-Oct-2019 21:45:32 UTC] PHP Warning: Use of undefined constant PASSWORD_BCRYPT - assumed ' PASSWORD_BCRYPT' (this will throw an Error in a future version of PHP) in /home/ijwe4nfwf9ei/public_html/blog-approval.php on line 7 Here's my code: <?php echo phpinfo(); $pass=password_hash ("password", PASSWORD_BCRYPT); ?> I checked and I'm using php 7, so why do I keep getting this error? I had it print out my php info so I could check.. https://pyro-creations.com/tester.php I even read the manual and tried the examples and I still get those errors. How can I fix this? [please use code tags.] I have a system that I want to change. I'm attempting to convert a huge project I made with mysql to PDO. I have many cases where I would use a WHILE statement to return a query array. Code: [Select] while($row= mysql_fetch_array($result)){From what I've seen so far, it looks as though I need to use a foreach statement to do the same task. Code: [Select] foreach ($dbh->query($sql) as $row){ Is that correct? Hi, can someone help me figure out why the logo div isn't centering? Code: [Select] <?php require_once("functions.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <style type="text/css"> td { border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; border-top-color: #30C; border-right-color: #30C; border-bottom-color: #30C; border-left-color: #30C; } </style> <link href="doggyTreats.css" rel="stylesheet" type="text/css" /> </head> <body> <?php [color=yellow]logo();[/color] navBar(); echo "<div id=\"mainContent\">"; echo "<form action=\"\" method=\"post\" name=\"catalog\">"; DatabaseConnection(); $query = "SELECT * FROM treats"; $result_set = mysql_query($query) or die(mysql_error()); $i = 0; echo "<table>"; while ($row = mysql_fetch_array($result_set)) { echo"<tr><td width=\"2s00px\"><img src=\"{$row['product_pic']}\" /></td><td width=\"200px\">{$row['product_title']}.<br /><br />{$row['product_Description']}.<br /> Price: \${$row['price']}.<br /><br />Quantity <input name=\"quantity\" type=\"text\" size=\"2\" /></td></tr>"; } echo "<tr>"; echo "<td><input name=\"submit\" type=\"button\" value=\"Proceed to Checkout\" />"; echo "</table>"; echo "</form>"; echo "</div>"; footer(); ?> </body> </html> Code: [Select] #navBar { background-color: #060; width: 200px; padding-top: 50px; padding-bottom: 250px; float: left; } #navBar #menu { margin-right: 6px; } .menuOption { background-image: url(assets/bone2a.gif); background-repeat: no-repeat; padding-bottom: 25px; list-style-type: none; height: 20px; padding-top: 26px; text-align: center; } body { background-color: #0089cc; }[color=yellow] #logo { text-align: center; margin-top: 5px; height: 123px; width: 182px; }[/color] #footer { font-style: italic; text-align: center; } .shoppingCart tr th { padding: 5px; } .shoppingCart tr td { padding: 5px; } #mainContent { width: 350px; margin-top: 30px; } Code: [Select] <?php [color=yellow]function logo() { echo "<div id=\"logo\">"; echo "<img src=\"assets/logo.gif\" alt=\"logo\" />"; echo "</div>"; }[/color] function footer() { echo "<div id = \"footer\">"; echo "Auntie Vic\'s Treatery <br />"; echo "PO Box 34092 <br />"; echo "Clermont, IN 46234 <br />"; echo "317-701-0343 <br />"; echo "<a href=\"mailto:auntievics@gmail.com\">Email Us</a>"; echo "</div>"; } function navBar() { echo "<div id = \"navBar\">"; echo "<ul id=\"menu\">"; echo "<li class=\"menuOption\"><a href=\"index.html\">Home</a></li>"; echo "<li class=\"menuOption\"><a href=\"aboutUs.html\">Management Team </a></li>"; echo "<li class=\"menuOption\"><a href=\"treats.html\">Treats </a></li>"; echo "<li class=\"menuOption\"><a href=\"charities.html\">Supported Charities</a></li>"; echo "<li class=\"menuOption\"><a href=\"order.html\">Orders</a></li>"; echo "</ul>"; echo "</div>"; } ?> Let's see.... You add values to variables but you can declare them before assigning a value... Loops are great - they do things until a specific criteria is met....then I exit or break out of them. Functions are code that do specific tasks (or series of tasks) & can be called upon at any given time during a script. An array is like a....hotel with many different rooms - each room being a different value. I get GET and POST...and know how to use them between pages. Sessions can be used to pass data between pages - they help to keep track of things.... Cookies are like little signatures from your script that you can give to a users browser for any number of reasons. I guess you could say I'm starting to get it. It's only been 4 months. That being said can someone give me a brief and yet simple summary of what a PHP Class is... I have been struggling with understanding sessions and I think I finally understand it, but I want to make sure. Say you had a catalog page with products and A quantity text field. the session code would be something like this: Code: [Select] session_start(); $_SESSION ['product_id']=$product_id; $_SESSION ['quantity']=$quantity; that code would go on the catalog page and the checkout page, right? The only thing I'm not quit clear on is what goes in the [] Hi All I have a basic login system on my site. How would I go about displaying the current logged in user information from the session Id. its quite confusing..... <?php require 'Mysql.php'; class Membership { function validate_user($un, $pwd) { $mysql = New Mysql(); $ensure_credentials = $mysql->verify_Username_and_Pass($un, ($pwd)); if($ensure_credentials) { $_SESSION['status'] = 'authorized'; header("location: ../selfbuild/Controlpanel.php"); } else return "Please enter a correct username and password"; } function log_User_Out() { if(isset($_SESSION['status'])) { unset($_SESSION['status']); if(isset($_COOKIE[session_name()])) setcookie(session_name(), '', time() - 1000); session_destroy(); } } function confirm_Member() { session_start(); if($_SESSION['status'] !='authorized') header("location: login.php"); } } Just need to display the user name at the moment but am kinda not getting how its done. Do I just need <?php session_start(); echo $un Hi All, I'm trying to understand the logic behind this bit of code I found. I (think I) get that it takes an argument which in this case is a number, an checks to see if the array isset, then uses a while loop to loop through the possible values taking each value and placing it into another function which performs some task. What I'm really confused about is how the code is using unset, If I'm correct it's unsetting the incremented value which is the value that should be used in the next iteration, now I know this is not the case, but I don't understand why this is working. I have included the code in the topic and I also wrote a small piece of code to mirror this so I could play around with it in hopes of understanding the logic but it gives me a syntax error in my IDE when I try to unset the incremented value. I know this is probably something really stupid so be kind. <?php define("NUM_0", 0); define("NUM_1", 1); define("NUM_2", 2); define("NUM_3", 3); define("NUM_4", 4); function function_1($position) { static $positions = array(NUM_0, NUM_1, NUM_2, NUM_3, NUM_4,), $index = 0; if (isset($positions[$index])) { while ($position >= $index) { $current_position = $positions[$index]; unset($positions[$index++]); function_2($current_position); } } } function function_2($position) { switch ($position) { case 0: echo '$position equals 0 <br />'; break; case 1: echo '$position equals 1 <br />'; break; case 2: echo '$position equals 2 <br />'; break; case 3: echo '$position equals 3 <br />'; break; case 4: echo '$position equals 4 <br />'; break; } } function_1(NUM_4); [b] [u]output![/u] $position equals 0 $position equals 1 $position equals 2 $position equals 3 $position equals 4 [/b] function test() { static $var_1; $var_1 = 10; if (isset($var_1)) { while ($var_1 >= 0) { $var_2 = $var_1; unset ($var_1++); // syntax error on this line. echo $var_2; } } } test(); ?> I need some help understanding the below syntax (the ? and the colon are throwing me) isset($_POST['cardType']) ? $_POST['cardType'] : ''; Thanks for any help on this .. Frank Hi guys Sorry i keep asking noob questions today... I'm working on something that has a user facing image upload facility. So i'm slowly working through a class to make this as secure as possible. One of the tips online is to use the method "is_uploaded_file ( )". According to php.net - "Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd. " I'm not one to just use things without understanding why. So how exactly could someone get a script to work on an internal file via a browse/upload facility? Can someone explain to me in plain English what is the purpose of imagecreatefromgif?? I read the Manual but am not really understanding what purpose it servers in the larger image rendering process. Also, how should I Error-Handle this function - if at all?! Thanks, Debbie I don't really understand what htmlentities() does and when to use it?! The manual says this... <?php $str = "A 'quote' is <b>bold</b>"; // Outputs: A 'quote' is <b>bold</b> echo htmlentities($str); // Outputs: A &#039;quote&#039; is <b>bold</b> echo htmlentities($str, ENT_QUOTES); ?> 1.) Isn't there a way to print this... Code: [Select] $str = "A 'quote' is <b>bold</b>"; ...as this... Quote A 'quote' is <b>bold</b> That is, WYSIWYG. 2.) When and why would you want this displayed... Quote A 'quote' is <b>bold</b> I am trying to make my code more secure, and I was told to use something like this on all code that comes from the User and needs to be output, but I'm a little lost here... echo ' <div class="userInfo"> <a href="#" class="username"> <strong>' . nl2br(htmlentities($username)) . '</strong> </a>'; Debbie So I have been around the net a few times reading tutorials, watching vids as I try to teach my self php. I have come across a few items that I am having trouble understanding. The first is the use of the % symbol. For example I commonly see the % used in generating random strings of characters. Here is piece of the code I used to generate a random string. What is the purpose of % in this statement. if ($alt == 1) { $rndPKID .= $consonants[(rand() % strlen($consonants))]; $alt = 0; } else { $rndPKID .= $vowels[(rand() % strlen($vowels))]; $alt = 1; } The second is the use of the & or as it is better known. The ampersand symbol. I commonly see it used when declaring a function. function newfunction($var1, &$var2){ //Do Stuff Here. } Can anyone help me understand those 2 symbols purpose and usage in php? Hello, After a user gets input into my Users table in my database, I'm using lastInsertId() to grab the newly created ID and then enter the newly created ID (along with some other stuff) into a separate table. Could this potentially be a problem? In other words, what happens if 2 users on 2 different computers both sign up a the same time? How will be database know which lastInsertId() to use? Here's my current code: $dbWrite->insert('users', $data); $last_id = $dbWrite -> lastInsertId(); // get the ID that was just created $data = array ('course_id' => $_POST['course_id'], 'user_id' => $last_id); $dbWrite->insert('course_enrollment', $data); // Use that new ID in a different table Perhaps there's a way to combine the steps? Thank you for your thoughts... Hi.
I haven't done a lot of OOP. Hardly any really. I've had a go at writing a very small class that outputs a greeting depending on what time of day it is. What do the OOP experts here make of it? What do you like, what do you hate? Is there anything I could do to make it more useful?
Here is the code;
class Greeting { // the __construct didn't do what I originally wanted. Denfine the hour outside the method (I don't know why this is a good/bad idea) /* public function __construct() { $hour_of_day = date('G'); } */ public function callGreetingPhrase() { return $this->getGreetingPhrase(); } // the setter doesn't seem to have a purpose here. I tried using it so that I could pass in a value of my choosing (for testing purposes) can't get it to work though /* public function setGreetingPhrase($value) { $this->hour_of_day = $value; } */ private function getGreetingPhrase() { $hour_of_day = date('G'); if($hour_of_day < 12 ) { // if it's before 12pm $greeting_phrase = "good morning"; } elseif($hour_of_day >= 12 && $hour_of_day < 18 ) { // if it's after 12pm but before 6pm $greeting_phrase = "good afternoon"; } else { // what is left over - after 6pm until midnight $greeting_phrase = "good evening"; } return $greeting_phrase; } } $greeting = new Greeting; echo $greeting->callGreetingPhrase();It annoyed me that I could 't figure out how to use the __constructor here to store the hour. But should that have bothered me? Can someone maybe explain a bit about the setter that I tried to use setGreetingPhrase. I only put it in because I've seen other Classes with one. Could I use a setter method here for anything useful? Any feedback appreciated! I come from a long line of down to earth, hard-up, and linear programmers and I've been introduced to the wonders of web. But now I'm a bit lost. Okay, I know much about programming concepts with experience with C++, C#, and assembly, but I can't seem to tame PHP. I've written some code to act as a sort of framework in the spirit of the M-V-C pattern, but I don't know what's happening to my instantiations! I've been reading up on the help files, documentations, and looking up excellent code, but I still don't know what's happening. I'm totally in the dark. Can someone point me to the light? I create my includes (global variables), and local variables, and even classes, but I seem to lose the instantiation of these objects when I navigate more than three pages from my index. What's happening and how do I avoid this? Hi i'm new to the forum and i'm wondering if anyone here could help me out with the problem i'm having. the script i have uses $_SESSION['userid'] = $users['id']; and i'm not exactly sure how to read that .. any information would be helpful. thanks in advance Code: [Select] $result = mysql_query("SELECT * FROM Chords_Loops_Lyrics ORDER BY MusicFiles_ID ASC"); while($row = @mysql_fetch_array($result)){ $Chords_Loops_Lyrics = array($row['CCL_ID'] => $row['MusicFiles_ID'], $row['Type'], $row['FileName']); } I know I'm doing this wrong, because of the results. How can I assign values to this array, when I do a print r on this, it only spits out the last value. I need to store like 100 of these "chord loops and lyrics" into an array with the values you see in the $row fields. I just can't seem to find how to properly write this in php. Hey guys. I have this code which connect me to the database and displays info in the web. However i do not understand a few lines of it. Code: [Select] <?php while ($query = mysql_fecth_assoc($result)) { $field01 = $result['Name']; $field02 = $result['Username']; ?> Can someone try to explain in they're own, simple words? Thank you. Full code. Code: [Select] <?php $dbhost = ""; $dbuser = ""; $dbpass = ""; $db = ""; $connection = mysql_connect($dbhost, $dbuser, $dbpass); mysql_select_db($db, $connection); $query = 'SELECT * FROM users'; $result = mysql_query($query); while ($query = mysql_fecth_assoc($result)) { $field01 = $result['Name']; $field02 = $result['Username']; echo $field01; echo $field02; } ?> |