Error Count - PHP - php

I have a form which has email as field name. What I am trying to do is if the email is it no equal to $emailToCheck is not equal to $_POST['email'], it should throw an error first time. The second time if the user enters wrong email id again it should always redirect to "error.htm" even if the page refreshes.
It doesn't work the form always shows even if the email id is entered wrong twice.
<?php
if (!empty($_POST['email'])) {
$email="website#test.com";
if($email!=$_POST['email'])
{
$count="1";
}
if($count=="2"){
header("Location: /error.htm");
exit(0);
}
}
if($count!="2"){
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form</title>
</head>
<body id="main_body" >
<div id="form_container">
<h1><a>Form</a></h1>
<form id="form_1123848" class="appnitro" method="post" action="">
<div class="form_description">
<h2>Form</h2>
<p> <input type="text" name="email" value="" /></p>
</div>
<ul >
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
</body>
</html>
<?
}
?>

You have two issues here:
1. You are defining $count as a string, and never incrementing it. If you look over your code, $count is getting specifically set to 1 every time there is a mismatch. How is supposed to ever get to 2?
2. Furthermore, data here is stateless. How is the script supposed to know what $count was set to on the previous call? You need to also set $count as a session variable so that the script will know what its previous value.
You should try updating your code to something similar to this:
// Check if `email` passed in POST request:
if ($_POST['email']) {
$email = "website#test.com"; //Manually define expected email address.
// Check if provided email does *not* match the expected email:
if ($email !== $_POST['email']) {
// Record the mismatch attempt in session and increment:
if (!($_SESSION['incorrectEmailCount'])) {
// If this is the first mismatch, define the session variable, and set to 1.
$_SESSION['incorrectEmailCount'] = 1;
} else {
// Session variable already set due to previous mismatch. Increment it.
$_SESSION['incorrectEmailCount']++;
}
}
// If user entered incorrect email more than once:
if ($_SESSION['incorrectEmailCount'] > 1) {
// Redirect to error page and stop execution.
header("Location: /error.htm");
exit(0);
}
}

Once the form is submitted, the page reloads, resetting the counter. In order to actually count, you need to provide that value in the form and pass it along to the PHP when the form is submitted.
<?php
// Try to get the amount of attempts from the POSTed data
$count = isset($_POST['count']) ? $_POST['count'] : 0;
if (isset($_POST['email'])) {
$email = "website#test.com";
if ($email != $_POST['email']) {
$count++;
}
if ($count == 2) {
header("Location: /error.htm");
}
}
if ($count <= 2):
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form</title>
</head>
<body id="main_body" >
<div id="form_container">
<h1><a>Form</a></h1>
<form id="form_1123848" class="appnitro" method="post" action="">
<!-- Let the POST data know this is the x attempt -->
<input type="hidden" name="count" value="<?php echo $count; ?>">
<div class="form_description">
<h2>Form</h2>
<p> <input type="text" name="email" value="" /></p>
</div>
<ul>
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
</div>
</body>
</html>
<?php endif; ?>
Also, your coding style is far from consistent. Try to work on that!

Related

PHP Keep the variable scope even after the page reload

