Undefined index using more than one form - php

Here's my problem:
I have two forms on the same page.
The first form works fine.
But whenever I click the submit button on the second form, I get two notices.
The first says "undefined index: email" which is referring to "$email = $_POST["email"];" in my coding.
The second says "undefined index: password" which is referring to "$password = $_POST["password"];" in my coding.
I do not want my 2nd form to be affected by all the "if statements" I created for the first form. And I'm going to be creating more "if statements" for the 2nd form soon.
For example, when I hit the submit button on the second form, it's echoing "You need to enter an email and password" which is an error I only wanted applied to the first form.
So MY QUESTION IS: How can I get the forms to only be affected by a specific group of "if statements"? Like in css coding you apply ids, but what would i do to the forms or "if statements" so the "if statements" only affect specific forms?
Here's the coding:
<form action="login.php" method="post">
<ul id="login">
//login information
<li id="loginn">
<input type="submit" value="Log in">
</li>
</ul>
</form>
<form action="" method="post">
<ul id="register">
//register info list items
<li>
<input type="submit" value="Sign up">
</li>
</ul>
</form>
<?php
if (empty($_POST) === false) {
$email = $_POST["email"];
$password = $_POST["password"];
if (empty($email) === true || empty($password) === true) {
$errors[] = "You need to enter an email and password.";
} else if (user_exists($email) === false) {
$errors[] = "The email you entered is not in our records. Have you registered?";
} else if (user_active($email) === false) {
$errors[] = "Go to your email, open the email we sent you,and activate your account.";
} else {$login = login($email, $password);
if ($login === false) {
$errors[] = "That email/password combination is incorrect.";
} else {
$_SESSION['users_id'] = $login;
header('Location: homepage.php');
exit();
}
}
}
if (empty($errors) === false) {
?>
<?php
echo output_errors($errors);
}
?>

You could add a <hidden> form field with the form's name:
<input type="hidden" name="formname" value="form1">
Then, in the PHP, use that to discern the forms:
if ($_POST['formname'] == "form1") {
// ifs for first form
}
(Note there is no error checking whatsoever in this code!)

Related

How to redirect parent page from iframe popup?

So I have a page where when user click on login button, it will open up an iframe popup with a login form. So, if the user submitted the correct username/password, it will redirect the parent page to let say Main.php. However, I wasn't able to achieve this as it keeps on redirecting it in the iframe popup. How do I achieve this? I'm fairly new to php so please clarify your answer.
Here's the code snippet that processes the login. Tell me if you need more. Thank you.
<?php
include '../Initialization.php';
if (empty ($_POST) === false) {
$username = $_POST ['username'];
$password = $_POST ['password'];
if (empty ($username) === true || empty ($password) === true) {
$errors[] = 'You need to enter a username and password!';
} else if (user_exists ($username) === false) {
$errors[] = 'We can\'t find the username you entered. Have you registered?';
} else if (user_active ($username) === false) {
$errors[] = 'You haven\'t activated your account!';
} else {
$login = login($username, $password);
if ($login === false) {
$errors[] = 'That username/password combination is incorrect!';
} else {
$_SESSION['user_id'] = $login;
header("Refresh:0; url=../../Main.php"); //Am I doing anything wrong here?
exit();
}
}
print_r ($errors);
}
?>
The link that will open up the iframe :
<a class='iframe' href="Login.php" style="text-decoration:none; color:#FFF">LET'S GO</a
The login form :
<form action = "Core/System/LoginProcess.php" method="post">
<p>
<input name="username" type="text" class="textBox" id="username2" placeholder = "Username" onblur="this.value=removeSpaces(this.value);"/>
<br />
<br />
<input name="password" type="password" class="textBox" id="password" placeholder = "Password" />
</p>
<p> </p>
<p>
<input name="Login" type="submit" class="loginButton" id="Login" value="Login" />
</p>
</form>

How to validate a form in PHP, then redirect to an external page

