I am using the header function to locate to another page based on certain conditions. I am monitoring a mailbox and the code redirects to another page based on the sender address. All headers are working except one. If the sender does not belongs to any existing group, I wanted to redirect it to new.php. But it is not redirecting. I am unable to figure out why. Please help me.
<?php
session_start();
$server = '{server}INBOX';
$username = 'aaa#bbb.com';
$password = 'password';
require_once '../swift/lib/swift_required.php';
include('connection.php');
$connection = imap_open($server,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
$_SESSION['connection']=$connection;
$result = imap_search($connection,'UNSEEN');
if($result) {
rsort($result);
foreach($result as $email_number)
{
$header = imap_headerinfo($connection, $email_number);
$fromaddr = $header->from[0]->mailbox . "#" . $header->from[0]->host;
$query = "select * from usergroup where email='$fromaddr'";
$_SESSION['fromaddr']=$fromaddr;
$result1 = mysql_query($query) or die($query."<br/><br/>".mysql_error());
while($line=mysql_fetch_array($result1,MYSQL_ASSOC))
{
$email=$line['email'];
$group=$line['group'];
if(mysql_num_rows($result1) == 1){
if($group == 1){
header("Location: facilitator.php");
}
elseif($group == 2){
header("Location: learner.php");
}
}
elseif (mysql_num_rows($result1) == 0) {
header("Location: new.php");
}
}
}
}
elseif (!$result)
{
echo "No unread messages found";
}
?>
It appears as though you are nesting that redirection inside the while loop. Since there are no rows, the while condition mysql_fetch_array() will immediately return FALSE and skip the whole block, including the redirection you intended it to follow.
Move the test for mysql_num_rows() outside the while loop.
// Test for rows and redirect BEFORE entering the while loop.
if (mysql_num_rows($result1) === 0) {
header("Location: new.php");
// Always explicitly call exit() after a redirection header!
exit();
}
// Otherwise, there are rows so loop them.
while($line=mysql_fetch_array($result1,MYSQL_ASSOC))
{
$email=$line['email'];
$group=$line['group'];
if($group == 1){
header("Location: facilitator.php");
}
}
You actually may not need a while loop at all, depending on how many rows you are expecting to fetch. If you only expect one group per email, then forego the loop and just call $line = mysql_fetch_array() once. However, if you are expecting multiple rows but want to redirect on the first one encountered where $group == 1, then your logic works. In that case however, since you are only doing the redirection and no other action, you might as well just put that condition in your query:
// Test the group in your query in the first place.
$query = "select * from usergroup where email='$fromaddr' AND group = 1";
$result1 = mysql_query($query) or die($query."<br/><br/>".mysql_error());
if (mysql_num_rows($result1) === 0) {
// you didn't match a row, redirect to new.php
}
else {
// you had a match, redirect to facilitator.php
}
Easy one:
change:
elseif (mysql_num_rows($result1) == 0){
to:
else {
The condition in the else if is probably false - so you don't get in there and thus the redirection doesn't occur.
Related
I have this script. Everything works fine except that the first "if" condition does not evaluate as expected because it does not echo out the code that proves that it evaluated properly.I have a page(index.php) containing a form with post action from where the $_POST['pincode'] is coming from. So when if($pincode !== $_POST['pincode']) evaluates to true, instead of header location to echo the error message and come back to index.php page, what happens is that it routes to my checkpin.php (this script) and stays there.
NB: $_POST['pincode'] is a number input type in HTML.
$_SESSION['pincode']= $_POST['pincode'];
$conn = new mysqli("localhost","user","pass",'db');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = $conn->query("SELECT pincodex, pinmatch FROM voters_reg WHERE pincodex = '{$_SESSION['pincode']}'");
$row_count = $sql->num_rows;
if ($row_count == 1)
{
while($row = $sql->fetch_assoc()){
$pinmatch = $row['pinmatch'];
$pincode = $row['pincodex'];
if($pincode !== $_POST['pincode']){
$_SESSION['error'] = "first error message";
header('Location: index.php');
exit();
} elseif ($pinmatch == $_POST['pincode']){
$_SESSION['error'] = "second error message";
header('Location: index.php');
exit();
} else {
$_SESSION['success'] = "success message";
header('Location: pinsuccess.php');
exit();
}
}
}
$conn->close();
Logically, $pincode should never be able to be not equal to $_POST['pincode']. Consider the following steps:
$_SESSION['pincode'] is set to $_POST['pincode'];
Rows are selected from your database WHERE pincodex = '{$_SESSION['pincode']}'
At this point, because of the WHERE clause, every row returned by your query will have pincodex == $_POST['pincode'].
You set $pincode = $row['pincodex'];
If there is a row, $row['pincodex'] will always equal $_POST['pincode'].
So, regardless of type checking, the condition if($pincode !== $_POST['pincode']){ can never evaluate to true, and your code will never enter that if block.
If a pincode is entered that is not found in your database, $sql->num_rows will return 0 and the code will not enter the if ($row_count == 1) block at all. I think this is most likely why your script is not redirecting as expected.
Try changing the if statement to if($pincode !== (int)$_POST['pincode']){
I have a problem with the code, it is the premature execution error when using header.
Code:
<?php
session_start();
require 'config.php';
$prepend = "<span class='welcome'>";
$append = "</span>";
if (!isset($_SESSION['name'])) {
header("Location: login.php");
}
echo $prepend."Здравей ".$_SESSION['name'].$append."</br>";
if (isset($_POST['submit']))
{
$newname = mysql_real_escape_string($_POST['newname']);
$newpass = mysql_real_escape_string($_POST['newpass']);
$oldpass = mysql_real_escape_string($_POST['oldpass']);
$checkPass = "SELECT pass from admin WHERE pass = '$_POST[oldpass]'";
$rs = mysqli_query($connect,$checkPass);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if ($data > 0)
{
$query = "UPDATE admin SET pass ='".$_POST['newpass']."',name ='".$_POST['newname']."'" ;
$result = mysqli_query($connect, $query);
if ($result === true)
{
echo "Update sucessfuly!";
}
}
else {
header('Location: admin.php?failed=1');
}
}
?>
The first time when you open the page the else part is performed immediately and I can not understand why.
First you have 2 weird lines in your code:
$rs = mysqli_query($connect,$checkPass);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
Those function don't exist, in fact you probably used the mysql_...() ones, as it seems confirmed by the previous statements.
Now when you execute
$data = mysql_fetch_array($rs, MYSQLI_NUM);
then $data is an array (the next record returned) or FALSE (when no more record exist. And this statement should belong to a loop.
Anyway, in the current form of your code, when you execute if ($data > 0), it can't return anything significative since $data is an array.
So you must refactor all this piece of code according to your need (I guess you want to control that pass was really found by the previous query).
the first time you open page, the else part is executed because the session variables are not set, you need to set session variables first.
$_SESSION['sessionName']= $value;
you must have done this on some other page, if so, then please share the code.
and try using
if(mysqli_num_row($data)>0)
{
$query = "UPDATE admin SET
pass='".$_POST['newpass']."',name='".$_POST['newname']."'" ;
$result = mysqli_query($connect, $query);
if ($result === true)
{
echo "Update sucessfuly!";
}
}
else{
header('Location: admin.php?failed=1');
}
}
?>
I am new in PHP and need help with my below code. When I am entering wrong userid instead of giving the message "userid does not exist" it is showing "password/id mismatch. Please guide me where I am wrong.
<?php
session_start();
$id = $_POST['userid'];
$pwd = $_POST['paswd'];
$con = mysqli_connect("localhost", "????", "????", "??????");
if ($con) {
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
if ($result) {
$row = mysql_fetch_array($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist !!!";
}
} else {
echo "Connection failed - ".mysqli_error()." -- ".mysqli_errno();
}
?>
The main problem you have is that you're mixing up between the mysqli and mysql functions. These two libraries are not compatible with each other; you must only use one or the other.
In other words, the following line is wrong:
$row=mysql_fetch_array($result);
It needs to be changed to use mysqli_.
While I'm here, going off-topic for a moment I would also point out a few other mistakes you're making:
You aren't escaping your SQL input. It would be extremely easy to hack your code simply by posting a malicious value to $_POST['userid']. You must use proper escaping or parameter binding. (since you're using mysqli, I recommend the latter; it's a better technique).
Your password checking is poor -- you don't appear to be doing any kind of hashing, so I guess your passwords are stored as plain text in the database. If this is the case, then your database is extremely vulnerable. You should always hash your passwords, and never store the actual password value in the database.
I've gone off topic, so I won't go any further into explaining those points; if you need help with either of these points I suggest asking separate questions (or searching here; I'm sure there's plenty of existing advice available too).
else
{
echo "ID/Password Mismatch";
}
is connected with the
if($row["userid"]==$id && $row["paswd"]==$pwd)
{
So since you are giving a wrong id. It echo's: ID/Password Mismatch
Also the else at if ($result) { wont ever show since
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
You need some additionnal checks:
select * return 1 row (not 0, and not more)
you need to protect the datas entered by the html form (for example someone could enter 1 or 1 to return all rows
<?php
session_start();
$con = mysqli_connect("localhost", "????", "????", "??????");
$id = mysqli_real_escape_string($_POST['userid']);
$pwd = mysqli_real_escape_string($_POST['paswd']);
if ($con) {
// don't even do the query if data are incomplete
if (empty($id) || empty($pwd)
$result = false;
else
{
// optionnal : if userid is supposed to be a number
// $id = (int)$id;
$result = mysqli_query($con, "SELECT * FROM users WHERE userid='$id'");
}
if (mysqli_num_rows($result) != 1)
$result = false;
if ($result) {
$row = mysqli_fetch_assoc($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist, or incomplete input";
}
} else {
echo "Connection failed - " . mysqli_error() . " -- " . mysqli_errno();
}
?>
Try with isset() method while you are checking if $result empty or not.
that is in line
if ($result) {.......}
use
if (isset($result)) { .......}
$result is always true, because mysqli_query() only returns false if query failed.
You could check if $result has actual content with empty() for example.
You can use this sql compare password as well with userid
$sql= "SELECT * FROM users WHERE userid='".$id.", and password='".$pwd."'";
This code only redirects to notenrolled.php even if the input value is correct. I want it to continue the process if the value entered is correct. Is there something wrong with my code?
<?php
//Setup connection to the database
$connect = mysql_pconnect("localhost", "root", "")
or die(mysql_error());
//Connect to the database
mysql_select_db("dbgis", $connect) or die(mysql_error());
$query = "SELECT * from tbl_student WHERE stud_id= '$stud_id' ";
$result = mysql_query($query);
$totalrows = mysql_num_rows($result);
while($row = mysql_fetch_array($result))
{
header("Location: yesno.php");
}
if($totalrows != 0)
{
header("Location: notenrolled.php");
}
?>
I tried the die(); and it seems to be working because it just says a redirection looping error with yesno.php. So I think I might have put the code in the wrong .php page.
The flow is like this: I have a guard.php page where I could search a query(stud_id) using my search form in the page. I then want to check whether the query exists and if it doesn't, I want it to redirect to notenrolled.php else if the query is found, I want it to proceed to yesno.php.
When you set a Location header, you ALWAYS immediately follow it with exit or die().
(Only if you truly understand what you are doing, might you not immediately use it, but at your own risk.)
if ($totalrows > 0)
{ // has results
header("Location: yesno.php");
exit(0);
}
else
{ // no result
header("Location: notenrolled.php");
exit(0);
}
You should not use while just to evaluate if there is a record.
while($row = mysql_fetch_array($result))
{
header("Location: yesno.php");
}
Your code always redirects to notenrolled.php because of the codition:
if($totalrows != 0)
{
header("Location: notenrolled.php");
}
//this block will always be true if your $totalrows is greater than 0
The solution: check $totalrows if is greater than 0
if ($totalrows > 0){
header("Location: yesno.php");
} else {
header("Location: notenrolled.php");
}
u can use php function mysql_affected_rows to see number off affected rows in SELECT,
if (mysql_affected_rows() == 0){
header("Location: notenrolled.php");
} else {
header("Location: yesno.php");
}
The correct way to do it is this:
if($totalrows>0)
header("Location: yesno.php");
else
header("Location: notenrolled.php");
try this
if($totalrows == 0)
{
header("Location: notenrolled.php");
die();
}
What is the problem with following code? Please help me out.
I want to match admin-id and password from the database along with login-id and password of the normal users and further want to transfer the control to the respective forms.
When I run this code it gives following errors:
Notice: Undefined variable: userstatus in C:\xampp\htdocs\xampp\Test\HRMS\extract.php on line 25
Notice: Undefined variable: usertype in C:\xampp\htdocs\xampp\Test\HRMS\extract.php on line 30
$query1="select user_type,user_staus from `user_info` where name='$username' and
password='$password'";
$fetched=mysql_query($query1);
while($record=mysql_fetch_assoc($fetched))
{
while(each($record))
{
$usertype=$record["user_type"];
$userstatus=$record["user_staus"];
}//closing of 1st while loop
}//closing of 2nd while loop
if($userstatus==1) //if is logged in already
{
echo "Please login after some time";
exit();
}
if($usertype == 0) // if user is not an admin
{
$query1="select * from `user_info` where name='$username' and password='$password'";
$result = mysql_query($query1);
if(mysql_num_rows($result) == 1)
{
header("Location: user_form.php");
}
}
else if($usertype == 1) //if the user is a normal user
{
header("Location: admin_form.php");
}
else
{
echo "please register to login";
}
Can someone help me find the problem?
There are many problems with your code, main reason you receiving an error is because $usertype and $userstatus are not predefined and not validated.
But in my opinion it is not a main issue with your code.
There are few questions that I would like to ask you:
Why creating two loops if you need to fetch a single row?
Why querying database twice if you already know the answer?
Are you escaping $username and $password for bad characters using mysql_real_escape_string method?
here is an example how this code should look like:
$query1 = "SELECT user_type,user_staus FROM `user_info` WHERE name='{$username}' AND password='{$password}' LIMIT 1";
$fetched = mysql_query($query1);
//check if record exists otherwise you would receive another notice that can
//break redirect functionality
if (mysql_num_rows($fetched))
{
$record = mysql_fetch_assoc($fetched);
// make sure that value is integer
if ((int)$record["user_staus"])
{
exit("Please login after some time");
}
else
{
$url = (bool)$record["user_type"] ? 'admin_form.php' : 'user_form.php';
header("Location: {$url}");
exit(0);
}
}
else
{
echo "please register to login";
}
UPDATE
As suggested by nikc.org, removed 3rd level if nesting and replaced with ternary comparison
you have overlooked the scope rules ( since you have not shown full code)
while($record=mysql_fetch_assoc($fetched))
{
while(each($record))
{
$usertype=$record["user_type"];
$userstatus=$record["user_staus"];
}//closing of 1st while loop
}//closing of 2nd while loop
Here $usertype and $userstatus are declared inside inner while loops { } .
ie, their scope resorts to that { } . as soon as code comes out of it the $userstatus and $usertype dies and so further accessing is not possible .
you must declare there variables ut side in global area first .