The website generates the random number from 1 to 100 when accessing the first page(page1.php). And the user will guess the number.
The first page contains
- a text box for accepting a
number from the user, and a submit button.
The second page(page2.php) will be returned to the user if the guess number is too high or too low. And the page shows a message telling the user "Too High" or "Too Low". The page also contains
a button(retry button) that allows the user to go back to the first page(page1.php) to re-enter a new number
a button that allows the user to quit the game.
The third page(page3.php) is returned to the user if the guess is correct. The page displays "Correct", the random number, and the count of tries.
And I have this index.php which is heart for all the pages. And here is the code.
index.php
<?php
$name = '';
$inputnumber = '';
$random = 33; //this is just an assumption to keep it simple
$message = '';
$guesscount = '';
if (isset($_POST['action'])) {
$action = $_POST['action'];
}
if ($action === 'guess') {
$guesscount = $_POST['$guesscount'];
$inputnumber = $_POST['$inputnumber'];
if ($inputnumber == $random) {
$message = "Correct!";
include 'page3.php';
}
if ($inputnumber > $random) {
$message = "Too High";
include 'page2.php';
}
if ($inputnumber < $random) {
$message = "Too Low";
include 'page2.php';
}
}
if ($action === 'retry') {
include 'page1.php';
}
page1.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guess</title>
</head>
<body>
<h1>Number Guess</h1>
<form name="myForm" action="index.php" method="post" >
Number Guess: <input type="text" name="$inputnumber" value="<?php if(isset($inputnumber)==1){
echo $inputnumber;}else echo ""; ?>" /><br>
<input type="submit" name="action" value="guess" />
<hr>
Guess Count: <?php echo $guesscount; ?>
</form>
</body>
</html>
page2.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guess</title>
</head>
<body>
<h1>Number Guess</h1>
<form name="myForm" action="index.php" method="post" >
Message: <?php echo $message; ?>
<input type="hidden" name="$guesscount" value="<?php echo $guesscount;?>"/><br>
<input type="submit" name="action" value="retry" />
<hr>
Guess Count: <?php echo $guesscount;?>
</form>
</body>
</html>
page3.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guess</title>
</head>
<body>
<h1>Number Guess</h1>
<form name="myForm" action="index.php" method="post" >
Message: <?php echo $message; ?>
Number of Tries: <?php echo $guesscount; ?>
<input type="submit" name="action" value="ok" />
</form>
</body>
</html>
page1.php is the page to load first.
Challenge I have faced is, I couldn't keep the $guesscount stable always. It keeps resetting on me. I have tried session but couldn't resolve it.Please help resolving it.
Thanks in advance.
I don't know why but my gut feeling tells me that the reason why the session is not working for you on other pages is because you do not initiate it ??
So what you have to do is:
index.php
<?php
session_start();
$_SESSION['myVariable'] = 'myVariable';
?>
page1.php
<?php
session_start();
$mySessionVar = $_SESSION['myVariable'];
var_dump($mySessionVar); // <- this should print myVariable
?>
You may get an error saying that $_SESSION is null or not set and to prevent that you can just enclose $_SESSION inside and isset method
if(isset($_SESSION['myVariable']) && $_SESSION['myVariable'] != null) {
$mySessionVar = $_SESSION['myVariable'[;
}

PHP $_SESSION Not checking login status

I've looked through multiple web articles and stackoverflow answers, however I cannot find the bug in my code. Maybe I've been looking at it too long.
Basically I'm just setting up a simple login for a demonstration, yes I know its inject-able and outdated, this doesn't matter. Basically I'm using a login with sessions and then redirecting the user to secure content when they're logged in. I've also created a script that checks for the session variables, to see if the user is logged in or not. Basically, I'm beating a dead horse and I don't know why this isn't working, could someone please help?
index.php:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome, please log in</title>
<link href="../css/admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<?PHP require_once"scripts/mysql_connect.php"; // Establish a database connection ?>
<div id="admin_top">
<div id="admin_logo"></div>
</div>
<div id="admin_login_box">
<H1 style="margin-left: 20px;">Please log in</H1>
<hr><br>
<?PHP
echo "<form method='post' action='checklogin.php' name='loginform'>
<input type='email' name='aEmail' placeholder='Your Email Address' required><br>
<input type='password' name='aPassword' placeholder='Password' required><br><br>
<input type='submit' value='Log In'>
</form>"
?>
</div>
</body>
</html>
checklogin.php:
<!doctype html>
<html>
<head>
<title>Checking login...</title>
<link href="../css/admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="admin_top">
<div id="admin_logo"></div>
</div>
<div id="admin_login_box">
<?php
require_once"scripts/mysql_connect.php";
$aEmail = $_POST['aEmail'];
$aPassword = $_POST['aPassword'];
$md5Password = MD5($aPassword);
$sql = "SQL";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$active = $row['active'];
$count = mysql_num_rows($result);
// If result matched, table row must be 1 row.
if($count == 1) {
$_SESSION["login"] = "OK";
$_SESSION["aEmail"] = $aEmail;
echo "<h1>Log in successfull!</h1>
<hr><br />
Your details checked out! Redirecting you now...";
// Wait 1 seconds then redirect to the secure content.
header("Location: http://www.website.com/secure_content.php");
} else {
echo "<h1>Log in unsuccessfull!</h1>
<hr><br />
Sorry. It seems your log in detials were incorrect. Please go back and try again.";
// Wait 2 seconds then redirect back to the log in page.
header("Location: http://www.website.com/index.php");
}
exit;
?>
</div>
</body>
</html>
loginstatus.php:
<?php session_start();
if(!(isset($_SESSION["login"]) && $_SESSION["login"] == "OK")) {
header("Location: http://www.website.com/index.php");
exit;
}
?>
Thanks for any help!
In checklogin.php and index.php you need to start the session. Add the following code before <!doctype html>
Add this code:
<?php session_start(); ?>
You forgot to put that line in this file because you are creating a new session during the checks in the database.
Looks like you haven't started the session in the first place. On the top of your page please write the following code:
<?php session_start(); ?>
Now, secondly, I'd suggest you to write your HTML and PHP separately instead of writing your HTML for the form within the echo.
Also, it's better if you add a name to your submit button.
Let me show a sample below.
<div id="admin_login_box">
<H1 style="margin-left: 20px;">Please log in</H1>
<hr><br>
<form method='POST' action='checklogin.php' name='loginform'>
<input type='email' name='aEmail' placeholder='Your Email Address' required><br>
<input type='password' name='aPassword' placeholder='Password' required><br><br>
<input type='submit' name='submit' value='Log In'>
</form>
Now, in your checklogin.php. you should place an isset condition and see if you're getting any POST request.
Try this:
<?php
require_once"scripts/mysql_connect.php";
if (isset($_POST['submit']) { // Add this condition
$aEmail = $_POST['aEmail'];
$aPassword = $_POST['aPassword'];
$md5Password = MD5($aPassword);
/* Other code */
if($count == 1) {
/* Other code */
} else {
/* Other code */
}
}
Hope this helps.

$_SESSION not storing values

I am having an issue with storing $_SESSION variables, i am a little new at PHP and I like it to the extent of my current knowledge.
first my creds:
Win 7 Pro 64
PHP 5
Remote Server(not sure of its config)
So what I am trying to do is set up a Login Page that contains a hardcoded username and password for testing purposes.
I want to display the username on a successor page to confirm it.
Login.php
<?php session_start();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head >
<title>Login</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-language" content="en-gb" />
<script type="text/javascript">
// Perform Client side validation of Username and Password
function redirect() {
var username = document.getElementById("username");
var password = (document.getElementById("password"));
if (!username.value == " ") {
if (!password.value == " ") {
if (username.value == "aknight") {
if (password.value == "00226291") {
window.location = "Home.php";
exit();
} else
alert("Username or Password Invalid");
}
} else
alert("Password is required");
} else
alert("Username is required");
}
</script>
</head>
<body>
<div id="header">
<h1>Product Order System</h1>
<br/>
<h2>The most expensive crap youll ever find...</h2>
</div>
<div id="content">
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$_SESSION['username'] = $_POST['username'];
}else{
?>
<form action="" method="POST">
<fieldset>
<legend>Login Information</legend>
<p>
<label for="Username">Username:</label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="Password">Password:</label>
<input type="password" name="password" id="password" />
</p>
<p>
<input type="button" name="login" value="Login" onclick="redirect();"/>
<input type="button" name="cancel" value="Cancel" />
</fieldset>
</form>
<?php }
include ('includes/footer.html');
?>
home.php
<?php
session_start();
$page_title = 'Home';
include ('includes/header.php');
if(isset($_SESSION['username'])) { $name = $_SESSION['username'];}else{echo "<p>error</p>";}
echo "<h3>Welcome ".$name."!</h3>" ;
?>
I have tried printing out the $_SESSION values and they are coming up empty.
producing this result
<?php
echo "<pre>".print_r($_SESSION)."</pre>";
?>
Array {
[username] =>
}
Please do not mind the JS, it is preschool client validation just to move forward.
Any help would be greatly appreciated.
Give your login form a name, and then in your JavaScript validation function, instead of window.location, do a document.forms['yourformname'].submit().
I think your Javascript validation is actually what's causing the issue.
You're setting the session variable in Login.php using the POST request, but no POST is actually being sent to Login.php since your Javascript is redirecting to Home.php once the form is considered valid. You need to submit the form at some point in the process, so you actually get some POST values which you'll use to populate your SESSION variables.
If you want to keep your Javascript validation, maybe have a look at submit() : http://www.w3schools.com/jsref/met_form_submit.asp
You'll have to set a correct action property on your form before submitting it.
So heres a fix that seems to be working
<?php session_start();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head >
<title>Login</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-language" content="en-gb" />
<script type="text/javascript">
// Perform Client side validation of Username and Password
function redirect() {
var username = document.getElementById("username");
var password = (document.getElementById("password"));
if (!username.value == " ") {
if (!password.value == " ") {
if (username.value == "aknight") {
if (password.value == "00226291") {
document.forms[0].submit();
exit();
} else
alert("Username or Password Invalid");
}
} else
alert("Password is required");
} else
alert("Username is required");
}
</script>
</head>
<body>
<div id="header">
<h1>Product Order System</h1>
<br/>
<h2>The most expensive crap youll ever find...</h2>
</div>
<div id="content">
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$_SESSION['username'] = $_POST['username'];
header('Location : ../Home.php');
}else{
?>
<form action="Home.php" name="login" method="POST">
<fieldset>
<legend>Login Information</legend>
<p>
<label for="Username">Username:</label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="Password">Password:</label>
<input type="password" name="password" id="password" />
</p>
<p>
<input type="button" name="login" value="Login" onclick=" redirect();"/>
<input type="button" name="cancel" value="Cancel" />
</fieldset>
</form>
<?php }
include ('includes/footer.html');
?>
Will post again if the nex series of pages has a similiar issue
Thanks

Php redirect on custom Post/get from webform

Hi all this is an easy question but right now i can't think about ..
I've a form where people can insert a personal code like "Abcdef301"
On submit i want to redirect them to url:
http://domain.tld/yoururls/Abcdef301
I've tried with some Post and Get (like the emails form but i've failed)
Any help?
<?php
if(isset($_POST['VAI'])) {
if(isset($_POST['text']) && $_POST['text'] != "") {
header("Location: http://domain.tld/yoururls/".$_POST['text']);
} else {
// handle error of no code in form field here if you want to
}
}
?>
<html>
<head>
<title>page title</title>
</head>
<div id="feedback-form">
<div class="success-block"></div>
<form action="" method="post">
<input name="text" placeholder="Inserire Codice Evento" required type="text">
<input type="submit" value="VAI" class="btn">
</form>
</div>
</html>
Should be what you're looking for.

