php custom error message shown incorrectly - php

i'm working on a php assignment for log in function using .txt file instead of db, but i'm facing with some sort of problem here. supposedly the "invalid email or password" to be shown after a non exist details key in, but when the page load, the msg showed by default, below is my code
<?php
$lines= file("customers.txt");
$matchFound=false;
$errmsg = 'Invalid email or password';
for($i=0;$i<count($lines);$i++)
{
if ($i!=0)
{
$line=trim($lines[$i]);
$cells=explode("\t",$line);
$_SESSION['email'] = isset($_POST['email'])? $_POST['email'] : null;
$_SESSION['password'] = isset($_POST['password']) ? $_POST['password'] : null;
if ($_SESSION['email']==$cells[2] && $_SESSION['password']==$cells[3])
{
$matchFound=true;
break;
}
}
}
if ($matchFound == true)
{
header('Location: login2.php');
}
else
{
echo $errmsg;
}
?>

This is because you're not checking if the user submitted the form input correctly. The value of $matchFound is FALSE by default, and the error message will always be displayed when the script is ran.
Specify a name attribute for your form submit button, and then add an if block to make sure the form was correctly submitted:
if (isset( $_POST['submitButton'] )) {
# code...
}
That way, the code inside the if block won't be run if the user input wasn't received and you could avoid the error being displayed every time you load the page.
Also, you're missing the session_start() statement at the top of your script. This is required if you want the sessions to work properly.

Try:
if ($matchFound == true)
{
header('Location: login2.php');
}
else if(isset($_POST['email']))
{
echo $errmsg;
}
Also you need session_start to use $_SESSION array

Related

session is works locally but not online [duplicate]

I'm new to PHP and am even more of a beginner when it comes to sessions. I have my index.php page, which is where users can register and login. The forms are posting to validate.php and loginvalidate.php pages, respectively for registering and logging in.
I have these errors on index.php when I load it:
1) Notice: Undefined index: registered
2) Notice: Undefined index: neverused
I have tried modifying my text in many ways but I never got to solve the errors.
Index.php
<?php
if ($_SESSION['registered'] != NULL){
echo $_SESSION['registered'];
}
if ($_SESSION['badlogin'] != NULL){
echo $_SESSION['badlogin'];
}
if ($_SESSION['neverused'] != NULL) {
echo $_SESSION['neverused'];
}
?>
Validate.php (after submitting register form)
if (mysqli_num_rows($result) > 0) { //IF THERE IS A PASSWORD FOR THAT EMAIL IN DATABASE
$_SESSION['registered'] = "Email is already registered.";
mysqli_close($db_handle);
header('Location: index.php');
exit();
}
Loginvalidate.php (after submitting login form)
if ($numrows!=0) //IF THERE IS A PASSWORD FOR THAT EMAIL IN THE DATABASE
{
if ($row['password'] == $password) { //IF THE PASSWORD MATCHES USER INPUT
header('Location: homepage.php');
echo "lol";
exit();
}
else{
$_SESSION['badlogin'] = "Email/password combination not valid.";
mysqli_close($db_handle);
header('Location: index.php');
exit();
}
}
else { //THERE IS NO PASSWORD FOR THAT EMAIL, SO THAT EMAIL IS NOT REGISTERED
$_SESSION['neverused'] = "Email is not registered.";
mysqli_close($db_handle);
header('Location: index.php');
exit();
}
Okay so my script does what it is intended to do. The only thing that I can't solve is these session errors. Do you see any misuse of sessions? Of course, I have started the sessions in all of my .php files.
Also, note that I am aware that there is no protection from hackers. This is only for a future prototype that won't contain any important data.
The reason for these errors is that you're trying to read an array key that doesn't exist. The isset() function is there so you can test for this. Something like the following for each element will work a treat; there's no need for null checks as you never assign null to an element:
// check that the 'registered' key exists
if (isset($_SESSION['registered'])) {
// it does; output the message
echo $_SESSION['registered'];
// remove the key so we don't keep outputting the message
unset($_SESSION['registered']);
}
You could also use it in a loop:
$keys = array('registered', 'badlogin', 'neverused');
//iterate over the keys to test
foreach($keys as $key) {
// test if $key exists in the $_SESSION global array
if (isset($_SESSION[$key])) {
// it does; output the value
echo $_SESSION[$key];
// remove the key so we don't keep outputting the message
unset($_SESSION[$key]);
}
}
If you're getting undefined index errors, you might try making sure that your indexes are set before you try comparing the values. See the documentation for the isset function here:
http://php.net/manual/en/function.isset.php
if (isset($_SESSION['registered']))
if ($_SESSION['registered'] != NULL){
echo $_SESSION['registered'];
}
}
if (isset($_SESSION['badlogin']))
if ($_SESSION['badlogin'] != NULL){
echo $_SESSION['badlogin'];
}
}
if (isset($_SESSION['neverused']))
if ($_SESSION['neverused'] != NULL) {
echo $_SESSION['neverused'];
}
}

