This is the first time I have been dumbfounded on what to search for to find my answer. I generally don't ever create a post because there are umpteen thousand posts on the internet with my answer; certainly this is no exception. My problem with finding the answer is, I'm not quite sure what to even search for.
The below code works. That's not the problem. My problem is, what if I wanted to run this one thousand times. Surely I do not need to write this entire expression so many times to get the desired affect do I?
I have a feeling it has to do with an array, but I'm still at a point where I understand arrays one day and the next they are greek.
But anyway, long post for a simple question. Hopefully someone can help me out with this.
This is PHP.
$firstname = $validate->stripExcess($firstname);
$lastname = $validate->stripExcess($lastname);
$email = $validate->stripExcess($email);
$password1 = $validate->stripExcess($password1);
$password2 = $validate->stripExcess($password2);
This is the entire page:
<?php
session_start();
require("../classes/uservalidation.php");
$firstname = $lastname = $email = $password1 = $password2 = "";
if($_SERVER['REQUEST_METHOD'] == "POST") {
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$email = $_POST['email'];
$password1 = $_POST['password'];
$password2 = $_POST['verify'];
}
//create validation object
$validate = new userValidation;
//execite stripExcess method $vaidate
$firstname = $validate->stripExcess($firstname);
$lastname = $validate->stripExcess($lastname);
$email = $validate->stripExcess($email);
$password1 = $validate->stripExcess($password1);
$password2 = $validate->stripExcess($password2);
//
$returnValidate = $validate->register($firstname, $lastname, $email, $password1, $password2);
//check if the variable is an array -- (case when returnValidate has an error)
if (is_array($returnValidate)) {
$url = $returnValidate[0];
$errorMessage = $returnValidate[1];
//echo $url;
//exit();
}else{
$url = $returnValidate;
//echo $url;
//exit();
}
//Set the form values to SESSION vairbale to pass around
$_SESSION['fname'] = $firstname;
$_SESSION['lname'] = $lastname;
$_SESSION['email'] = $email;
$_SESSION['password1'] = $password1;
$_SESSION['password2'] = $password2;
//redirect to the correct page based on validate results
header("Location: " . $url, true, 303);
?>
And the class:
<?php
session_start();
require("../classes/uservalidation.php");
$firstname = $lastname = $email = $password1 = $password2 = "";
if($_SERVER['REQUEST_METHOD'] == "POST") {
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$email = $_POST['email'];
$password1 = $_POST['password'];
$password2 = $_POST['verify'];
}
//create validation object
$validate = new userValidation;
//execite stripExcess method $vaidate
$firstname = $validate->stripExcess($firstname);
$lastname = $validate->stripExcess($lastname);
$email = $validate->stripExcess($email);
$password1 = $validate->stripExcess($password1);
$password2 = $validate->stripExcess($password2);
//
$returnValidate = $validate->register($firstname, $lastname, $email, $password1, $password2);
//check if the variable is an array -- (case when returnValidate has an error)
if (is_array($returnValidate)) {
$url = $returnValidate[0];
$errorMessage = $returnValidate[1];
//echo $url;
//exit();
}else{
$url = $returnValidate;
//echo $url;
//exit();
}
//Set the form values to SESSION vairbale to pass around
$_SESSION['fname'] = $firstname;
$_SESSION['lname'] = $lastname;
$_SESSION['email'] = $email;
$_SESSION['password1'] = $password1;
$_SESSION['password2'] = $password2;
//redirect to the correct page based on validate results
header("Location: " . $url, true, 303);
?>
I don't know what are you want, but maybe:
$values = array("firstname", "lastname", "email", "password1", "password2");
foreach($values AS $value) {
$$value = $validate->stripExcess($$value);
}
Yes. If you have quite a few variables you can use an array of variables. Basically, the array is a very common structure in PHP. When you get values from $_GET and $_POST you also work with arrays. Nested Arrays and Arrays of objects, Nested arrays of objects all of these are widely used in php.
Try to var_dump $_GET and $_POST (when you send some values to the server) and analyze how the are formed when they have values.
Related
Before completing registration I wan't to check if all submitted post values aren't empty. The POST values will be assigned to the variables only when all input fields have been filled. Else missingFields will be displayed in the URL.
So what I came up with seems to work, however I wonder if the !empty is actually going through all post values, just like individually checking all post values with !empty. If not, what should be changed?
if (!empty($_POST['first']) && ($_POST['last']) && ($_POST['email']) && ($_POST['password'])) {
// If the posts contain any values, assign them to these variables.
$first_name = $_POST['first'];
$last_name = $_POST['last'];
$mail_address = $_POST['email'];
$password = $_POST['password'];
$hash = hash('sha256', $password); // Password will be hashed.
// Check if the email already exists or not.
$existingUser = 'SELECT * FROM account WHERE sMailaddress = :mail';
$stmt = $pdo->prepare($existingUser);
$stmt->execute([
':mail' => $mail_address
]);
// When no results are found, insert values into database.
if ($stmt->rowCount() == 0) {
$registerUser = 'INSERT INTO account (sFirstname, sLastname, sMailaddress, sPassword)
VALUES (:first_name, :last_name, :mail_address, :pass)';
$stmt = $pdo->prepare($registerUser);
$stmt->execute([
':first_name' => $first_name,
':last_name' => $last_name,
':mail_address' => $mail_address,
':pass' => $hash
]);
header('Location: template/authentication.php?registrationCompleted');
} else {
header('Location: template/authentication.php?alreadyExists');
}
} else {
header('Location: template/authentication.php?missingFields');
}
$first_name = $_POST['first'];
$last_name = $_POST['last'];
$mail_address = $_POST['email'];
$password = $_POST['password'];
$hash = hash('sha256', $password); // Password will be hashed.
$check_1 = "pass";
if (empty($first_name)) {
$check_1 = "fail";
}
if (empty($last_name)) {
$check_1 = "fail";
}
if (empty($mail_address)) {
$check_1 = "fail";
}
if (empty($password)) {
$check_1 = "fail";
}
// other validation and sanitation stuff
if (($check_1 === "pass") && ($stmt->rowCount() == 0)) {
// add to database
}
you can also check user input string length and use regex to better sanitize and validate the form
I have a form submission page that POSTS the fields to a confirmation page that sends an email using PHP but I keep getting blank emails when the page is ran as a stand alone page instead of from the form submission page. The form has 'required', but I want to add a statement to the PHP that stops the process if the $email variable is blank/null.
<?php
// variables start
$team = $_POST['team'];
$manager = $_POST['manager'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$classification = $_POST['classification'];
$registration = $_POST['registration'];
$division = $_POST['division'];
// variables end
// email start
$subject = "Thank you for registering you team";
$message = "<html>...
In addition to stopping the process if the $email variable is blank/null, I also want to redirect the user to our home page.
You should be able to do something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['email'])) {
// variables start
$team = $_POST['team'];
$manager = $_POST['manager'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$classification = $_POST['classification'];
$registration = $_POST['registration'];
$division = $_POST['division'];
// variables end
// email start
$subject = 'Thank you for registering you team';
$message = '<html>...';
} else {
header('Location: https://example.com');
}
Simplest way:
...
// variables end
if( ! (!isset($email) || trim($email) === '') ){
header("Location: homepage.php");
exit();
}
// email start
...
Note the exit() statement after the redirection: without exit() or die() the PHP script could be continue the execution resulting in possible unexpected behaviour.
I am wanting to keep a table log history of executed MySQLI queries and log the specific user who executed a query and date & time the query was executed - on any (all) of my PHP pages.
What is the best way and simplest way to achieve this?
PHP
session_start();
if(!isset($_SESSION["username"])){
header("Location: login.php");
exit(); }
$connection = mysqli_connect("****", "****", "****", "****");
if (!$connection) {
die("Database connection failed: " . mysqli_connect_error());
}
if(isset($_POST['update'])) {
$accountNo = $_GET['ID'];
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
$dob = $_POST['dob'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$town = $_POST['town'];
$postcode = $_POST['postcode'];
Recommendation from a SO user:
However, there are errors with this suggestion ...many.
$query = "UPDATE usertable set firstname = '".$firstname."', surname='".$surname."', dob='".$dob."', email='".$email."', phone='".$phone."', address='".$address."', town='".$town."', postcode='".$postcode."' where accountNo='".$accountNo."'";
$log_action = mysqli_query($connection,$query);
$result = mysqli_query($connection,$query);
if($result) {
define("LOG_FILE", "https://www.*******.com/logfile.txt");
function log_action($action, $data) {
$time = date('Y-m-d h:i:s');
$user = isset($_SESSION['username']) ? $_SESSION['username'] : '';
$message = "$time\tuser=$user\taction=$action\tdata=$data\n";
file_put_contents(LOG_FILE, $message, FILE_APPEND);
}
Write a wrapper library that logs all the mysqli calls that you want to record, e.g.
function my_mysqli_query($link, $query, $resultmode = MYSQLI_STORE_RESULT) {
log_action('mysqli_query', $query);
return mysqli_query($link, $query, $resultmode);
}
function my_mysqli_prepare($link, $query) {
log_action('mysqli_prepare', $query);
return mysqli_prepare($link, $query);
}
...
define("LOG_FILE", "/path/to/logfile.txt");
function log_action($action, $data) {
$time = date('Y-m-d h:i:s');
$user = isset($_SESSION['username']) ? $_SESSION['username'] : '';
message = "$time\tuser=$user\taction=$action\tdata=$data\n";
file_put_contents(LOG_FILE, $message, FILE_APPEND);
}
I've written it to log to a file. You could log to a database table instead, it's just more code in log_action().
Then do a global replace in all your other scripts, replacing mysqli_query with my_mysqli_query, mysqli_prepare with my_mysqli_prepare, and so on. So your code would look like:
if(isset($_POST['update'])) {
$accountNo = $_GET['ID'];
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
$dob = $_POST['dob'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$town = $_POST['town'];
$postcode = $_POST['postcode'];
$query = "UPDATE usertable set firstname = '".$firstname."', surname='".$surname."', dob='".$dob."', email='".$email."', phone='".$phone."', address='".$address."', town='".$town."', postcode='".$postcode."' where accountNo='".$accountNo."'";
$result = my_mysqli_query($connection,$query);
if ($result) {
echo "Update successful";
}
}
For some reason, file_get_contents() is not returning any results.
Here is my code:
$result = file_get_contents('http://localhost/service/service.php?action=register&name='.$name.'&lname='.$lname.'&email='.$email.'&username='.$username.'&password='.$password.'&gender='.$gender.'&mobile='.$mobile.'&address='.$address);
Any suggestions?
You have to encode your variables in order to create a valid URL.
Use the function urlencode().
$name = urlencode($name);
$lname = urlencode($lname);
$email = urlencode($email);
$username = urlencode($username);
$password = urlencode($password);
$gender = urlencode($gender);
$mobile = urlencode($mobile);
$address = urlencode($address);
$result = file_get_contents('http://localhost/service/service.php?action=register&name='.$name.'&lname='.$lname.'&email='.$email.'&username='.$username.'&password='.$password.'&gender='.$gender.'&mobile='.$mobile.'&address='.$address);
I am using below code to encrypt user registration password during registration. But the problem is that I can't get login with same password again, I might be because password in DB is different and encrypted and not same as the password user enter.
<?php
if(isset($_POST['submit'])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
if(!empty($firstname) && !empty($lastname) && !empty($username) && !empty($email) && !empty($password)) {
$firstname = mysqli_real_escape_string($db_connect, $firstname);
$lastname = mysqli_real_escape_string($db_connect, $lastname);
$username = mysqli_real_escape_string($db_connect, $username);
$email = mysqli_real_escape_string($db_connect, $email);
$password = mysqli_real_escape_string($db_connect, $password);
$sql = "SELECT randsalt FROM user ";
$select_randsalt_query = mysqli_query($db_connect, $sql);
if(!$select_randsalt_query) {
die("Query failed".mysqli_error($db_connect));
}
while($row = mysqli_fetch_array($select_randsalt_query)) {
$salt = $row['randsalt'];
///crypt function takes 2 parameter. one from DB
///and other from user input.
// $password = crypt($password, $salt);
}
$sql_register ="INSERT INTO user(user_firstname, user_lastname, username, user_email, user_password, user_role )";
$sql_register .="VALUES('{$firstname}', '{$lastname}', '{$username}', '{$email}', '{$password}', 'Unknown' ) ";
$query_register = mysqli_query($db_connect, $sql_register);
if(!$query_register) {
die("Query failed".mysqli_error($db_connect));
}
$message = "<h3>Your Registration has been Submitted</h3>";
} else {
$message = "<h3>You Can't leave field Empty</h3>";
}
} else {
$message = '';
}
?>
I tried to do something like this in login.php
<?php
if(isset($_POST['submit'])){
$Username = $_POST['Username'];
$Password = $_POST['Password'];
//To prevent SQL injection and store into new variable
$Username = mysqli_real_escape_string($db_connect, $Username);
$Password = mysqli_real_escape_string($db_connect, $Password);
$sql_login = "SELECT * FROM user WHERE username = '{$Username}' ";
$query_login = mysqli_query($db_connect, $sql_login);
if(!$query_login){
die("Query Failed".mysqli_error($db_connect));
}
while($row = mysqli_fetch_assoc($query_login)){
$username = $row['username'];
$user_password = $row['user_password'];
$user_firstname = $row['user_firstname'];
$user_lastname = $row['user_lastname'];
$user_email = $row['user_email'];
$user_role = $row['user_role'];
}
$Password = crypt($Password, $user_password);
///User validation
if( ($Username === $username && $Password === $user_password) && $user_role === "Admin"){
//Using session to store information from db
//Using session from right to left. Right is the variable got from db.
$_SESSION['USERNAME'] = $username;
$_SESSION['PASSWORD'] = $user_password ;
$_SESSION['FIRSTNAME'] = $user_firstname;
$_SESSION['LASTNAME'] = $user_lastname;
$_SESSION['EMAIL'] = $user_email;
$_SESSION['ROLE'] = $user_role;
header("Location: ../admin/index.php");
}else{
header("Location: ../index.php");
}
}
?>
but this is not working. Sorry people I just entered to the PHP world and don't have deep understanding.
Welcome to PHP development. Let me make your life a lot easier:
Regardless of what your tutorial/book/friend said, don't escape strings, use prepared statements instead. They're a lot easier to implement safely and your life becomes a heck of a lot easier. (If you rely on escaping, and you remember to escape 2999 out of 3000 parameters a user can control, you're still vulnerable.)
Instead of mucking about with crypt(), just use password_hash() and password_verify().
There are updated guides everywhere that can explain how to use these features better, but http://www.phptherightway.com is the one the community points to the most.