Updating a Database With PHP

I'm trying to update my database records with the following code but am having no luck what so ever. Anybody care to help? Thanks
<?php include "base.php"; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Project Sproom</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<?php if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
if(!empty($_POST['username']) && !empty($_POST['email']))
{
$newusername = mysql_real_escape_string($_POST['username']);
$newemail = mysql_real_escape_string($_POST['email']);
$edit = mysql_query("UPDATE users (Username, EmailAddress) VALUES('".$newusername."', '".$newemail."') WHERE UserID=".$_SESSION['UserID']."");
// }
?>
<div id="container">
<div id="homemenu">
<ul id="navlist">
<li id="active">Home</li>
<li>Edit Profile</li>
</ul>
</div>
<div id="homemain">
<h1>Edit Profile</h1>
<p>This will be the edit profile when i have figured out how to do it...</p>
<br />
<form method="post" action="profile.php" name="editprofile" id="editprofile">
<label for="username">Username: </label> <input type="text" name="username" id="username" value="<?=$_SESSION['Username']?>"/><br />
<label for="email">E-Mail: </label> <input type="text" name="email" id="email" value="<?=$_SESSION['EmailAddress']?>"/> <br />
<input type="submit" name="editprofile" id="editprofile" value="Submit" />
</fieldset>
</form>
</div>
</div>
<?php
}
else
{
?>
<meta http-equiv="refresh" content="0;index.php">
<?php
}
?>
You're using INSERT syntax for an UPDATE query. The syntax should be like this:
UPDATE users SET Username = 'username', EmailAddress = 'email' WHERE UserID = 1;
Docs here.
You haven't connected to the MySQL database, have you?
I didn't see that in this code...
Or is that part of the included "base.php" on top of this script?
I am afraid you need fist establish a connection to a certain MySQL database before trying to update a row in a table.
Edit:
Okay, well then. Try issue the following line of code after the update:
echo "edit was " .$edit;
This is to check whether the update query was executed successfully (in which case it should echoes true) or failed (in which case it echoes false).
So at least you can tell the result of such a mysql_query.
$edit = mysql_query("UPDATE users SET Username='".$newusername."', EmailAddress='".$newemail."' WHERE UserID=".$_SESSION['UserID']."");
Try this

Categories