Redirecting to same page along with Success Message with Php [duplicate]

This question already has answers here:
Redirect to another page with a message
(6 answers)
Closed 8 months ago.
What's the best way to display a success message after redirecting to same page? I've been thinking about doing that with javascript but maybe there's a way to do this with Php? The user submit from profile.php and gets redirected to same page. I'd like to grab a variable... Can I concatenate after $_SERVER['HTTP_REFERER']? Whats the best approach?
here a snippet of code: query.php
$stmt->execute() or die(mysqli_error($db));
if($stmt){
// echo "Data Submitted succesfully";
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
}
$stmt->close();
$db->close();
}
You could skip the session, and pass a url query parameter as a code or the message.
$stmt->execute() or die(mysqli_error($db));
if($stmt){
// echo "Data Submitted succesfully";
header('Location: ' . $_SERVER['HTTP_REFERER'] . '?message=success1');
exit;
}
$stmt->close();
$db->close();
}
Then have code that checks for $_GET['message] ...etc
You can use sessions. Just start session, save message in global array $_SESSION, then in profile.php check if $_SESSION with your key is set and it isn't empty show it. After it you can unset your key in $_SESSION.
query.php
<?php
session_start();
//your code
if($stmt) {
$_SESSION['myMessage'] = 'Some message';
//your code
}
//rest of your code
profile.php
<?php
session_start();
//your code
if(isset($_SESSION['myMessage']) && $_SESSION['myMessage'] !== '') {
//display message or do with it what you want
}
//rest of code
If you're processing your form in the same page, then you don't have to do any redirection. The solution to achieve the desired result would be like this:
Put your form processing code at the very top of your PHP script i.e. profile.php page.
Use a boolean variable to hold the status of ->execute() statement, and use that same variable at later point of your code.
So the code would be like this:
// Declare a boolean variable at the beginning
$status = false;
// your code
$status = $stmt->execute();
$stmt->close();
$db->close();
}
if($status){
// Data submitted succesfully
}else{
// Data couldn't get submitted
}
If you want to process the form at the same file, you don't need to redirect again to the same page.
As mention by the other answer, you process the form at the top of the page.
To display a message after success or failure, you store the message in a variable. Later with the from you echo the message variable if it is set.
// Check if form was submitted
if(isset($_POST['submit'])) { // I name the submit button "submit"
// process the form
if ($stmt->execute()) {
$message = "<div> Success </div>";
} else {
$message = "<div> Failed </div>";
}
}
// Display The form and the message if not empty
if (! empty($message)) {
echo $message;
}
// Form

PHP:my session_variables shows when the page refresh

I know this is very simple thing but i am not aware of this. I have php code on same page for a signup form which have some session variables to be shown when any condition matches with the code.
The code structure is like this:
<?php
session_start();
if(isset($_POST['signup'])
{
if(condition)
{
$_SESSION['err1']="string";
}
else
{
$_SESSION['err2']="string";
}
}
?>
//HTML form
<?php if(isset($_SESSION['err1']) {?>
<li><?php echo $_SESSION['err1'];}?></li>
<?php if(isset($_SESSION['err2']) {?>
<li><?php echo $_SESSION['err2'];}?></li>
//rest of the form
I have more block of if-else in my code. Initially, when an condition is matched, the session message is shown. But as soon as the page refresh an another session message is shown along with previous session message.
Is this correct way of coding with forms? Because i want to show error messages inside the html form.
That's maybe because you do not empty your session variable.
Between 2 HTTP request, the session is kept on the server (juste reloading at each request).
So, if you are putting a message on $_SESSION['error1'] for the first call, it will show it. Then, on the second load, if you are putting a message on $_SESSION['error2'], you will also have the message of error1 because the session keep your data.
After showing the form, you should empty all your session messages
Simply unset your session variable after you echo.
<li><?php echo $_SESSION['err1'];} unset($_SESSION['err1']); ?></li>
This is really a bad example that use session to echo errors.
what i do many times at the starting of my php.
$errors = array(); // make a empty array errors before the conditional statements
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['Submit'])) {
//handle your POST variable
if(condition1){
$errors[] = "some error";
}
if(condition2) {
$errors[] = "some another error";
}
//more conditions
if (!empty($errors)) {
//process your form data if there is no errro
} else {
//display back your form along with Errors
if(isset($errors) && !empty($errors)) {
foreach($errors as $error) {
echo "<p class = 'error'>" . $error . "</p>";
}
}
<form action = "" method = "POST">
//your form elements
</form>
}
}
in first line of the php page, u can write
you can try any of the three lines between if condition
if(isset($_SESSION))
{
unset($_SESSION);
unregister($_SESSION['variable-name']) // try this also
session_destroy(); //try this also
}

Redirect to another page after pressing submit button php mysql

