I came back to this post this morning to mark as resolved, but I can't find the "mark as resolved" in thread tools.
As it has been awhile since I had used this forum and it is now under new ownership, perhaps things have changed.
How do I mark as resolved?
NNew_PHP_Guy
- Mar 15, 2018
- Joined Jan 28, 2017
@
I didn't understand that undefined meant unusable in this instance.
I thought I was somehow coding it improperly.
I know it's monkey see monkey do, but this is the code I saw used in the video tutorial, so it's not like I pulled it out the air like fetch_a-bucket.
There are many many of us that could benefit from the knowledge of experienced moderators such as yourself.
Have any of you considered doing tutorials?
I would be willing to pay reasonable $$ to learn from professionals that moderate here.@
Thank you for your reply.
The coding I presented in this post was mimic of video tutorial on youtube.
Provided by mmtuts
title:How To Connect To A Database Using PDO PHP | OOP PHP Tutorial | Learn OOP PHP
Published on Jan 9, 2018
https://www.youtube.com/watch?v=yWJFbPT3TC0&t=553s
I thought I was getting up-to-date properly structured coding tutorial. When the fetch_assoc failed to work I did a lot of searches trying to find out why. As a result of thoes searches I had tried the other coding such as PDO::FETCH_ASSOC. No where in my searches did I see mention that fetch_assoc was not usable in PDO query. Thank you. I now know that. So my question is answered as to why it was an undefined method.There should be no application specific values defined inside of any class, i.e. the connection credentials, database name
but accepts the connection credentials, database name, and character set as call time parameters, would be useful.
Can you please point to good example?
Terminate connections like this $stmt = null; $dbh = null; ?
I will study further error handling and naming conventions.Fatal error: Uncaught Error: Call to undefined method PDOStatement::fetch_assoc() in C:\xampp\htdocs\PDO_connection.php:40
Hi. Actually have two part question here. First: in need of help understanding why fetch_assoc() is an undefined method. Why is fetch_assoc considered undefined in my code?
If I use fetch() it does not throw error, however it does display:
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\PDO_connection.php on line 54
I have tried changing the case from lower to upper FETCH_ASSOC(), that did not remedy the problem. I have tried using as PDO::FETCH_ASSOC(), then I get different FATAL error.
I tried adding attribute to my $pdo variable
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
Secondly: Can I assume that I get the Warning on line 54 because $data is empty as a result of the call to undefined method?
My goal was to be able to output/view as many or as few columns of each row as desired.
Code is as follows:<?php //This class is used for connecting to the database. class Dbh { private $servername; private $username; private $password; private $dbname; public function connect() { $this->servername = "localhost"; $this->username = "root"; $this->password = ""; $this->dbname = "miles_away_travel"; $this->charset = "utf8mb4"; try { //set dsn $dsn = 'mysql:host='.$this->servername.';dbname='.$this->dbname.';charset='.$this->charset; //create a PDO instance $pdo = new PDO($dsn,$this->username,$this->password); //also set some attributes after PDO construction with the setAttribute method: $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); return $pdo; } catch (PDOException $e) { echo "<h2>connection failed:</h2> ".$e->getMessage(); } } } //This class is used to query the database class FindUser extends Dbh { protected function seekUser(){ $sql = "SELECT COUNT(*) FROM members"; $result = $this->connect()->query($sql); $numRows = $result->fetchColumn(); //print_r($numRows); if ($numRows >0){ while($row = $result->fetch_assoc()){ $data[] = $row; return $data; //print_r($data); } //return $data; } } } //This class will be used view or use database column data class UserData extends FindUser { public function showData(){ $newData = $this->seekUser(); foreach ($newData as $data) { echo $data['username']."</br>"; echo $data['password']."</br>"; } } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>PDO Connect_Query_Display</title> </head> <body> <?php $showUser = new UserData(); $showUser->connect(); echo $showUser->showData(); ?> </body> </html>
@.
Thanks for taking time to review my code and pointing out the flaws.
Soooooo much to learn.False negatives.
Guess how filter_var works.
I am assuming with regex also.
As per the first part of my previous post, was I understanding correctly?
If I understand this correctly, every time the submit is pressed regardless of which form, it is like the page is being reloaded. This in turn causes the Token generation function which is at the beginning of the script to be called again.
So, what I should do is start a SESSION session_start(); on each page. Create SESSION variables array not global variables.
Since I will have SESSION. I will process email address on one page. Generate token on another page and process token verification on another.
I am not very familiar with working with SESSIONS, which is why I was trying to do all of this on one page to begin with.
I will check out a few tutorials and try to get the hang of it.You know php has a function for this filter_var()
Yes. I am aware of the function. I have read that it is unreliable and that comprehensive regex is better.
Hi. Attempting email address confirmation script. My attempt contains three files: (email_token_test.php)
require_once (gen_email_token.php)
require (PHPMailer-master/PHPMailerAutoload.php)I am expecting the variable $token5 to contain a 5 character string and for that string to remain the same through the whole script. To the best of my limited knowledge I am only calling the token generation function 1 time, but doing several var_dumps on $token5 shows that $token5 is changing as the script progresses.
I know that a standard way of email address confirmation is with user registeration and database population, but in this instance user aren't signing in or registering. They will just be submitting email address for a quote request.
What am I doing wrong and how do I correct it?
I tried several times to post my code but was not able to.
I tried to attach the files with .php extension but was unable to.
I had no choice but to attach as .txt extension, Sorry[ATTACH]5467[/ATTACH][ATTACH]5469[/ATTACH]
Hi. Attempting email address confirmation script. My attempt contains three files: (email_token_test.php)
require_once (gen_email_token.php)
require (PHPMailer-master/PHPMailerAutoload.php)I am expecting the variable $token5 to contain a 5 character string and for that string to remain the same through the whole script. To the best of my limited knowledge I am only calling the token generation function 1 time, but doing several var_dumps on $token5 shows that $token5 is changing as the script progresses.
I know that a standard way of email address confirmation is with user registeration and database population, but in this instance user aren't signing in or registering. They will just be submitting email address for a quote request.
What am I doing wrong and how do I correct it?
gen_email_token.php
require_once "random_compat-2.0.10/lib/random.php"; include "password_compat-1.0.4/lib/password.php"; function generateEmailToken() { try { $string = random_bytes(32); } catch (TypeError $e) { // Well, it's an integer, so this IS unexpected. die("An unexpected error has occurred"); } catch (Error $e) { // This is also unexpected because 32 is a reasonable integer. die("An unexpected error has occurred"); } catch (Exception $e) { // If you get this message, the CSPRNG failed hard. die("Could not generate a random string. Is our OS secure?"); } $myRandomString = (bin2hex($string)); if($myRandomString = (bin2hex($string))){ $randomToken = password_hash($myRandomString, PASSWORD_BCRYPT); //return $randomToken.'<br>'; } if($randomToken = password_hash($myRandomString, PASSWORD_BCRYPT)){ $newRandomToken = substr($randomToken, 7); //return $newRandomToken.'<br>'; } global $token5; if($newRandomToken = substr($randomToken, 7)){ $token5 = substr($newRandomToken, -5); //return $token5.'<br>'; } if($token5 = substr($newRandomToken, -5)){ return $token5; } }
email_token_test.php
require_once "gen_email_token.php"; require "PHPMailer-master/PHPMailerAutoload.php"; global $token5; global $newEmailToken; $newEmailToken = generateEmailToken(); var_dump($token5); if(isset($_POST['submit'])){ //echo 'Submit button pressed!'.'<br>'; print_r($_POST); $postedEmail = null; if($_POST['req-email']){ $postedEmail = $_POST['req-email']; //var_dump($postedemail); //echo $newEmailToken; } if(strlen($postedEmail) === 0){ //Blank string, add error to $errors array. $errors[] = "You must enter your email address."; } if(strlen($postedEmail)<3){ $errors[] = "You have entered an invalid email address."; } // MAKE SURE THE "FROM" EMAIL ADDRESS DOESN'T HAVE ANY NASTY STUFF IN IT $pattern = '/^(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){255,})(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){65,}@)(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22))(?:\.(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\]))$/iD'; if (preg_match($pattern, trim(strip_tags($postedEmail)))) { $cleanedEmail = trim(strip_tags($postedEmail)); //var_dump('<br>'.$cleanedEmail); //echo '<span style="color:green;">Success'.' '.'</span>'.'<b>'.$cleanedEmail.'</b>'.'<span style="color:green;">'.' '.'is a valid Email.'.'<br>'.'</span>'; } else { $errors[] = "The email address you entered was invalid. Please try again!"; //var_dump($errors); } $Email = $cleanedEmail; if(!empty($errors)){ echo '<h1>Error(s)!</h1>'; foreach($errors as $errorMessage){ echo '<span style="color:red;">'.$errorMessage .'</span>'; } } if(empty($errors)){ $message = '<html><body>'; $message .= '<img src="http://res.cloudinary.com/dx1tairmq/image/upload/v1499127233/miles%20away%20travel/newmatlogo_small.png" alt="miles away travel">'; $message .= 'Miles Away Travel has sent an email verification code.'; $message .= '<table rules="all" style="border-color: #666;" cellpadding="10">'; $message .= "<tr><td><strong> Your verification code: </strong></td><td>" . $token5 ."</td></tr>"; $message .= "</table>"; $message .= '<p>Please enter this code in the email Verification form</p>'; $message .= "</body></html>"; $mail = new PHPMailer; //$mail->SMTPDebug = 1; // Enable verbose debug output $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; $mail->Username = 'kentest894@gmail.com'; // set gmail email id $mail->Password = 'My_New_Gmail_894'; // gmail email password $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted $mail->Port = 587; // TCP port to connect to $mail->setFrom('kentest894@gmail.com', 'Miles Away Travel'); $mail->addAddress($Email, 'Ken Smith'); // Add a recipient //$mail->addAddress('kenneth894@hotmail.com' , 'K-man'); // Name is optional $mail->addReplyTo('friend_one_email_Addess', 'Information'); $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'EMAIL verification code'; $mail->Body = $message; $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; if(!$mail->send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } else { echo 'Message has been sent'.'<br>'; } var_dump($token5); function buildform(){ echo '<h3>Your email address must be verified for quote submission.</h3> <form name="e-verify" method="post" action="email_token_test.php" id="form2"> <h3>Email Verification form</h3><br> <label for="req-codeField">ENTER CODE HERE:</label> <input type="text" name="req-codeField" max length="5"/> <input type="submit" name="e-verify-submit" value="verify"/> </form>'; } function show_form(){ echo'<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="form_show.css" type="text/css" media="all" /> </head> <body> <div id="innerdiv"> <?php buildform(); ?> </div> </body> </html>'; } buildform(); show_form(); } var_dump($token5); } if(isset($_POST['e-verify-submit'])){ print_r($_POST); $errors = array(); $postedCode = null; if($_POST['req-codeField']){ $postedCode = $_POST['req-codeField']; $postedCode = trim(stripslashes($postedCode)); //var_dump($postedfname); } if(strlen($postedCode) === 0){ //Blank string, add error to $errors array. $errors[] = "You must enter your verification code."; } if (strlen($postedCode) < 5 || strlen($postedCode) > 5) { $errors[] ='Verification code should contain 5 characters.'; } If ($postedCode === $token5){ echo '<span style="color:green;">Success your email has been verified</span>'; }else{ echo '<span style="color:red;">Email verification has failed. Please contact us by phone.</span>'; } var_dump($postedCode); var_dump($token5); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="form_show.css" type="text/css" media="all" /> </head> <body> <h1>Email Token Test</h1> <form name="e-mail" action="email_token_test.php" method="post" id="form1"> <label for="req-email">Email*:</label> <input type="email" id="req-email" name="req-email" required="required" minlength="3" value="" /> <br> <br> <input type="submit" name="submit" value="submit"/> </form> </body> </html>
Hi. Attempting email address confirmation script. My attempt contains three files: (email_token_test.php)
require_once (gen_email_token.php)
require (PHPMailer-master/PHPMailerAutoload.php)I am expecting the variable $token5 to contain a 5 character string and for that string to remain the same through the whole script. To the best of my limited knowledge I am only calling the token generation function 1 time, but doing several var_dumps on $token5 shows that $token5 is changing as the script progresses.
I know that a standard way of email address confirmation is with user registeration and database population, but in this instance user aren't signing in or registering. They will just be submitting email address for a quote request.
What am I doing wrong and how do I correct it?
gen_email_token.php
require_once "random_compat-2.0.10/lib/random.php"; include "password_compat-1.0.4/lib/password.php"; function generateEmailToken() { try { $string = random_bytes(32); } catch (TypeError $e) { // Well, it's an integer, so this IS unexpected. die("An unexpected error has occurred"); } catch (Error $e) { // This is also unexpected because 32 is a reasonable integer. die("An unexpected error has occurred"); } catch (Exception $e) { // If you get this message, the CSPRNG failed hard. die("Could not generate a random string. Is our OS secure?"); } $myRandomString = (bin2hex($string)); if($myRandomString = (bin2hex($string))){ $randomToken = password_hash($myRandomString, PASSWORD_BCRYPT); //return $randomToken.'<br>'; } if($randomToken = password_hash($myRandomString, PASSWORD_BCRYPT)){ $newRandomToken = substr($randomToken, 7); //return $newRandomToken.'<br>'; } global $token5; if($newRandomToken = substr($randomToken, 7)){ $token5 = substr($newRandomToken, -5); //return $token5.'<br>'; } if($token5 = substr($newRandomToken, -5)){ return $token5; } }
email_token_test.php
require_once "gen_email_token.php"; require "PHPMailer-master/PHPMailerAutoload.php"; global $token5; global $newEmailToken; $newEmailToken = generateEmailToken(); var_dump($token5); if(isset($_POST['submit'])){ //echo 'Submit button pressed!'.'<br>'; print_r($_POST); $postedEmail = null; if($_POST['req-email']){ $postedEmail = $_POST['req-email']; //var_dump($postedemail); //echo $newEmailToken; } if(strlen($postedEmail) === 0){ //Blank string, add error to $errors array. $errors[] = "You must enter your email address."; } if(strlen($postedEmail)<3){ $errors[] = "You have entered an invalid email address."; } // MAKE SURE THE "FROM" EMAIL ADDRESS DOESN'T HAVE ANY NASTY STUFF IN IT $pattern = '/^(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){255,})(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){65,}@)(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22))(?:\.(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\]))$/iD'; if (preg_match($pattern, trim(strip_tags($postedEmail)))) { $cleanedEmail = trim(strip_tags($postedEmail)); //var_dump('<br>'.$cleanedEmail); //echo '<span style="color:green;">Success'.' '.'</span>'.'<b>'.$cleanedEmail.'</b>'.'<span style="color:green;">'.' '.'is a valid Email.'.'<br>'.'</span>'; } else { $errors[] = "The email address you entered was invalid. Please try again!"; //var_dump($errors); } $Email = $cleanedEmail; if(!empty($errors)){ echo '<h1>Error(s)!</h1>'; foreach($errors as $errorMessage){ echo '<span style="color:red;">'.$errorMessage .'</span>'; } } if(empty($errors)){ $message = '<html><body>'; $message .= '<img src="http://res.cloudinary.com/dx1tairmq/image/upload/v1499127233/miles%20away%20travel/newmatlogo_small.png" alt="miles away travel">'; $message .= 'Miles Away Travel has sent an email verification code.'; $message .= '<table rules="all" style="border-color: #666;" cellpadding="10">'; $message .= "<tr><td><strong> Your verification code: </strong></td><td>" . $token5 ."</td></tr>"; $message .= "</table>"; $message .= '<p>Please enter this code in the email Verification form</p>'; $message .= "</body></html>"; $mail = new PHPMailer; //$mail->SMTPDebug = 1; // Enable verbose debug output $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; $mail->Username = 'kentest894@gmail.com'; // set gmail email id $mail->Password = 'My_New_Gmail_894'; // gmail email password $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted $mail->Port = 587; // TCP port to connect to $mail->setFrom('kentest894@gmail.com', 'Miles Away Travel'); $mail->addAddress($Email, 'Ken Smith'); // Add a recipient //$mail->addAddress('kenneth894@hotmail.com' , 'K-man'); // Name is optional $mail->addReplyTo('friend_one_email_Addess', 'Information'); $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'EMAIL verification code'; $mail->Body = $message; $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; if(!$mail->send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } else { echo 'Message has been sent'.'<br>'; } var_dump($token5); function buildform(){ echo '<h3>Your email address must be verified for quote submission.</h3> <form name="e-verify" method="post" action="email_token_test.php" id="form2"> <h3>Email Verification form</h3><br> <label for="req-codeField">ENTER CODE HERE:</label> <input type="text" name="req-codeField" max length="5"/> <input type="submit" name="e-verify-submit" value="verify"/> </form>'; } function show_form(){ echo'<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="form_show.css" type="text/css" media="all" /> </head> <body> <div id="innerdiv"> <?php buildform(); ?> </div> </body> </html>'; } buildform(); show_form(); } var_dump($token5); } if(isset($_POST['e-verify-submit'])){ print_r($_POST); $errors = array(); $postedCode = null; if($_POST['req-codeField']){ $postedCode = $_POST['req-codeField']; $postedCode = trim(stripslashes($postedCode)); //var_dump($postedfname); } if(strlen($postedCode) === 0){ //Blank string, add error to $errors array. $errors[] = "You must enter your verification code."; } if (strlen($postedCode) < 5 || strlen($postedCode) > 5) { $errors[] ='Verification code should contain 5 characters.'; } If ($postedCode === $token5){ echo '<span style="color:green;">Success your email has been verified</span>'; }else{ echo '<span style="color:red;">Email verification has failed. Please contact us by phone.</span>'; } var_dump($postedCode); var_dump($token5); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="form_show.css" type="text/css" media="all" /> </head> <body> <h1>Email Token Test</h1> <form name="e-mail" action="email_token_test.php" method="post" id="form1"> <label for="req-email">Email*:</label> <input type="email" id="req-email" name="req-email" required="required" minlength="3" value="" /> <br> <br> <input type="submit" name="submit" value="submit"/> </form> </body> </html>
@ Thank you for your reply.
The value will never be the literal string 'NULL' (what your code is testing for now), nor will it ever normally be a php NULL value, so, there's no good reason to test against a null value. If the 1st/default option choice is actually a prompt to make a selection and its value in an empty string - '', you would test if the submitted value is an empty string when the form field is 'required'
This would not be the literal string "NULL" ?
<select name="req-state" class="required" value="" /><option value="NULL">Please select your state</option>
Can someone tell me which of these two methods would be best.
Or perhaps suggest another method.if (isset($_POST['Submit'])) { if(isset($_POST['req-state'])) { if($_POST['req-state'] ! == 'NULL') && ($_POST['req-state'] ! == ""){ $_POST['req-state'] = filter_var($_POST['req-state'], FILTER_SANITIZE_STRING); if ($_POST['req-state'] == "") { $errors .= 'Please enter a valid state.<br/><br/>'; } else { echo '<p>You have selected: <strong>', $_POST['state'], '</strong>.</p>'; } } }
if(isset($_POST['req-state']) { if($_POST['req-state'] ! == 'NULL') && ($_POST['req-state'] ! == "") { $_POST['req-state'] = $newState; } if(!in_array($newState, array("Alabama", "Alaska", "Arizona" "rest of the states"))) { $errors .= 'Please enter a valid state.<br/><br/>'; } else { echo '<p>You have selected: <strong>', $newState, '</strong>.</p>'; } }
So, in summary.
Yes. Salted sha1 hash can be tested locally, if coded properly (call the function!).
Testing locally does not require https: , but should be used in production.
The best method of token generation is random_bytes().
If php 7 is not available, need backward compatability library to use random_bytes().
Finally, It is best for the developer to research each component of the code to determine it's present useability and effectiveness.
Sorry, I obviously did not do the proper research.
I do believe that posting here does tend to lead one to resources they otherwise wouldn't know exist.Again thanks to all for your attention in this matter.
All along most of you were pointing me towards password_hash() , not available until php version 5.5 . Thank you for steering me in the right direction.
I am using an older machine and OS so I can only run php version 5.4.31
Further research has led me to libraries such as random_compat-2.0.10 & password_compat-1.0.4
These will allow me to use random_bytes() or password_hash() which I believe will be sufficient for token generation. If I am mistaken in my belief, someone please let me know.One other question. Is there any desireable gain if I seed Password_hash() with random_bytes() ?
Or should I just seed with a static password and rely on the random salts that password_hash generates? Check this script.session_start(); require_once "random_compat-2.0.10/lib/random.php"; include "password_compat-1.0.4/lib/password.php"; function generateFormToken($form) { try { $string = random_bytes(32); } catch (TypeError $e) { // Well, it's an integer, so this IS unexpected. die("An unexpected error has occurred"); } catch (Error $e) { // This is also unexpected because 32 is a reasonable integer. die("An unexpected error has occurred"); } catch (Exception $e) { // If you get this message, the CSPRNG failed hard. die("Could not generate a random string. Is our OS secure?"); } $myRandomString = (bin2hex($string)); $token = password_hash($myRandomString, PASSWORD_BCRYPT); $_SESSION[$form.'_token'] = $token; return $token; } $newToken = generateFormToken('form1'); echo $newToken; /*in hidden form input*/
Yes. "lightning" in my original post. I was just using "lightning" for test purpose. In my last reply $inText = md5(uniqid(microtime(), true));.
So would having md5 hash of microtime and random generated salt added to sha256 hash of microtime be better than password_hash?Thank you all for your replies.
I am learning here.
That reference to OWASP will be very useful. Didn't know it existed.
I originally asked the question because I was not getting anything from the script.
I am using an older computer with older version of windows and xampp and wasn't sure if they were compatabile with sha1. My mistake was pointed out. I was not actually calling the function. Now that I have called the function I see it works with sha1 & sha256.Is salting depricated when creating tokens not passwords?
My plan was to generate the token by using the above script and using the $inText variable like this.
$inText = md5(uniqid(microtime(), true));
I would then store that token in a session variable and in a hidden form input. Then compare them when the form is submitted.
Would using the above script with sha256 and randomly generated salt be better than password_hash ? If not. Why?
I also plan to include script to check for input names that don't match the one that are in this form.
Validate the url.
Filter the input values.
And finally add google reCaptcha to the form and script.I am attempting to add some form security using a salted sha1 hash which I plan to use as a form security token.
I am very new to these concepts and trying to test locally.
Can I test this script locally with xampp?
Do I somehow have to have https: in xampp?
I have tried to echo the $output variable, but just get a blank page.
When I run the script I don't get any errors.$inText = ('lightning'); function createHash($inText, $saltHash=NULL, $mode='sha1'){ // hash the text // $textHash = hash($mode, $inText); // set where salt will appear in hash // $saltStart = strlen($inText); // if no salt given create random one // if($saltHash == NULL) { $saltHash = hash($mode, uniqid(rand(), true)); } // add salt into text hash at pass length position and hash it // if($saltStart > 0 && $saltStart < strlen($saltHash)) { $textHashStart = substr($textHash,0,$saltStart); $textHashEnd = substr($textHash,$saltStart,strlen($saltHash)); $outHash = hash($mode, $textHashEnd.$saltHash.$textHashStart); } elseif($saltStart > (strlen($saltHash)-1)) { $outHash = hash($mode, $textHash.$saltHash); } else { $outHash = hash($mode, $saltHash.$textHash); } // put salt at front of hash // $output = $saltHash.$outHash; return $output; }
I noticed the script had the smtp debug set to zero, I will set debugging on and experiment a bit.
These are in the script.
$mail->isSMTP();
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;Thank you for pointing that out.
A little dyslexia can really muck things up.
This has resolved my problem with the native sendmail, it tests fine.
However, still can't get PHPMailer to work.
Will PHPMailer work on localhost if configured correctly? or does it have to be used on live host?I have been trying for several days to configure send mail and PHPmailer to use smpt through gmail and failing miserably. I have searched the web extensively trying to come up with a solution. Most of the solutions involve changing sendmail.ini & php.ini settings, all of which I have tried and have not been able to resolve the issue. I have tried this with a couple different scripts and get the same result. This leads me to believe that is somehow a problem with gmail. trying to use scripts from here: https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form
My sendmail error log reads as follows: 17/08/01 19:26:15 : Socket Error # 11001<EOL>Host not found.
My sendmail debug log reads as follows: 17/08/01 19:26:12 Name: Rusty
17/08/01 19:26:12 Surname: Nail
17/08/01 19:26:12 Email: rusty@mydomain.com
17/08/01 19:26:12 Phone: 123-456-7890
17/08/01 19:26:12 Message: Rusty is testing this form
17/08/01 19:26:12
17/08/01 19:26:12 --- MESSAGE END ---
17/08/01 19:26:12 Connecting to smpt.gmail.com:587
17/08/01 19:26:15 Disconnected.
17/08/01 19:26:15 Disconnected.
17/08/01 19:26:15 Disconnected.
17/08/01 19:26:15 Socket Error # 11001<EOL>Host not found.[SMPT SERVER TEST]
2017-08-01 02:33:45 Connection: opening to smpt.gmail.com:587, timeout=30, options=array ( ) 2017-08-01 02:33:47 Connection failed. Error #2: stream_socket_client(): php_network_getaddresses: getaddrinfo failed: No such host is known. [C:\xampp\htdocs\contact-form\contact-form\PHPMailer-master\class.smtp.php line 294] 2017-08-01 02:33:47 Connection failed. Error #2: stream_socket_client(): unable to connect to smpt.gmail.com:587 (php_network_getaddresses: getaddrinfo failed: No such host is known. ) [C:\xampp\htdocs\contact-form\contact-form\PHPMailer-master\class.smtp.php line 294] 2017-08-01 02:33:47 SMTP ERROR: Failed to connect to server: php_network_getaddresses: getaddrinfo failed: No such host is known. (0) SMTP error: Connect failedI will include my sendmail.ini and php.ini mailfunction settings.
Note: I have put XXXXXXX where my gmail account and password are for this post.
The actual ini files contain the real gmail acct & password.
I will also include html & php files if required.[sendmail]
; you must change mail.mydomain.com to your smtp server,
; or to IIS's "pickup" directory. (generally C:\Inetpub\mailroot\Pickup)
; emails delivered via IIS's pickup directory cause sendmail to
; run quicker, but you won't get error messages back to the calling
; application.smtp_server=smpt.gmail.com
; smtp port (normally 25)
smtp_port=587
; SMTPS (SSL) support
; auto = use SSL for port 465, otherwise try to use TLS
; ssl = alway use SSL
; tls = always use TLS
; none = never try to use SSLsmtp_ssl=auto
; the default domain for this server will be read from the registry
; this will be appended to email addresses when one isn't provided
; if you want to override the value in the registry, uncomment and modify;default_domain=mydomain.com
; log smtp errors to error.log (defaults to same directory as sendmail.exe)
; uncomment to enable loggingerror_logfile=error.log
; create debug log as debug.log (defaults to same directory as sendmail.exe)
; uncomment to enable debuggingdebug_logfile=debug.log
; if your smtp server requires authentication, modify the following two lines
auth_username=XXXXXX@gmail.com
auth_password=XXXXXXXXXX; if your smtp server uses pop3 before smtp authentication, modify the
; following three lines. do not enable unless it is required.pop3_server=
pop3_username=
pop3_password=; force the sender to always be the following email address
; this will only affect the "MAIL FROM" command, it won't modify
; the "From: " header of the message contentforce_sender=XXXXXX@gmail.com
; force the sender to always be the following email address
; this will only affect the "RCTP TO" command, it won't modify
; the "To: " header of the message contentforce_recipient=
; sendmail will use your hostname and your default_domain in the ehlo/helo
; smtp greeting. you can manually set the ehlo/helo name if requiredhostname=
[mail function]
; XAMPP: Comment out this if you want to work with an SMTP Server like Mercury
SMTP = smpt.gmail.com
smtp_port = 587; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = XXXXXX@gmail.com; XAMPP IMPORTANT NOTE (1): If XAMPP is installed in a base directory with spaces (e.g. c:\program filesC:\xampp) fakemail and mailtodisk do not work correctly.
; XAMPP IMPORTANT NOTE (2): In this case please copy the sendmail or mailtodisk folder in your root folder (e.g. C:\sendmail) and use this for sendmail_path.
; XAMPP: Comment out this if you want to work with fakemail for forwarding to your mailbox (sendmail.exe in the sendmail folder)
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"; XAMPP: Comment out this if you want to work with mailToDisk, It writes all mails in the C:\xampp\mailoutput folder
;sendmail_path="C:\xampp\mailtodisk\mailtodisk.exe"; Force the addition of the specified parameters to be passed as extra parameters
; to the sendmail binary. These parameters will always replace the value of
; the 5th parameter to mail(), even in safe mode.
;mail.force_extra_parameters =; Add X-PHP-Originating-Script: that will include uid of the script followed by the filename
mail.add_x_header=Off; Log all mail() calls including the full path of the script, line #, to address and headers
mail.log = "C:\xampp\php\logs\php_mail.log"Thank you for looking at this.