How to do a q&a validation in php with cookies - php

I would like create a script that is somewhat like a login. Before going to a certain page, they must answer a question correctly. If they get it right, then they proceed to the page. For example "What's your mom's name?" If the mom's name is Laurie, then they must enter this into a textbox and get it right to proceed.
Update
I used the script that oliver moran gave me to accomplish this. I added more questions so there is currently one question per page. After the final question has been answered, I have the page targeted to a place where they login, because I couldn't figure out how to do this simply based on the answer of the question. And I am fine with having the user login as a separate function. I have gotten the form to get them to login, and not let users that aren't logged in get to these pages. And the script works as long as they have kept the browser window open.
I have used the link that Oliver Moran gave on using sessions, and you can see in my code that I use sessions. But this does not solve the problem of keeping them logged in.
I would now like to know how to set a cookie once the user has logged in so they can leave the browser window and come back and still be logged in. I have searched this site for an answer, and couldn't find one that made sense. Here is my login code
<?php
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
if ($username&&$password) {
$connect = mysql_connect("127.0.0.1","root","") or die('Couldn\'t Connect to Database');
mysql_select_db ("login") or die('Couldn\'t find database');
$query = mysql_query("SELECT * FROM members WHERE username='$username'");
$numrows = mysql_num_rows($query);
if ($numrows !=0) {
while($rows = mysql_fetch_assoc($query)){
$dbusername = $rows['username'];
$dbpassword = $rows['password'];
}
if ($username==$dbusername&&$password==$dbpassword) {
echo "Login Successful. <a href='home.php'>Click here for the members area</a>";
$_SESSION['username'] = $dbusername;
}
else{
echo "Incorrect Password";
}
}
else{
die("Incorrect Username and Password");
}
}
else{
die("Please enter something in the boxes");
}
?>

