how to change from mysql to mysqli - php

i change the server from php 5.2 to php 7.3 & from centos 6 to centos 7.3 , i use also smarty
when i upgrade the host the code not working
i cant login to admin dashboard
its give error " Invalid username/password entered. "
can any please help
if ($_SESSION['ADMINID'] != "" && $_SESSION['ADMINUSERNAME'] != "" && $_SESSION['ADMINPASSWORD'] != "")
{
$redirect = $config['adminurl']."/home.php";
header("location: $redirect");
}
else
{
if($_POST['login']!="")
{
$adminusername = cleanit($_POST['username']);
$adminpassword = cleanit($_POST['password']);
if ($adminusername == "")
{
$error = "Error: Username not entered.";
}
elseif ($adminpassword == "")
{
$error = "Error: Password not entered.";
}
else
{
$encodedadminpassword = md5($adminpassword);
$query="SELECT * FROM administrators WHERE username='".mysqli_real_escape_string($adminusername)."' AND password='".mysqli_real_escape_string($encodedadminpassword)."'";
$executequery=$conn->execute($query);
$getid = $executequery->fields['ADMINID'];
$getusername = $executequery->fields['username'];
$getpassword = $executequery->fields['password'];
if (is_numeric($getid) && $getusername != "" && $getpassword != "" && $getusername == $adminusername && $getpassword == $encodedadminpassword)
{
$_SESSION['ADMINID'] = $getid;
$_SESSION['ADMINUSERNAME'] = $getusername;
$_SESSION['ADMINPASSWORD'] = $encodedadminpassword;
$redirect = $config['adminurl']."/home.php";
header("location: $redirect");
}
else
{
$error = "Invalid username/password entered.";
}
}
}
STemplate::assign('message',$message);
STemplate::assign('error',$error);
STemplate::display('administrator/index.tpl');
}
problem in below
$encodedadminpassword = md5($adminpassword);
$query="SELECT * FROM administrators WHERE username='".mysqli_real_escape_string($adminusername)."' AND password='".mysqli_real_escape_string($encodedadminpassword)."'";
$executequery=$conn->execute($query);
$getid = $executequery->fields['ADMINID'];
$getusername = $executequery->fields['username'];
$getpassword = $executequery->fields['password'];

Related

how to validate one variable either of two variables in php

