header and redirect in php - 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'));

Related

how to change from mysql to mysqli

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'];

Redirect to different pages on login- php

I want to redirect an admin to a page and other users to a different page.
Able to do in procedure but not in oop.
An admin might add new users and display them n has a whole lot of jobs to do whereas a user can see only his/her page.
<?php
require_once('userClass.php');
$userObj = new USER();
session_start();
$type = $_GET['type'];
if(empty($type) || !isset($type)) {
echo 'Request type is not set';
} else if($type == 'signup') {
$data = USER::addNewUser($_REQUEST);
$_SESSION = $data;
if($data['status'] == 'error') {
header("location:register.php");
} else {
header("location:index.php");
}
} else if($type == 'login') {
$username = addslashes($_REQUEST['username']);
$password = addslashes($_REQUEST['password']);
$_SESSION = USER::login($username, $password);
if($_SESSION['status'] == 'error') {
header("location:index.php");
}
else {
header("location:profile.php");
}
/*if($_SESSION['username'] == 'admin#admin.com') {
header("location:admin.php");
}
else {
header("location:profile.php");
}*/
} else if($type == 'logout') {
unset($_SESSION);
session_destroy();
header("location:index.php");
}
?>
Looking for a solution....Please help.
*Look at the comented section in code.
One of the easy way to do so is to define the role.
For example
if($_SESSION['username'] == 'admin#admin.com' && $_POST['role'] = 'admin'){
header("location:admin.php");
}
else {
header("location:profile.php");
}
Check the below code, hope this helps.
if($_SESSION['status'] == 'error') {
header("Location: index.php");
}
else {
if($_SESSION['username'] == 'admin#admin.com') {
header("Location: admin.php");
}
else {
header("Location: profile.php");
}
}

PHP Returning value from If/Else If statement called via class

I am trying to figure out why this isn't working. What I am trying to do is return a value after the function is called. It is a login function which is supposed to check the database for the users status. That value being $userStatus. Depending on the status I'd like to return a value which would then trigger the error. However the script only fires off the first else if statement.
Here is the index page which calls the script
if(isset($_POST['btn-login'])) {
$uname = strip_tags($_POST['txt_uname_email']);
$umail = strip_tags($_POST['txt_uname_email']);
$upass = strip_tags($_POST['txt_password']);
if ($login->doLogin($uname,$umail,$upass)) {
$login->userLoginTime($uname);
$login->redirect('home.php');
} else if ($userStatus == 0) {
$error = "Your account is not active!";
} else if ($userStatus == "") {
$error = "You don't have an account, please sign up";
}
}
?>
Here is the class page where the function is housed.
public function doLogin($uname,$umail,$upass)
{
try
{
$stmt = $this->conn->prepare("SELECT
user_id, user_name, user_email, user_pass, Enabled
FROM users WHERE user_name=:uname OR user_email=:umail ");
$stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
$userStatus = $userRow['Enabled'];
if ($userStatus == 5) {
if ($stmt->rowCount() == 1) {
if (password_verify($upass, $userRow['user_pass'])) {
$_SESSION['user_session'] = $userRow['user_id'];
return true;
}
} else {
return false;
}
}
if ($userStatus == 0) {
return $userStatus;
}
if ($userStatus == "") {
return $userStatus;
}
}
$userStatus is never being set. You'll want to set it before your if:
$userStatus = $login->doLogin($uname,$umail,$upass);
if($userStatus === true) {
$login->userLoginTime($uname);
$login->redirect('home.php');
} else if ($userStatus === 0) {
$error = "Your account is not active!";
} else if ($userStatus === "") {
$error = "You don't have an account, please sign up";
}
maybe "txt_uname_email" in
$uname = strip_tags($_POST['txt_uname_email']);
is incorrect? Something with name?

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()

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