I'm trying to validate a registration form using HTML and PHP, and insert the data into an SQL database. Upon registration, I'd like for my user to be directed to their personal dashboard. I can get everything to work except for the redirect upon form submission.
Here is the PHP at the start of the page:
<?php
// define variables and set to empty values
$emailErr = $passErr = $confirmErr = $email = $pass = $confirm = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["pass"])) {
$passErr = "You must have a password";
} else {
$pass = test_input($_POST["pass"]);
}
if (empty($_POST["confirm"])) {
$confirmErr = "You must confirm your password";
} else {
$confirm = test_input($_POST["confirm"]);
}
if ($pass != $confirm) {
$confirmErr = "Your passwords must match";
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = test_input($_POST["email"]);
$pass = test_input($_POST["pass"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
And my HTML form:
<div class="container">
<form class="form-signin" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<h2 class="form-signin-heading">Register below:</h2>
<span class="error"><?php echo $emailErr;?></span>
<input type='email' class="form-control" placeholder="enter email..." name='email'/>
<span class="error"><?php echo $passErr;?></span>
<input type='password' class="form-control" placeholder="enter password" name='pass'/><span class="error"><?php echo $confirmErr;?></span>
<input type='password' class="form-control" placeholder="confirm password" name='confirm'/>
<input type='submit' class="btn btn-success btn-block" name="submit" value="submit">
<h5>Already have an account? Log in.</h5>
</form>
</div>
Note the use of
<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
on
<form action="">
param. Using this function I can't get a redirect.
I've included my SQL entries following the HTML, and the entries are working just fine, but the header(); tag doesn't seem to work. See here:
<?php
$email = $_POST['email'];
$pass = md5($_POST['pass']);
// Database connection
require 'database.php';
$sql = "SELECT email FROM users WHERE email = '".$email."'";
$result = $conn->query($sql);
$row_count = $result->num_rows;
if ($row_count == 1) {
// user already exists
header('Location: login.php');
} elseif ($row_count > 1) {
// just to double check multiple entries aren't input into the DB
echo 'There are too many records with that name!';
} else {
// enter user into DB
$sql = "INSERT INTO users (email, pass)
VALUES ('".$email."', '".$pass."')";
if ($conn->query($sql) === TRUE) {
header('Location: dashboard.php');
exit();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli_close($conn);
}
?>
Any ideas what I'm doing wrong?
hi i have seen you code in your code you are using login.php for redirecting from header tag.
and in html file you are using login.html file for checking account is exists or not.
Please check file extension for your login file.
you can use following link for header function details:
PHP header(Location: ...): Force URL change in address bar
If I understand it right, what you can do is redirect back to your page with the link :
<form name="form-lignin" method="post" action="this-php-page.php">
On the same page you can then create a section that will show up only if the form has been submitted and the form will be hidden. The section can be personalised for each user then as well.
You can do this by adding a hidden field to your form.
<input type='hidden' name='submission' value="something"/>
Then you can add this php :
if ($_POST["submission"]=="something") {
*Dashboard content?*
} else {
*The actual form...*
}
Hope this helped :)
1.you need ensure the code has run
if ($conn->query($sql) === TRUE) {
echo 'is run!';exit;
header('Location: dashboard.php');
exit();
}
and you can use if ($conn->query($sql)) instand if ($conn->query($sql) === TRUE)
2.notice ,if the "exit;" code run ,"mysqli_close($conn);" will useless。
You first need to put all your php code above the html so that the html output will be sent to the browser after execution of the validation script.
Then
1 Capture form values
2 Validate form values
3 If Every thing is ok. Then sanitize the input and insert it into the database.
4 if insert successful, Redirect it to another page, Using header('location:http://example.com');
Thats it

Hold register details after error message to prevent re-entering of data

How can I hold the half entered details that a user when attempting to create a user for my webpage?
If, for example, the user only fills out the 'USERNAME' field, I want the error to flag, redirecting them back to the register page, but I want the fields that they previously entered to remain filled.
Any ideas please? :(
The Register Page
<!DOCTYPE html>
<html>
<head>
<title>The Classic - Vintage Cinema Reviews</title>
<link href="CSS.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" href="favicon.ico">
<meta name="description" content="A unique, ground-breaking website for all things relating to classical cinema. The Classic revolutionises the way that we see classic cinema, and provides the movie goer with an opportunity to find all the reviews they need!">
<meta name="author" content="Stefan Batterbee">
<meta charset="UTF-8">
</head>
<body>
<div id="page">
<header> <?php
session_start();
if(isset($_SESSION['Logged_In']))
{
header('Location: index.php');
}
else
{
echo '<br>';
echo 'You are not logged in!<br>';
echo 'Click here to log in,<br>';
echo 'or register below.';
}
?>
</header>
<nav>
<ul id="navigation">
<li>H O M E </li>
<li>F I L M R E V I E W S </li>
<li>A R T I C L E S</li>
<li>A B O U T U S</li>
</ul>
</nav>
<div id="breadcrumbs">
<a class="link" href="index.php">Home</a> > Register
</div>
<div id="main">
<centre>
<?php
if( isset($_SESSION['ERROR_MESSAGE']) && is_array($_SESSION['ERROR_MESSAGE']) && count($_SESSION['ERROR_MESSAGE']) >0 ) {
echo '<h3 style="color:#F00;">';
foreach($_SESSION['ERROR_MESSAGE'] as $msg) {
echo $msg;
}
echo '</h3><br>';
unset($_SESSION['ERROR_MESSAGE']);
}
?>
<br>
<center><h1>Welcome to The Classic!</h1><br>
<h3>You can create an account below to become an exclusive member of our website.<br>
Just simply fill our your details below, and we will create your account!<br>
<p>If you already have an account, please go to the log in page.</p></h3></center><br><br>
</centre>
<div id="loginbox">
<form method="post" action="regprocess.php">
<h3>Username:</h3>
<input type="text" name="username" value=""/><br>
<h3>Password:</h3>
<input type="password" name="password" /><br>
<h3>Confirm Password:</h3>
<input type="password" name="password2" /><br>
<h3>First Name:</h3>
<input type="text" name="fname" value=""/><br>
<h3>Surname:</h3>
<input type="text" name="lname" value=""/><br><br>
<input type="submit" name="submit" value="Create your account!" /><br><br>
Already a user? Log in <a class="link" href="register.php">HERE</a><br>
</form>
</div><br><br>
</div>
<footer>
<p class="textleft">Created by Stefan Batterbee (2013)</p>
<p class="textright">Click <a class="link" href="https://www.facebook.com/the.classic.cinema.reviews">HERE</a> to access our Facebook page.</p>
</footer>
</div>
</body>
</html>
The Processing Script
<?php
session_start();
include"config.php";
$error_message = array();
$error = false;
$username = $_POST['username'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
if($username == '') {
$error_message[] = 'Please enter a username.';
$error = true;
}
if($password == '') {
$error_message[] = 'Please enter a password.';
$error = true;
}
if($password2 == '') {
$error_message[] = 'Please enter a confirmation of your password.';
$error = true;
}
if($fname == '') {
$error_message[] = 'Please enter a first name.';
$error = true;
}
if($lname == '') {
$error_message[] = 'Please enter a last name.';
$error = true;
}
if ($password != $password2)
{
$error_message[] = 'Your passwords did not match, please try again!';
$error = true;
}
if ($username && $password && $password2 && $fname && $lname != '' and $password == $password2) {
$insert = 'INSERT INTO USER(USERNAME, PASSWORD, FIRST_NAME, SURNAME) VALUES("'.$username.'","'.$password.'","'.$fname.'","'.$lname.'")';
}
mysql_query($insert);
header('location: log_in.php');
if($error) {
$_SESSION['ERROR_MESSAGE'] = $error_message;
session_write_close();
header("location: register.php");
exit();
}
?>
In each value spot of each input, echo the posted value of that input.
<h3>Username:</h3>
<input type="text" name="username"
value="<?php if(isset($_POST['username'])) echo $_POST['username']; ?>"/><br>
You check for isset first to see if it is in the post, and if it is, put it back into the input.
EDIT:
I forgot to add that you should do the processing on the same page, rather than doing a redirect. That is what allows the post values to stick around so you can refill them into the form. It will also make it no longer necessary to put your error message into a SESSION variable.
EDIT 2:
As was commented, you can also fill the post into the session. The reason I don't do this is that, if a) the session were hijacked, or b) it's a public computer and someone else sits down at it, the person's registration data would show up again on the registration form. If you choose to set the post values into the session, I strongly suggest that, at the end of printing out the form, you unset all the registration session values. They will be lost on a page refresh, but it's more secure for the user. It's a good idea to do this for your error message also, unless you want that error message to be stuck on the page forever. E.g.:
//after the </form> tag
unset($_SESSION['ERROR_MESSAGE']);
unset($_SESSION['username']);
// ... and so forth for the rest
As per your request:
Using sessions could work better if you're planning on using your code in two seperate pages.
You would first assign your session name to your POST name:
$_SESSION['username'] = $_POST['username'];
then using it inside your input element:
<input type="text" name="username" value="<?php if(isset($_SESSION['username'])) echo $_SESSION['username']; ?>"/>
That's what I use myself. It's another option.
However, using ob_start() is usually required when using sessions, by placing it on top of session_start(); yet required since you are using header(). Not using ob_start(); will result in an headers already sent error message.
For example:
<?php
ob_start();
session_start();
// ...
Footnotes: session_start(); must reside inside all files using the same session(s).

PHP change post target when user logs in successfully

Here is my form that is using login.php to check if the user is registered, etc.
<form action="login.php" method="post" target="SHOW">
<ul id="login">
<li>
Username:<br />
<input type="text" name="username">
</li>
<li>
Password:<br />
<input type="password" name="password">
</li>
<li>
Submit:
<br />
<input type="submit" name="log in">
</li>
<li>
Register</li>
</ul>
</form>
<iframe id="iframe" name="SHOW" scrolling="no"></iframe>
My dilemma stems with the iframe tags I'm using to display the error messages. If the user is registered I would like to redirect him back to index.php as you can see at the end of the PHP ---> header('Location: index.php');
Problem is that iframe doesn't allow for redirecting. So, I would like to change the target from ---> target="SHOW" to target="_top" or something like that. So, the user is redirected after successfully logging in without using any JavaScript.
My failed attempt at accomplishing this --> $href->removeAttribute('target');
$href->setAttribute("target", "_top");
Here is login.php.
<?php
include 'core/init.php';
if(empty($_POST) === false){
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username) || empty($password) === true){
$errors[] = 'You need to enter a username and password';
} else if (user_exists($username) === false){
$errors[] = 'We can\'t find that username. Have you registered?';
} else if (user_active($username) === false){
$errors[] = 'You haven\'t activated your account!';
} else {
$login = login($username, $password);
if($login === false){
$errors[] = 'That username/password combination is incorrect';
} else {
$_SESSION['user_id'] = $login;
$href->removeAttribute('target');
$href->setAttribute("target", "_top");
header('Location: index.php');
exit();
}
}
print_r($errors);
}
?>
Since you're POST-ing to the iframe, any action taken by the response will only be valid for the context of the iframe itself, which means that doing a regular HTTP redirection will only change the content of the iframe.
If you want to keep the iframe (which I'd advice against, and instead keep both the error handling and logging in the same controller / file that displays the form), you can redirect by using javascript in your iframe response:
<script type="text/javascript">
parent.location.href = 'http://www.bbc.co.uk/';
</script>
Not pretty, but it works.

$errors[] not returning

I am working on building a PHP login and registration system for my website. The coding calls for using $errors[] if form fields are empty and functions to check if the input username exist on the database. I am not recieving any errors, even if I do not put in any information.
login.php
<?php
include 'cic/initalize.php';
if (user_exists('cassey') === true) {
echo 'exists';
}
die();
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'Please provide your username and password.';
} else if (user_exists($username) === false) {
$errors[] = 'We can\'t find the username entered, please enter a valid
username or register to continue';
}
}
?>
clients.php (users)
<?php
function user_exists($username) {
$username = sanitize($username);
return (mysql_result(mysql_query("SELECT userId FROM clients WHERE
username = '$username'"), 0) === 1) ? true : false;
}
?>
code that calls login.php
<div class="widget">
<h2>Login | Register</h2>
</div><!--End widget class tag-->
<div class="inside">
<form action="login.php" method="post">
<ul id="logIn">
<li>
Username:<br/>
<input type="text" name="username"/>
</li>
<li>
Password:<br/>
<input type="password" name="password"/>
</li>
<li>
<input type="submit" value="Login"/>
</li>
<li>
Register
</li>
</ul>
</form>
</div><!--End inside class tag-->
login.php:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
include 'cic/initalize.php';
if (user_exists('cassey') === true)
echo 'exists';
else
die "User does not exist!";
if (isset($_POST['your_submit_button']) && isset($_POST['username']) && isset($_POST['password']))
{
$username = $_POST['username'];
$password = $_POST['password'];
if (strlen($username)==0 || strlen($password)==0)
{
$errors[] = 'Please provide your username and password.';
}
elseif(user_exists($username) === false)
{
$errors[] = 'We can\'t find the username entered, please enter a valid
username or register to continue';
}
}
else
{
echo "Error: at least one field wasn't set in the form !<br>";
print_r($_POST);
}
?>
Documentation:
isset
empty
ini_set
error_reporting
print_r
Replace your_submit_button with the real name of the submit button in your HTML form.
Using empty() is not a good idea since the string "0" is considered empty. What you need to check is if the strings contain at least a character (length not equal to zero).

Categories