i have two variables mobile and email now i want to validate both but i want the user to leave blank one of the fields if user does not have one for ex if a user does not want to register with his email then he can go to mobile number for registration and vice versa this is my validation code
<?php
$emailError = "";
$fullnameError = "";
$usernameError = "";
$passwordError = "";
$mobileerror = "";
$errors = 0;
if ((isset($_POST['submit']))) {
$email = strip_tags($_POST['email']);
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$mobile = strip_tags($_POST['mobile']);
$fullname_valid = $email_valid = $mobile_valid = $username_valid = $password_valid = false;
if (!empty($fullname)) {
if (strlen($fullname) > 2 && strlen($fullname) <= 30) {
if (!preg_match('/[^a-zA-Z\s]/', $fullname)) {
$fullname_valid = true;
# code...
} else {
$fullnameError = "fullname can contain only alphabets <br>";
$errors++;
}
} else {
$fullnameError = "fullname must be 2 to 30 char long <br>";
$errors++;
}
} else {
$fullnameError = "fullname can not be blank <br>";
$errors++;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$query2 = "SELECT email FROM users WHERE email = '$email'";
$fire2 = mysqli_query($con, $query2) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire2) > 0) {
$emailError = $email . "is already taken please try another one<br> ";
} else {
$email_valid = true;
}
# code...
} else {
$emailError = $email . "is an invalid email address <br> ";
$errors++;
}
# code...
if ($mobile) {
$query4 = "SELECT mobile FROM users WHERE mobile = '$mobile'";
$fire4 = mysqli_query($con, $query4) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire4) > 0) {
$mobileerror = "is already taken please try another one<br> ";
} else {
$mobile_valid = true;
}
}
if (!empty($username)) {
if (strlen($username) > 4 && strlen($username) <= 15) {
if (!preg_match('/[^a-zA-Z\d_.]/', $username)) {
$query = "SELECT username FROM users WHERE username = '$username'";
$fire = mysqli_query($con, $query) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire) > 0) {
$usernameError = '<p style="color:#cc0000;">username already taken</p>';
$errors++;
} else {
$username_valid = true;
}
} else {
$usernameError = "username can contain only alphabets <br>";
$errors++;
}
} else {
$usernameError = "username must be 4 to 15 char long <br>";
$errors++;
}
} else {
$usernameError = "username can not be blank <br>";
$errors++;
}
if (!empty($password)) {
if (strlen($password) >= 5 && strlen($password) <= 15) {
$password_valid = true;
$password = md5($password);
# code...
} else {
$passwordError = $password . "password must be between 5 to 15 character long<br>";
$errors++;
}
# code...
} else {
$passwordError = "password can not be blank <br>";
$errors++;
}
//if there's no errors insert into database
if ($errors <= 0) {
if ($fullname_valid && ($email_valid || $mobile_valid )&& $password_valid && $username_valid) {
$query = "INSERT INTO users(fullname,email,username,password,avatar_path) VALUES('$fullname','$email','$username','$password','avatar.jpg')";
$fire = mysqli_query($con, $query) or die("can not insert data into database" . mysqli_error($con));
if ($fire) {
header("Location: dashboard.php");
}
}
}
}
?>
now when i use email and leave blank mobile the code works fine but when i use email and leave blank mobile then error occurs how to solve this problem
Use one more flag
$isValid_email_mobile = FALSE;
When control flow enters into if (filter_var($email, FILTER_VALIDATE_EMAIL)) then on SUCCESS just set $isValid_email_mobile = TRUE; It will be same if control enters in condition if ($mobile) again on SUCCESS , set it as $isValid_email_mobile = TRUE;
When $isValid_email_mobile = FALSE; becomes TRUE then you know that of the field/variable has passed your requirement and its ready for DB INSERT
Then
In your last IF condition when you try to INSERT just change IF condition to the following
IF ($fullname_valid && $isValid_email_mobile && $password_valid && $username_valid)
One more thing whenever you are using Flag logic always set your flag to some default value before using it.
now when i use email and leave blank mobile the code works fine but when i use email and leave blank mobile then error occurs
you have:
if (!empty($fullname)) {}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {}
if ($mobile) {}
if (!empty($username)) {}
if (!empty($password)) {}
To remove the error, try adding
if (!empty($mobile)) {
Also, I would suggest to wrap the statements a bit more. You only need one to fail in order to stop input. You could do something like this:
$mobileOrEmail = false;
if (!empty($fullname) && !empty($username) && !empty($password) {
//check fullname, username and password
if (!empty($mobile) {
//check mobile, if it passes
$mobileOrEmail = true;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
//check email, if it passes
$mobileOrEmail = true;
}
if (!$mobileOrEmail) $errors++;
} else {
//missing input values
$errors++;
}
Personally, I would create a function for each input field.
function checkUsername($username){
//check username
return true;
}
function checkEmail($email) {
//check email
return true;
}
....
then you can run
if (checkUsername($username) && checkPassword($password)
&& checkFullname($fullname) && (checkEmail($email) || checkEmail($email)) {
//user input correct
} else {
//user input failed
}
Just to give it more structure

header and redirect in php

my problem is in my add-post page when i submit redirect isnt done and header()seems doesnt work
public function insert($query){
$insertRecord = $this->link->query($query) or die($this->link->error.__LINE__);
if($insertRecord){
header("Location:admin/index.php?msg=".urlencode('Record Added'));
exit();
} else {
die("Error : (".$this->link->errno.')'.$this->link->error);
}
}
if($title == "" || $body == "" || $category == "" || $author == ""){
$error = "please fill all required fields";
} else {
$query = "insert into posts(category,title,body,author,tags) values ('$category','$title','$body','$author','$tags')";
$insertRecord = $db->insert($query);
}
header('Location: admin/index.php?msg='.urlencode('Record Added'));

User Login Error

(Sorry if this is a nooby question - I am new to PhP)
So I've got the registration page set up nicely, and with it adding to the MySQL database, however, when i go to login with the correct details I get the error:
PHP Fatal error: Call to undefined method User::authenticate() in
here's my ClassUser code
`
function __construct() {
if(session_id() == "") {
session_start();
}
if (isset($_SESSION['isLoggedIn']) && $_SESSION['isLoggedIn'] == true) {
$this->_initUser();
}
}//end__construct
public function autheniticate($user,$pass) {
$mysqli = new mysqli(DBHOST,DBUSER,DBPASS,DB);
if ($mysqli->connect_errno) {
error_log("Cannot connect to MySQL: " . $mysqli->connect_error);
return false;
}
$safeUser = $mysqli->real_escape_string($user);
$incomingPassword = $mysqli->real_escape_string($pass);
$query = "SELECT * from Customer WHERE email = '{$safeUser}'";
if (!$result = $mysqli->query($query)) {
error_log("Cannot retrieve account for {$user}");
return false;
}
//Will be obly one row, so no while() loop needed
$row = $result->fetch_assoc();
$dbPassword = $row['password'];
if (crypt($incomingPassword, $dbPassword) != $dbPassword ) {
error_log("Passwords for {user} don't match");
return false;
}
$this->id = $row['id'];
$this->username = $row['username'];
$this->isLoggedIn = true;
$this->_setSesstion();
return true;
}//end function authenticate
private function _setSession() {
if(session_id() == '') {
session_start();
}
$_SESSION['id'] = $this->id;
$_SESSION['username'] = $this->username;
$_SESSION['isLoggedIn'] = $this->isLoggedIn;
}//end function setSession
private function _initUser() {
if(session_id() == '') {
session_start();
}
$this->id = $_SESSION['id'];
$this->username = $_SESSION['username'];
$this->isLoggedIn = $_SESSION['isLoggedIn'];
}//end function initUser
}//end classUser
?>`
and here's my login process code;
`
require_once('functions.inc');
//prevent access if they haven't submitted the form
if (!isset($_POST['submit'])) {
die(header("Location: login.php"));
}
$_SESSION['formAttempt'] = true;
if(isset($_SESSION['error'])) {
unset($_SESSION['error']);
}
$_SESSION['error'] = array();
$required = array("username","password");
//Check required fields
foreach ($required as $requiredField) {
if (!isset($_POST[$requiredField]) || $_POST[$requiredField] == "") {
$_SESSION['error'][] = $requiredField . " is required.";
}
}
if (count($_SESSION['error']) > 0) {
die(header("Location: login.php"));
} else {
$user = new User;
if($user->authenticate($_POST['email'],$_POST['password'])) {
unset($_SESSION['formAttempt']);
die(header("Location: authenticated.php"));
} else {
$_SESSION['error'][] = "There was a problem with your username and password.";
die(header("Location: login.php"));
}
}
?>
`
`
//Prevent access if they haven't submitted the form
if (!isset($_POST['submit'])) {
die(header("Location: register.php"));
}
$_SESSION['formAttempt'] = true;
if (isset($_SESSION['error'])) {
unset($_SESSION['error']);
}
$_SESSION['error'] = array();
$required = array("username", "password1", "password2");
//Check Required Fields
foreach ($required as $requiredField) {
if(!isset($_POST[$requiredField]) || $_POST [$requiredField] == "") {
$_SESSION['error'][] = $requiredField . "is required.";
}
}
if(!preg_match('/^[\w.]+$/',$_POST['username'])) {
$_SESSION['error'][] = "Username must only contain numbers and letters.";
}
if(!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) {
$_SESSION['error'][] = "Invalid email address";
}
if($_POST['password1'] != $_POST['password2']) {
$_SESSION['error'][] = "Passwords do not match";
}
//Final disposition
if (count($_SESSION['error']) > 0) {
die(header("Location: register.php"));
} else {
if(registerUser($_POST)) {
unset($_SESSION['formAttempt']);
die(header("Location: register-success.php"));
} else {
error_log("Problem registering user: {$_POST['email']}");
$_SESSION['error'][] = "Problem registering account";
die(header("Location: register.php"));
}
}
function registerUser ($userData) {
$mysqli = new mysqli(DBHOST,DBUSER,DBPASS,DB);
if($mysqli->connect_errno) {
error_log("Cannot connect to mySQL: " . $mysqli->connect_error);
return false;
}
$email = $mysqli->real_escape_string($_POST['email']);
//Check for an existing user
$findUser = "SELECT id from Customer where email = '{$email}'";
$findResult = $mysqli->query($findUser);
$findRow = $findResult->fetch_assoc();
if(isset($findRow['id']) && $findRow['id'] != "") {
$_SESSION['error'][] = "A user with that email address already exists";
return false;
}
$username = $mysqli->real_escape_string($_POST['username']);
$cryptedPassword = crypt($_POST['password1']);
$password = $mysqli->real_escape_string($cryptedPassword);
$query = "INSERT INTO Customer (email,create_date,password,username) " .
"VALUES('{$email}',NOW(), '{$password}', '{$username}')";
if($mysqli->query($query)) {
$id = $mysqli->insert_id;
error_log("Inserted ($email) as id ($id)");
return true;
} else {
error_log("Problem inserting {$query}");
return false;
}
}
?>`
any help would be greatly appreciated! Thank you
Your defined function name is:
// You are misspelling "authenticate"
autheniticate($user,$pass)
but you are calling:
authenticate()

Session not working on wamp but works on live server

I have this code and I have tried everything i can think of to get it to work on my WAMP local server any help would be greatly appreciated. I am PHP stupid. This works on a live server but not my WAMP server. I do get logged in just the pages do not seem to be passing the session variable to the proper user level. That's what's not working sorry for the poor description the first time.
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['login']))
{
if ($level == "Administrator") {
echo 'My Content';
}
elseif ($level == "Bank Officer") {
echo "";
}
elseif ($level == "Agent") {
echo "";
}
elseif(!empty($_POST['login']) && !empty($_POST['password']))
{
$login = mysql_real_escape_string($_POST['login']);
$password = $_POST['password'];
$checklevel = mysql_query("SELECT * FROM users WHERE login = '".$login."' AND password = '".$password."' ");
if(mysql_num_rows($checklevel) == 1)
{
$row = mysql_fetch_array($checklevel);
$level = $row['level'];
$_SESSION['level'] = $level;
}
$checklogin = mysql_query("SELECT * FROM users WHERE login = '".$login."' AND password = '".$password."' AND level='".$level."'");
if(mysql_num_rows($checklogin) == 1)
{
$row = mysql_fetch_array($checklogin);
$firstname = $row['firstname'];
$login = $row['login'];
$agent = $row['agent'];
$_SESSION['agent'] = $agent;
$_SESSION['firstname'] = $firstname;
$_SESSION['login'] = $login;
$_SESSION['LoggedIn'] = 1;
Thanks you for any help at all.
if ($_SESSION['level'] == "Bank Officer")
{
header('Location: index3.php');
exit;
}
elseif ($_SESSION['level'] == "Agent")
{
header('Location: index4.php');
exit;
}
elseif ($_SESSION['level'] == "Bank Manager")
{
header('Location: index5.php');
exit;
}
else
{
echo "Contact Administrator";
exit;
}

php form submission-checking not being recognized

I basically took in 3 pieces of data from a form, and before processing them, I just wanted to make sure that all fields were filled in. So the focus of this is the second to last IF statement, checking if the different variables are empty. It seems to only be working for the first variable and I can't figure out how to make it apply to all of them.
<?php
include ("account.php") ;
include ("connect.php") ;
$isdone = FALSE;
$un = $_REQUEST [ "un"] ;
$pw = $_REQUEST [ "pw"] ;
$data = mysql_query("SELECT * FROM `auth` WHERE username = '$un'") or die(mysql_error());
$info = mysql_fetch_array($data);
$info['username'];
$password = $info['pw'];
session_start();
if(trim($un) != '' && trim($pw) != '' && $password == $pw)
{
$_SESSION['uze']=$un;
include "problem.html";
}
elseif( !isset($_POST['submit1']) && $isdone == FALSE)
{
echo "wrong password";
}
$selected = $_REQUEST [ "type"] ;
if($selected == 'afs')
{
$typeinc = 'afs';
}
else if($selected == 'db')
{
$typeinc = 'database';
}
else if($selected == 'cs')
{
$typeinc = 'computer systems';
}
else if($selected == 'pw')
{
$typeinc = 'password';
}
else if($selected == 'hw')
{
$typeinc = 'hardware';
}
else if($selected == 'other')
{
$typeinc = 'other';
}
$text = $_REQUEST ["inc"];
$selected2 = $_REQUEST ["yesno"];
if($selected2 == 'yes')
{
$email = 'yes';
}
else
{
$email = 'no';
}
if(isset($_POST['submit1']))
{
if(empty($typeinc) || empty($text) || empty($email))
{
print( 'You have not filled in all fields, click to sign in and re-enter' );
}
}
else{
mysql_query("INSERT INTO `swp5_proj`. `inci` (`type`, `date`, `time`, `reporter`, `desc`) VALUES ('$typeinc', CURDATE(), CURTIME(), '".$_SESSION['uze']."', '$text');") or die(mysql_error());
mysql_query("DELETE FROM inci WHERE type = ' '");
$isdone = TRUE;
}
if(isset($_POST['submit1']) && $isdone == TRUE)
{
echo "session over";
}
?>
Make sure you clean your REQUEST variables before you put them in a MySQL query.
if((trim($un) !== '') && (trim($pw) !== '') && ($password == $pw))
You're setting $email to yes or no in the line just above.
In your if statement you are using the shortcut OR operator.... As soon as a single statement evaluates to true, the entire statement evaluates to true and there is no need to continue processing further.

Categories