I would to redirect to the next page after the form is completed and the submit button is pressed. This code works well on a windows server, but it fails to redirect to the next page on a linux server
<?php
include 'scripts/functions/init.php';
Restrict();
?>
<?php
$userid = $_SESSION['userid'];
if (empty($_POST)=== false)
{
$R_fields = array('OFO_Code','OFO_Title','Curr_Code','Curr_Title');
foreach($_POST as $key=>$value)
{
if (empty($value) && in_array($key,$R_fields)=== true)
{
$errors[] = 'fields marked with (*) are required';
break 1;
}
}
$_SESSION['Combo'] = $_SESSION['OFO_Code'].$_SESSION['Curr_Code'];
if(empty($errors)=== true)
{
if(Curr_Code_exists($_SESSION['Combo']))
{
$errors[] = 'Sorry, the Curriculum Code already exist, please use the edit function';
}
if(strlen('Curr_Code')<6)
{
$errors[] ='Curriculum Code must be at least 6 Characters';
}
}
}
?>
the above code appears just before the html, followed by the form. then just after the submit button follows the following and it also lies within the within
<?php
$_SESSION['OFO_Code'] = $_POST['OFO_Code'];
$_SESSION['Curr_Code'] = $_POST['Curr_Code'];
if(empty($_POST) === false && empty($errors)=== true)
{
//Capture data from the fields to an array
$Capture_Occupation_info = array(
'OFO_Code' => $_SESSION['OFO_Code'],
'OFO_Title'=>$_POST['OFO_Title'],
'Curr_Code'=>$_SESSION['Combo'],
'Curr_Title'=>$_POST['Curr_Title'],
'userid'=>$userid);
//Submit the data into the database
capture_occupation_info($Capture_Occupation_info);
header('Location:Capture_Menu.php');
exit();
}
else
{
//Display errors
echo output($errors);
}
?>
This is a complete shot in the dark, but might be right on. Windows is not case sensative, but NIX is.
Capture_Menu.php
Is that exactly how it is capitalized on your UNIX box?
Also, you can not display or echo to the browser before doing a header redirect. Please check for echos or even lose blank spaces after things like ?>
I have had redirections not work before because my code printed something to the output that I didn't do on purpose.
You can try this...
error_reporting(E_ALL);
ini_set('display_errors', 'On');

php redirection not working

Ive got this register script that puts the information into a mysql database. now it all works fine and when someone does something wrong its says the error (e.g. "Username not defined")
but when it goes wrong it does not look very good because it just displays the message on an empty page, so i thought i would make it redirect to the form page and display the message there.
here is the working script
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$username = $_POST['username'];
$errors = array();
if(!$username) {
$errors[] = "Username is not defined";
}
if(!$password) {
$errors[] = "Password is not defined";
}
and it continues.
now i just thought i could do this
$errors = array();
if(!$username) {
$errors[] = header( 'Location: http://localhost/muiltabledistractions/#!/page_register_error-Username-is-not-defined' ) ;
}
if(!$password) {
$errors[] = "Password is not defined";
}
but no, all it does is ignore it.
could someone please help me
please feel free to ask for more of the script if you need it
many thanks connor
You cannot wrap a header in a array like that.
You just call the function, then it redirects.
header( 'Location: http://localhost/muiltabledistractions/#!/page_register_error-Username-is-not-defined' ) ;
it does not look very good because it just displays the message on an empty page,
What's the problem?
Why not to show the form again? with fields already filled.
This is going to be a user-friendly interface.
Just include your form in the same page with fields populated.
That's more common way than your redirects to blank form.
This is called POST/Redirect/GET pattern and here goes a short example of it:
the code
<?
if ($_SERVER['REQUEST_METHOD']=='POST') {
$err = array();
//performing all validations and raising corresponding errors
if (empty($_POST['name']) $err[] = "Username field is required";
if (empty($_POST['text']) $err[] = "Comments field is required";
if (!$err) {
// if no errors - saving data
// and then redirect:
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['name'] = $form['comments'] = '';
}
include 'form.tpl.php';
?>
the template
<? if ($err): ?>
<? foreach($err as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form>
<input type="text" name="name" value="<?=$form['name']?>">
<textarea name="comments"><?=$form['comments']?></textarea>
<input type="submit">
</form>
You are placing the return value of the header function in an array, then continuing with your page execution.
If you don't care about anything that would normally happen below that redirection, which I believe is what you're implying, you should just set the header and then immediately exit. Do not try to place the return value of the header function into the errors array like that, as there's no point.
if(!$username) {
header('Location: http://localhost/muiltabledistractions/#!/page_register_error-Username-is-not-defined');
exit;
}
I don't if this is the problem, but it's important to include the status code in header too. Like:
header("Location: /foo.php",TRUE,302);
307 for Temporary Redirect, 302 for permanently moved. Chrome, a while ago, didn't accepted headers redirect without status code (i don't know nowadays).
try this after filling your error array:
if (count($errors) > 0)
{
header( 'Location: http://localhost/muiltabledistractions/#!/page_register_error-Username-is-not-defined' );
exit;
}
Keep in mind there should be no html output before this part!

Categories