Typically, a server-side language is used for this kind of thing. This is because, if you do password checking in JavaScript, anybody can see the correct password (since all the code is available by looking at the page's source code).
In order to do it securely, you'll need to submit the answer to a server and use a server-side language to check the answer. The server-side script then decides what response to give back to the user.
PHP is a very popular language for server side scripting. Here's the basics:
First we need a log in page (login.html) that has a HTML form in it, like this:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/>
<title>Login</title>
</head>
<body>
<form action="script.php" method="post">
<label>Enter your mom's name: <input type="text" name="mom" /></label>
<input type="submit" value="Submit" />
</form>
</body>
</html>
The important part here is the form. When the form is submitted, the data is sent to a PHP script called script.php.
That script looks like this:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/>
<title>Check login</title>
</head>
<body>
<?php
$mom = $_REQUEST['mom'];
$correct_answer = "Barbie";
if (!isset($mom) || $mom != $correct_answer) {
// nothing was submited or the name was incorrect
echo '<p>That\'s the wrong answer. Try again.</p>';
} else {
echo '<p>Welcome! That\'s the right answer.</p>';
}
?>
</body>
</html>
This is a fairly simple script. It checks what was submitted for 'mom'. If nothing was submitted or it was the wrong answer then a 'try again' message is shown. Otherwise, a 'welcome' message is shown.
The PHP logic (and so the correct answer) will not be visible in a web browser. Only the 'try again' or 'welcome' message will be sent down from the server.
This is the basics of working with HTML forms on the server side. I suggest you read up on using PHP. It's an easy and fun language (if inelegant, in my opinion). You can learn the basics here:
http://www.w3schools.com/php/default.asp
To test your code, you will need a web server. You can download and install a fully-fledged web server with PHP and MySQL (a database) from here:
http://www.wampserver.com/en/
With that, you can develop at test server-side code on your own machine. To test the above example, copy the code above into two files, called login.html and script.php, and put them into the www directory of WAMP.
Good luck!

This is what I managed to come up with. At the top of the page, insert this code before the <!DOCTYPE html>
<?php
//Check for existance of cookie from right answer
if(isset($_COOKIE['parents'])){
header("Location:q1.html");//Move on to next question
}
//Checks answer
if(array_key_exists("dad", $_POST) && array_key_exists('mom', $_POST)){
$dad = $_POST["dad"];
$mom = $_POST["mom"];
$dcorrect = array("Dad", "dad");
$mcorrect = array("Mom", "mom");
if(in_array($dad, $dcorrect) && in_array($mom, $mcorrect)){
setcookie('parents', '1' ,time()+60*60*24);
header("Location: index.html");
}else{
$wrong="<div class='error'>Wrong answer</div>";
}
}
?>
With this HTML
<form action="index.html" method="post">
<label>Enter your father's name:</label>
<input required autocomplete="off" type="text" name="dad" placeholder="Bill">
<label>Enter your mother's name:</label>
<input required autocomplete="off" type="text" name="mom" placeholder="Billette">
<input type="submit" value="Press me when you think you are right" />
<?php echo $wrong; ?>
</form>

Related

How to display error messages on redirect?

It's worth noting I'm new to php. I would like to have an answer in php as well (if possible).
Here's what I'm trying to achieve: I want to redirect the user if any errors I check for are found to a html/php form (that the user see's first where inputs are previously created) with custom error messages that come from a file separate to the html/php form.
Details: The User see's the HTML/PHP form first where they enter names in a csv format. After they click create, the names are processed in another file of just php where the names are checked for errors and other such things. If an error is found I want the User to be redirected to the HTML/PHP form where they can fix the errors and whatever corresponding error messages are displayed. Once they fix the names the User can click the 'create user' button and processed again (without errors hopefully) and upon completion, redirect user to a page where names and such things are displayed. The redirect happens after the headers are sent. From what I've read this isn't the best thing but, for now, it'll do for me.
Code For HTML/PHP form:
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formInputNames"><br>
Activate: <input type="checkbox" name="activate">
</form>
<?php
// include 'processForm.php';
// errorCheck($fullname,$nameSplit,$formInputNames);
?>
</body>
</html>
I tried messing around with 'include' but it doesn't seem to do anything, however, I kept it here to help illustrate what I'm trying to achieve.
Code For Process:
$formInputNames = $_POST['names'];
$active = (isset($_POST['activate'])) ? $_POST['activate'] : false;
//checks if activate checkbox is being used
$email = '#grabby.com';
echo "<br>";
echo "<br>";
$fullnames = explode(", ", $_POST['names']);
if ($active == true) {
$active = '1';
//sets activate checkbox to '1' if it has been selected
}
/*----------------------Function to Insert User---------------------------*/
A Function is here to place names and other fields in database.
/*-------------------------End Function to Insert User--------------------*/
/*-----------------------Function for Errors---------------------*/
function errorCheck($fullname,$nameSplit,$formInputNames){
if ($formInputNames == empty($fullname)){
echo 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[0])) {
echo 'Error: First Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[1])) {
echo 'Error: Last Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif (preg_match('/[^A-Za-z, ]/', $fullname)) {
echo 'Error: Found Illegal Character in: '.$fullname.'<br><br>';
redirect('form.php');
}
}
/*-----------------------------End Function for Errors------------------------*/
/*--------------------------Function for Redirect-------------------------*/
function redirect($url){
$string = '<script type="text/javascript">';
$string .= 'window.location = "' .$url. '"';
$string .= '</script>';
echo $string;
}
/*-------------------------End Function for Redirect-----------------------*/
// Connect to database
I connect to the database here
foreach ($fullnames as $fullname) {
$nameSplit = explode(" ", $fullname);
//opens the database
I Open the database here
errorCheck($fullname,$nameSplit,$formInputNames);
$firstName = $nameSplit[0];//sets first part of name to first name
$lastName = $nameSplit[1];//sets second part of name to last name
$emailUser = $nameSplit[0].$email;//sets first part and adds email extension
newUser($firstName,$lastName,$emailUser,$active,$conn);
redirect('viewAll.php');
//echo '<META HTTP-EQUIV="Refresh" Content="0; URL=viewAll.php">';
//if you try this code out, you can see my redirect to viewAll doesn't work when errors are found...I would appreciate help fixing this as well. My immediate fix is using the line under it but I don't like it.
}
All the research I've done hasn't gotten me far. I understand that sending the headers isn't good practice. I looked at ob_open (php function-I think it was called) and couldn't figure out how to properly use it. I couldn't find a question on here that satisfied the conditions I'm trying to meet either.
Any help is certainly appreciated.Thank You
EDIT: This is not a duplicate of 'Passing error messages in PHP'.
-------While the idea is similar, they are 'Passing error messages in PHP' before the headers are sent. Therefore it's not the same.
Store the error in a session and echo it on the destination page.
Put session_start() at the top of the code of the form.php page. Like this:
<?php session_start(); ?>
<!DOCTYPE HTML>
<HTML>
<head>
Then replace the echo error with:
$_SESSION['error'] = 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
Use this in your conditions instead of the echo. Then in the form.php page:
if (isset($_SESSION['error'])) {
echo $_SESSION['error'];
unset($_SESSION['error']);
}
The unset makes sure that the error is repeated.
An HTTP Redirect causes a new HTTP request. Since php is stateless, it cannot natively support remembering a message to display to a specific user in another request. In order to get around this limitation, you would need to use a stateful storage mechanism (session or cookies), or pass the error message along to the next request via query string parameter. The usual way this is handled is by using session storage to save flash messages.
Here is a library that can make it a bit easier for you https://github.com/plasticbrain/PhpFlashMessages
Set session of error and display on the page on which you are redirecting

How to directly send php to another page?

I am new to programming and am using html, mySQL and PHP to try and make a user name and password setup for user profiles. I then want to display a customized page to the user.
The problem is, after I check to see if they are in the database, or not in the database, I can't figure out how to send them directly to a new page.
I've tried using a function I found on google called header() but I keep getting an error. I tried resolving it by making sure I had no output to the screen before using the header() function, and I'm pretty sure by now that I don't. I don't actually know what the problem is and am trying to find another way to do this or just find an answer with header(). Anyhow, here's my code:
<?php
require "connect_to_mysql_and_test_connection.php";
//use the variable $db to access the database
?>
<html>
<head>
<title>User Login</title>
<h2>Login:</h2>
</head>
<body>
<!--this makes a form to take the user input. the input of username and password. the submit buttons value is always submitted to $_POST-->
<form method="post">
Create user name:<br>
<input type="text" name="username" /><br>
Create password:<br>
<input type="text" name="password"/><br>
<input type="submit" name="submit"/><br>
</form>
<?php
$compare_username="";
$compare_password="";
//get the username and password fields from the database and store it in a variable
$username_password_fields=$db->query("SELECT username, password FROM users");//mysql object
//get number of rows
$rows= $username_password_fields->num_rows;
//create a while loop to go through each row.
while($rows >=1){
//iterate through each array returned by fetch_assoc to see if the username already exists
foreach($username_password_fields->fetch_assoc() as $key=>$value){
//echo $key . $value . "<br>";
//************check to see if the username exists****************
if ($value === $_POST['username']){
$compare_username=$value;
}
else if ($value === $_POST['password']){
$compare_password=$value;
}
}
//check to see if the username matches the password
$rows -= 1;//decrement the rows remaining
if ($compare_username != "" and $compare_password != ""){
//write code to send them to their custom page
**header("Location:http://jasongriffore.atwebpages.com/myfirstworkingsite.php")<--This is the problem. please help!**
echo "Ding ding ding a match!";
return;
}
else if ($compare_username != ""){
echo "This user name exists but the password is incorrect";
//they can try again on the same page
return;
}
}
//if after running the while loop they didn't get sent to their custom page, the must be new!
echo "Let's create a new account for you!";
//enter code to add a new user to the database
echo print_r($_POST, true);
?>
Use header() function:
header('Location: mypage.php');
And be sure there is no output sent to the browser before you do so as I can see there is because your HTML <form> is before your PHP treatment. Change that.
I would recommend using ob_start() and ob_end_flush() to buffer your output to the browser. You can read a little more about this here. The main reason you want to do this is because, the header tag requires that no output has been sent to the browser yet. By echoing out <html><head>... it's already sent data to the client, therefore no more headers can be sent (They are headers after all, intended to head the output.) ob_start() will buffer (Or store) everything until you're ready to output it, and will allow you later on to send headers because the output has not been sent to the browser yet.
<?php
require "connect_to_mysql_and_test_connection.php";
//use the variable $db to access the database
//Buffer the output
ob_start();
?>
<html>
<head>
<title>User Login</title>
<h2>Login:</h2>
</head>
<body>
<!--this makes a form to take the user input. the input of username and password. the submit buttons value is always submitted to $_POST-->
<form method="post">
Create user name:<br>
<input type="text" name="username" /><br>
Create password:<br>
<input type="text" name="password"/><br>
<input type="submit" name="submit"/><br>
</form>
<?php
$compare_username="";
$compare_password="";
//get the username and password fields from the database and store it in a variable
$username_password_fields=$db->query("SELECT username, password FROM users");//mysql object
//get number of rows
$rows= $username_password_fields->num_rows;
//create a while loop to go through each row.
while($rows >=1){
//iterate through each array returned by fetch_assoc to see if the username already exists
foreach($username_password_fields->fetch_assoc() as $key=>$value){
//echo $key . $value . "<br>";
//************check to see if the username exists****************
if ($value === $_POST['username']){
$compare_username=$value;
}
else if ($value === $_POST['password']){
$compare_password=$value;
}
}
//check to see if the username matches the password
$rows -= 1;//decrement the rows remaining
if ($compare_username != "" and $compare_password != ""){
//write code to send them to their custom page
header("Location:http://jasongriffore.atwebpages.com/myfirstworkingsite.php");
return;
}
else if ($compare_username != ""){
echo "This user name exists but the password is incorrect";
//they can try again on the same page
return;
}
}
//if after running the while loop they didn't get sent to their custom page, the must be new!
echo "Let's create a new account for you!";
//enter code to add a new user to the database
echo print_r($_POST, true);
//Write the output to the browser
ob_end_flush();
?>
Use javascript :
<script>window.location = 'http://jasongriffore.atwebpages.com/myfirstworkingsite.php';</script>

PHP cookies setting

I hate to say it but I have been working on what should have been a 30 minute assignment for a good 6 hours now with little to no progress. I am attempting to capture a name and email in a form, and set them to cookies that will last 10 minutes. While the cookies are active, the page should skip the form and just display the input. I have tried this with both cookies and sessions and cannot get it to work.
At this point I have written and deleted at least a hundred lines of code and just can't really see what the problem is. This is my first time working with PHP. Any help would be appreciated.
Currently this code creates the form, takes the info and posts it to the page correctly. When I go back to the page, it shows the form again. I assume this means the cookie isn't setting / sticking.
<?php
if (!empty($_POST)) {
setcookie('Cname',$_POST['name'], time()+600);
setcookie('Cemail', $_POST['email'], time()+600);
// header("Location:HW2.php");
}
?>
<html>
<head>
<title> Assignment 2 Alcausin </title>
</head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
$visibleForm = True;
if(isset($_COOKIE['name'])){
$visibleForm = False;
}
if(isset($_POST['submit'])){
$visibleForm = False;
echo "Your Name: ";
echo $_COOKIE['Cname'];
echo "<br>";
echo "Your Email: ";
echo $_COOKIE['Cemail'];
}
if($visibleForm){ // close php if form is displayed
?>
<form action ="HW2.php" method="post">
Name:<font color = red>*</font> <input type="text" name="name"><br>
E-mail:<font color = red>*</font> <input type="text" name="email"><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php // back to php
}
?>
</body>
</html>
I rewrote your script using sessions, so that your data is actually stored on the server and the client only has a session cookie which is a reference to the server-side data, so the client has no way of tampering with that data.
While this may not be important for your homework, this is definitely important when you deal with user accounts and privileges (imagine an "admin" cookie that tells if the user is admin or not - anyone can manually set that cookie and that's it, he's an admin on your website).
This wasn't tested and may not work at all - feel free to downvote my answer if that's the case.
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
ini_set("session.cookie_lifetime","600"); // sets the session cookie's lifetime to 10 minutes / 600 seconds
session_start(); // starts the session, this will create a new session cookie on the client if there's not one already
if (isset($_POST["name"]) && isset($_POST["email"])) { // if there's POST data
$_SESSION["name"] = $_POST["name"]; // this saves your values to the session so you can retrieve them later
$_SESSION["email"] = $_POST["email"]; // same here
};
?>
<html>
<head>
<title> Assignment 2 Alcausin </title>
</head>
<body>
<?php
$visibleForm = !isset($_SESSION["name"]); // visibleForm will be the opposite of isset, so if there's a "name" in the session then the form will be invisible
if ($visibleForm) { // if there's no session data, we display the form
echo '<form action ="HW2.php" method="post">Name:<font color = red>*</font> <input type="text" name="name"><br>E-mail:<font color = red>*</font> <input type="text" name="email"><br><input type="submit" name="submit" value="Submit"></form>';
} else { // this means there is some data in the session and we display that instead of the form
echo "Your Name: ";
echo $_SESSION["name"];
echo "<br>";
echo "Your Email: ";
echo $_SESSION["email"];
};
?>
</body>
</html>
First of all, you must add the session_start() at the highest level of your code as it is essential for any of this to work. session_start() actually generates the PHPSESSID cookie and is also the session identifier; you won't need to set anything to the PHPSESSID cookie using setcookie() if you use session_start().
For a basic way to do what you're trying to achieve, I'd try to set sessions whenever the page loads and if there is a current session, then it will skip the form like you said.
$_SESSION['SESSID'] = $someVar;
$_SESSION['SESSNAME'] = "someOtherVar";
Then right before your form, check if any of those are set by using
if(isset($someVar) && isset($someOtherVar))
You know the deal.
Then create a button that does a session_destroy() so that it ends the current session.

php login script using specific username and password by session id

I wish some help .
I need a php script using session id to redirect a specific username and password log in
to a specific html form as no one except that user can reach links without logging in by this username and password (i.e no one can copy the link after logging in at another browser and proceed) . Something like admin area or something.
(note : i'll specify name and password by myself not by retrieving it from database ,So no SQL scripts needed)
I searched too much in that and couldn't find something helps .
appreciate ur effort in advance .
On special_form.php and/or other similar pages put something like this:
check_login();
Where check_login() is something like this:
function check_login() {
if ($_SESSION['login'] == true AND !empty($_SESSION['user_id')) {
if ($_SESSION['username'] != 'MyUser' OR $_SESSION['password'] != 'MyPass') {
header('Location: http://www.domain.com/login.php');
}
} else {
header('Location: http://www.domain.com/login.php');
}
}
Now, on login-process.php write something like this:
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
if ($_SESSION['username'] == 'MyUser' AND $_SESSION['password'] == 'MyPass') {
header('Location: http://www.domain.com/special_form.php');
}
// normal login process code
I just hope that I've understood your problem correctly. Give me some hints if I'm wrong somewhere. :)
Put this on top of all pages to check if logged in:
if(!isset($_SESSION['loggedin'] ||
!$_SESSION['loggedin']==1) header('Location: http://website.com/login.php');
Html form on login.php
<?php
//And just check post variables from form:
if(isset($_POST['submit'])) {
if(strcmp($_POST['username'], 'Your username') == 0 &&
(strcmp($_POST['password'], 'Your password') == 0) {
$_SESSION['loggedin'] = 1;
header('Location: http://website.com/youareloggedin.php');
}
}
?>
<form action="" method="post">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" />
</form>
Some tips:
do not write anything to page before calling header function, it will break it.
A blank action on form will send data to itself, make sure php is on top (it is generally easier to keep all php on top and use inline php when needed e.g. <?=functionorvariable()?>
strcmp compares two strings, if they are equal it will give you zero as a return value.
always use isset to check if form was actually submitted on page instead of checking values.
you should add in error checking for checking post values, to see if they are empty or whatever, it is good practice.
learn by doing, please study the structure of this program and see how it is clearly written, it's intentions are clear. Always follow the clarity route when coding.
Good luck

how to show error message if someone left a field blank

So I created this page where a user can send data to a msql database but when they leave a field blank and they click submit I want an error to show up saying "You left a field blank".
This is the code:
<?php
$hostname = "";
$db_user = "";
$db_password = "";
$database = "";
$db_table = "";
# STOP HERE
####################################################################
# THIS CODE IS USED TO CONNECT TO THE MYSQL DATABASE
$db = mysql_connect($hostname, $db_user, $db_password);
mysql_select_db($database,$db);
?>
<html>
<head>
<title>Add your url to out database</title>
</head>
<body>
<?php
if (isset($_REQUEST['Submit'])) {
# THIS CODE TELL MYSQL TO INSERT THE DATA FROM THE FORM INTO YOUR MYSQL TABLE
$sql = "INSERT INTO $db_table(title,description,url,keywords) values ('".mysql_real_escape_string(stripslashes($_REQUEST['title']))."','".mysql_real_escape_string(stripslashes($_REQUEST['description']))."','".mysql_real_escape_string(stripslashes($_REQUEST['url']))."','".mysql_real_escape_string(stripslashes($_REQUEST['keywords']))."')";
if($result = mysql_query($sql ,$db)) {
echo '<h1>Thank you</h1>Your information has been entered into our database<br><br>';
} else {
echo "ERROR: ".mysql_error();
}
} else {
?>
<h1><center><img src='addalink.png'><center></h1>
<hr>
<center>
<form method="post" action="">
Name of the song:<br>
<input type="text" name="title"><br>
Artist: <br>
<input type="text" name="description"><br>
Download link: <br>
<font color="#0000FF">http://</font><input type="text" name="url"><br>
<input type="submit" name="Submit" value="Submit">
</form></br>
<?php
}
?> <center>
</body>
</html>
First of all, use a CSS style to style your form's inputs. It's a lot easier to read, and it means if you need to change anything in the future it's quick.
What you're wanting to do is run a script on submit that checks whether or not the values in the required fields are what you expect.
The jQuery Validation Plugin - http://bassistance.de/jquery-plugins/jquery-plugin-validation/ takes care of what you want.
If you want to write your own, it's a process of attaching the validation function to the click event of the submit button (or the onSubmit event of the form) and checking the data that's in the form.
If the data is missing, you add a class to show this. If the data is valid, you remove the previous class.
Finally, you only return true (to submit the form) in the case everything validates.
Keep in mind this is only client side, you still need to validate your data server side for security.
So, the common response is "do this on the front-end". If anything you are posting has security implications then I'd also recommend you check your form data on the back-end.
Also if you're going to go through the process of using mysql_real_escape, you might as well use mysqli and parameterized queries see: http://us2.php.net/manual/en/mysqli-stmt.prepare.php.
If you choose to go the back-end route, especially if you are using AJAX for the post, you can throw an Exception that actually outputs a 500 error along with the message you want to display, and then use Javascript to handle the "error case", so you can provide really nice validation methods that still do the validation on the server side.

Categories