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');
}
}
?>
Related
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."'";
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.
Here it's I have a problem with my PHP Code + Oracle Login form.
In this PHP file, I make login function. But I have an error like this :
Warning: oci_num_rows() expects parameter 1 to be resource, string given in C:\xampp\htdocs\developers\it\session.php on line 12
Wrong
-
<?php
session_start();
include ("config.php");
$username = $_POST['username'];
$password = $_POST['password'];
$do = $_GET['do'];
if($do=="login")
{
$cek = "SELECT PASSWORD, USER_LEVEL FROM T_USERS WHERE USERNAME='$username' AND PASSWORD='$password'";
$result = oci_parse($conn, $cek);
oci_execute($result);
if(oci_num_rows($cek)==1)
{
$c = oci_fetch_array($result);
$_SESSION['username'] = $c['username']; ociresult($c,"USERNAME");
$_SESSION['USER_LEVEL'] = $c['USER_LEVEL']; ociresult($c,"USER_LEVEL");
if($c['USER_LEVEL']=="ADMINISTRATOR")
{
header("location:supervisor.php");
}
else if($c['user_level']=="User")
{
header("location:user.php");
}
else if($c['user_level']=="Root")
{
header("location:administrator.php");
}
else if($c['user_level']=="Manager")
{
header("location:manager.php");
}
else if($c['user_level']=="Admin")
{
header("location:admin.php");
}
else if($c['user_level']=="Director")
{
header("location:director.php");
}
}
else
{
echo "Wrong";
}
}
?>
I have tried to search in google, but still don't find anything.
Someone knows, what's the problem ?
Thanks for advance.
According to your script instead of
if(oci_num_rows($cek)==1)
you should call
if(oci_num_rows($result)==1)
You probably want to use $result and not $cek when you're asking for the number of rows returned from oci_num_rows(). However, you really want to avoid using $username and $password directly in the string like that. It'll make you wide open for SQL injection attacks, so look into using oci_parse together with oci_bind_by_name.
After that you should also always call exit() after the sequence of redirects, as the script will continue running if you don't (and that might be a security issue other places).
I also got the same case, so I tricked it with a script like this, but I don't know whether there was an impact or not. because the session and validation went smoothly.
$username =$_POST['username'];
$password = $_POST['password'];
$conn = oci_connect('xxx', 'xxx', 'localhost/MYDB');
$pass_encription = md5($password);
$query = "SELECT * from *table_name* WHERE *field1*='".$username."' and *field2*='".$password."'";
$result = oci_parse($conn, $query);
oci_execute($result);
$exe = oci_fetch($result);
if ($exe > 0)
{
oci_close($conn);
oci_execute($result);
$row =oci_fetch_array($result);
$sid = $row['field_1_parameter'];
$snama = $row['field_2_parameter'];
$sjab = $row['field_3_parameter'];
$session = array (
'field_1_array' =>$sid,
'field_2_array' =>$snama,
'field_3_array' =>$sjab
);
if($sjab == 'Administrator')
{
$this->session->set_userdata($session);
redirect('redirecting_page');
}
`
I'm trying to retrieve the access level (admin/member/guest) for the currently logged in user and depending on this, show them specific content on my page. I'm trying to test this with echos right now but still cannot get anything to print out. Could anyone give any advice?
if(isset($_SESSION['username'])){
global $con;
$q = "SELECT access FROM users WHERE username = '$username' ";
$result = mysql_query($q, $con);
if($result == 'guest')
{
echo "You are a guest";// SHOW GUEST CONTENT
}
elseif($result == 'member')
{
echo "You are a member"; // SHOW OTHER CONTENT
}
elseif($result == 'admin')
{
echo "You are an admin";// SHOW ADMIN CONTENT
}
}
$result is a mysql resource. you need
if(isset($_SESSION['username'])){
global $con;
$q = "SELECT access FROM users WHERE username = '$username' LIMIT 1";
$result = mysql_query($q, $con);
$row = mysql_fetch_assoc($result);
$access = $row['access'];
if($access == 'guest')
{
echo "You are a guest";// SHOW GUEST CONTENT
}
elseif($access == 'member')
{
echo "You are a member"; // SHOW OTHER CONTENT
}
elseif($access == 'admin')
{
echo "You are an admin";// SHOW ADMIN CONTENT
}
}
$result as returned by mysql_query is not a string that you can compare against; it is a resource. You need to fetch the row from $result:
$row = mysql_fetch_assoc($result)
$access = $row['access'];
if($access == 'guest') {
...
}
...
A few other issues:
You have a possible SQL-injection issue in your query. You should never directly insert the values of variables into your SQL queries without properly escaping them first. You might want to use mysql_real_escape_string.
The mysql is being deprecated. You should try to use mysqli (MySQL Improved) or PDO (PHP Data Objects).
I see two issues:
1. You need to use session_start(); at the beginning. otherwise your if statement will not be executed.
2. mysql_query($q, $con) does not return a string. it returns a record set. You need to use mysql_fetch_assoc($result); which return associative array.And from the array you retrieve your desired value by:
$assoc_arr = mysql_fetch_assoc($result);
$access = $assoc_arr['access'];
now you can compare $access.
I have output from a select query as below
id price valid
1000368 69.95 1
1000369 69.94 0
1000370 69.95 0
now in php I am trying to pass the id 1000369 in function. the funciton can execute only if the valid =1 for id 1000368. if it's not 1 then it will throw error. so if the id passed is 1000370, it will check if valid =1 for 1000369.
how can i check this? I think it is logically possible to do but I am not able to code it i tried using foreach but at the end it always checks the last record 1000370 and so it throws error.
regards
Use a boolean variable:
<?php
$lastValid=false;
while($row = mysql_fetch_array($result))
{
if ($lastValid) {
myFunction();
}
$lastValid = $row['valid'];
}
?>
(Excuse possible errors, have no access to a console at the moment.)
If I understand correctly you want to check the if the previous id is valid.
$prev['valid'] = 0;
foreach($input as $i){
if($prev['valid']){
// Execute function
}
$prev = $i;
}
<?php
$sql = "SELECT * FROM tablename";
$qry = mysql_query($sql);
while($row = mysql_fetch_array($qry))
{
if ($row['valid'] == 1)
{
// do some actions
}
}
?>
I really really recommend walking through some tutorials. This is basic stuff man.
Here is how to request a specific record:
//This is to inspect a specific record
$id = '1000369'; //**some specified value**
$sql = "SELECT * FROM data_tbl WHERE id = $id";
$data = mysql_fetch_assoc(mysql_query($sql));
$valid = $data['valid'];
if ($valid == 1)
//Do this
else
//Do that
And here is how to loop through all the records and check each.
//This is to loop through all of it.
$sql = "SELECT * FROM data_tbl";
$res = mysql_query($sql);
$previous_row = null;
while ($row = mysql_fetch_assoc($res))
{
some_action($row, $previous_row);
$previous_row = $row; //At the end of the call the current row becomes the previous one. This way you can refer to it in the next iteration through the loop
}
function some_action($data, $previous_data)
{
if (!empty($previous_data) && $condition_is_met)
{
//Use previous data
$valid = $previous_data['valid'];
}
else
{
//Use data
$valid = $data['valid'];
}
if ($valid == 1)
{
//Do the valid thing
}
else
{
//Do the not valid thing
}
//Do whatever
}
Here are some links to some good tutorials:
http://www.phpfreaks.com/tutorials
http://php.net/manual/en/tutorial.php