So I have two files. The first is the index.php in the root folder the other is an index.php found in a controller folder named post_link. I want to pass email, password, and action from the form in index.php of the root to the index.php of post_link but its just passing empty values when I try to get them using, filter_input(INPUT_POST, 'value'). How do I pass variables from index.php of the root to the index.php of post_link?
index.php of the root:
<?php
session_start();
require_once('model/fields.php');
// Add header
include '/view/header.php';
// Add fields with optional initial message
$validate = new Validate();
$fields = $validate->getFields();
$fields->addField('first_name');
$fields->addField('last_name');
$fields->addField('password');
$fields->addField('email', 'Must be a valid email address.');
// Makes sure the pages uses a secure connection
if(!isset($_SERVER['HTTPS'])) {
$url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header("Location: " . $url);
exit();
}
$action = filter_input(INPUT_POST, 'action');
if ($action === NULL) {
$action = 'login';
$email = '';
} else {
$action = strtolower($action);
}
if ($email == '') {
$login_message = 'Login or register if you are a new user.';
}
else {
$login_message = '<span class="error">Invalid email.</span>';
}
?>
<main>
<h2>Login</h2>
<form action="post_list" method="post" class="aligned">
<fieldset>
<legend>Customer Login</legend>
<input type="hidden" name="action" value="login">
<label>Email:</label>
<input type="text" class="text" name="email">
<br>
<label>Password: </label>
<input type="text" class="text" name="password">
<br>
<label> </label>
<input type="submit" value="Login">
<br>
</fieldset>
</form>
<form action="." method="post" class="aligned">
<fieldset>
<legend>Customer Registration</legend>
<input type="hidden" name="action" value="reset">
<label>You must be registered to view posts</label>
<input type="submit" value="Register here">
</fieldset>
</form>
<p><?php echo $login_message; ?></p>
</main>
<?php include 'view/footer.php'; ?>
index.php of the controller:
<?php
// session_start();
require_once('../model/database.php');
require_once('../model/customers_db.php');
require_once('../model/validate.php');
$action = filter_input(INPUT_POST, 'action');
if ($action === NULL) {
$action = 'login';
$email = '';
} else {
$action = strtolower($action);
}
switch ($action) {
case 'login':
$email = filter_input(INPUT_POST, 'email');
$password = filter_input(INPUT_POST,'password');
if (is_valid_customer_login($email)) {
$_SESSION['is_valid_customer'] = true;
$customer = get_customer($email);
$first_name = $customer['firstName'];
$last_name = $customer['lastName'];
if (is_valid_customer_login_password($email, $password)) {
include('../view/customer_menu.php');
} else {
$login_message = '<span class="error">Invalid password.</span>';
include('../index.php');
}
} else {
if ($email == '') {
$login_message = 'Login or register if you are a new customer.';
}
else {
$login_message = '<span class="error">Invalid email.</span>';
}
}
break;
case 'reset':
// Reset values for variables
$first_name = '';
$last_name = '';
$email = '';
$password ='';
// Load view
include 'view/register.php';
break;
case 'register':
// Copy form values to local variables
$first_name = trim(filter_input(INPUT_POST, 'first_name'));
$last_name = trim(filter_input(INPUT_POST, 'last_name'));
$email = trim(filter_input(INPUT_POST, 'email'));
$password =trim(filter_input(INPUT_POST, 'password'));
// Validate form data
$validate->text('first_name', $first_name);
$validate->text('last_name', $last_name);
$validate->email('email', $email);
$validate->password('password', $password);
// Load appropriate view based on hasErrors
if ($fields->hasErrors()) {
include 'view/register.php';
} else {
add_customer($first_name, $last_name, $email, $password);
include 'view/customer_menu.php';
}
break;
case 'logout':
$_SESSION = array(); // Clear all session data from memory
session_destroy(); // Clean up the session ID
$login_message = 'You have been logged out.';
include('view/login.php');
break;
}
?>
This ain't gonna work this way, You have to use the action as "post_list/index.php". So modify your form as:
<form action="post_list/index.php" method="post" class="aligned">
<fieldset>
<legend>Customer Login</legend>
<input type="hidden" name="action" value="login">
<label>Email:</label>
<input type="text" class="text" name="email">
<br />
<label>Password: </label>
<input type="text" class="text" name="password">
<br>
<label> </label>
<input type="submit" value="Login">
<br>
</fieldset>
Related
I wrote a customer_display.php to validate data (only First Name so far), but no matter First Name field is empty or not, the webpage will jump to customer_search.php & did not change information in database. why?
<?php include '../view/header.php';
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// Initialize variables and set to empty strings
$firstName=$lastName="";
$firstNameErr=$lastNameErr="";
// Control variables
$app_state = "empty"; //empty, processed, logged in
$valid = 0;
// Validate input and sanitize
if ($_SERVER['REQUEST_METHOD']== "POST") {
if(isset($_POST["first_name"]))
{
if (empty($_POST["first_name"])) {
$firstNameErr = "First name is required";
}
else {
$firstName = test_input($_POST["firstName"]);
if(strlen($firstName)>5){
$firstNameErr = "First name is too long";
}
else{
$valid++;
}
}
}
if (empty($_POST["lastName"])) {
$lastNameErr = "Last name is required";
}
else {
$lastName = test_input($_POST["lastName"]);
$valid++;
}
if ($valid >= 2) {
$app_state = "processed";
}
}
// Sanitize data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($app_state == "empty") {
?>
<!-- display a table of customer information -->
<h2>View/Update Customer</h2>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="POST" id="aligned">
<input type="hidden" value="update_customer">
<input type="hidden" name="customer_id"
value="<?php echo htmlspecialchars($customer['customerID']); ?>">
<label>First Name:</label>
<input type="text" name="first_name"
value="<?php echo htmlspecialchars($customer['firstName']); ?>">
<span class="error"><?php echo $firstNameErr;?></span><br>
<label>Last Name:</label>
<input type="text" name="last_name"
value="<?php echo htmlspecialchars($customer['lastName']); ?>"><br>
<label>Address:</label>
<input type="text" name="address"
value="<?php echo htmlspecialchars($customer['address']); ?>"
size="50"><br>
<label>City:</label>
<input type="text" name="city"
value="<?php echo htmlspecialchars($customer['city']); ?>"><br>
<label>State:</label>
<input type="text" name="state"
value="<?php echo htmlspecialchars($customer['state']); ?>"><br>
<label>Postal Code:</label>
<input type="text" name="postal_code"
value="<?php echo htmlspecialchars($customer['postalCode']); ?>"><br>
<label>Country:</label>
<select name="selected">
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass ='';
$db = 'tech_support';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db);
if($conn->connect_error)
die('Could not connect: '. $conn->connect_error);
$selected= $conn->query("select * from countries where countryCode = '" .$customer['countryCode']. "'");
$sql = $conn->query("select * from countries order by countryName");
if($selectedrow = $selected->fetch_assoc()){
echo "<option selected value='" . $selectedrow['countryName']."'>". $selectedrow['countryName']."</option>";
}
//echo "<select>";
while ($row = $sql->fetch_assoc()) {
echo "<option value ='". $row['countryName']."'>". $row['countryName']."</option>";
}
//echo "</select>";
$conn->close();
?>
</select><br>
<label>Phone:</label>
<input type="text" name="phone"
value="<?php echo htmlspecialchars($customer['phone']); ?>"><br>
<label>Email:</label>
<input type="text" name="email"
value="<?php echo htmlspecialchars($customer['email']); ?>"
size="50"><br>
<label>Password:</label>
<input type="text" name="password"
value="<?php echo htmlspecialchars($customer['password']); ?>"><br>
<label> </label>
<input type="submit" value="Update Customer"><br>
</form>
<p>Search Customers</p>
</body>
</html>
<?php
}
elseif ($app_state == "processed") {
if ($firstName == "Vincent") {
$app_state = "Logged in";
}
}
if ($app_state == "Logged in") {
echo("Logged in<br> Hello Vincent</body></html>");
}
?>
<?php include '../view/footer.php'; ?>
index.php(to process the data):
<?php
require('../model/database.php');
require('../model/customer_db.php');
$action = filter_input(INPUT_POST, 'action');
if ($action === NULL) {
$action = filter_input(INPUT_GET, 'action');
if ($action === NULL) {
$action = 'search_customers';
}
}
//instantiate variable(s)
$last_name = '';
$customers = array();
if ($action == 'search_customers') {
include('customer_search.php');
} else if ($action == 'display_customers') {
$last_name = filter_input(INPUT_POST, 'last_name');
if (empty($last_name)) {
$message = 'You must enter a last name.';
} else {
$customers = get_customers_by_last_name($last_name);
}
include('customer_search.php');
} else if ($action == 'display_customer') {
$customer_id = filter_input(INPUT_POST, 'customer_id', FILTER_VALIDATE_INT);
$customer = get_customer($customer_id);
include('customer_display.php');
} else if ($action == 'update_customer') {
$customer_id = filter_input(INPUT_POST, 'customer_id', FILTER_VALIDATE_INT);
$first_name = filter_input(INPUT_POST, 'first_name');
//echo $first_name;
$last_name = filter_input(INPUT_POST, 'last_name');
$address = filter_input(INPUT_POST, 'address');
$city = filter_input(INPUT_POST, 'city');
$state = filter_input(INPUT_POST, 'state');
$postal_code = filter_input(INPUT_POST, 'postal_code');
$country_name = $_POST["selected"];
$phone = filter_input(INPUT_POST, 'phone');
$email = filter_input(INPUT_POST, 'email');
$password = filter_input(INPUT_POST, 'password');
//if(!$valid_fname == null){require ('customer_display.php');};
//echo $country_name;
$country_code = get_countryCode($country_name);
update_customer($customer_id, $first_name, $last_name,
$address, $city, $state, $postal_code, $country_code,
$phone, $email, $password);
include('customer_search.php');
}
?>
You have no name attribute with the value of 'action', so your update never happens.
<form action="" method="POST">
<input type="hidden" value="update_customer">
<!-- rest of the form -->
</form>
Edited for clarity.
I am making the login page in php.
However, no If worth of blank check of html form is operated (line4)
After entering in the html of the form, even if you press the login does not have moved if statement.
Since the cause is not know, I want you to tell me
if (isset($_POST["login"])) {//PUSH login button
//form blank check
if ($_POST["email"] = '') {
$error['email'] = "blank";
} else if ($_POST["pass"] = '') {
$error['pass'] = "blank";
}
}
if(!empty($_POST['email'])){
//email & password verification
if($_POST['email'] != '' && $_POST['pass'] != ''){
$email = $_POST['email'];
$pass = SHA1($_POST['pass']);
$query = "select * from human";
$result = mysqli_query($dbc,$query);
$data = mysqli_fetch_array($result);
if($data['email'] == $email) { //form email & password
if($data['pass'] === $pass) {
setcookie('email', $email, time()+(60*60*24*3));
setcookie('pass', $pass, time()+(60*60*24*3));
setcookie('name', $date['name'], time()+(60*60*24*3));
exit();
}else{
$error['match'] = "anmatch"; //Mismatch Error
}
}
}
<!DOCTYPE html>
<form action="" method="post">
<dl>
<dt>email</dt>
<dd>
<input type="text" name="email" size="35" maxlength="255"
value="<?php echo htmlspecialchars($_POST['email']); ?>">
<?php if($error['email'] == 'blank'): ?>
<p><font color="red">* Input email</font></p>
<?php endif; ?>
</dd>
<dt>password</dt>
<dd>
<input type="password" name="pass" size="35" maxlength="255"
value="<?php echo htmlspecialchars($_POST['pass']); ?>">
<?php if($error['pass'] == 'blank'): ?>
<p><font color="red">* Input password</font></p>
<?php endif; ?>
</dd>
</dl>
<input type="submit" id="login" name="login" value="sigh in">
</form>
Firstly as mentioned in the comments, you are assigning a value in your if statements. Also as a second point I'd guess because your condition is a nested else if the first assignment is always true so the second condition will never be tested.
//form blank check
if ($_POST["email"] = '') {
$error['email'] = "blank";
} else if ($_POST["pass"] = '') {
$error['pass'] = "blank";
}
The second condition statement will only evaluate when the first is false
You should try checking each variable independently nand make sure you use ==
//form blank check
if ($_POST["email"] == '') {
$error['email'] = "blank";
}
if ($_POST["pass"] == '') {
$error['pass'] = "blank";
}
I am trying to implement a basic user registration RESTful api.
I have a html form registerform.html, deregisterform.html, users.php, register.php and deregister.php which are all pasted below.
When i visit the registerform.html in my browser, i can fill in the details and a POST request is received by the users.php script and a json response is echoed back showing the id number of the user thats just been added.
My problem is that when i use the deregister form, the users.php script should recive a DELETE request, but is actually getting a GET request. I've been looking for an answer to this problem but im not finding a solution.
registerform.html
<form action="users.php" method="POST">
Username: <input type="text" name="uname" /><br />
FirstName: <input type="text" name="fname" /><br />
Last Name: <input type="text" name="lname" /><br />
Date of Birth: <input type="date" name="dob" /><br />
Telephone: <input type="mob" name="tel" /><br />
Email: <input type="email" name="email1" /><br />
Confirm Email: <input type="email" name="email2" /><br />
Password: <input type="password" name="pass1" /><br />
Confirm Password: <input type="password" name ="pass2" /><br />
<input type="submit" value="Register" name="sub" />
<br/>Already Registered? Login Here<br/>
</form>
deregisterform.html
<form action="users.php" method="DELETE">
Username: <input type="text" name="uname" /><br />
Password: <input type="password" name="pass1" /><br />
Confirm Password: <input type="password" name ="pass2" /><br />
<input type="submit" value="Deregister" name="sub" />
</form>
register.php
<?php
if(isset($_POST['uname']) && isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['tel']) && isset($_POST['dob']) &&
isset($_POST['email1']) && isset($_POST['email2']) && isset($_POST['pass1']) && isset($_POST['pass2']))
{
//take values from http POST and trim whitespace
$uname = trim($_POST['uname']);
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$tel = trim($_POST['tel']);
$dob = trim($_POST['dob']);
$email1 = trim($_POST['email1']);
$email2 = trim($_POST['email2']);
$pass1 = trim($_POST['pass1']);
$pass2 = trim($_POST['pass2']);
//validate the data from the form
if($um->isNameFormatted($uname))
{
if(!$um->isUserExists($uname)) //does user already exist with this username?
{
if($um->isNameFormatted($fname)) //first name formatted correctly
{
if($um->isNameFormatted($lname)) //last name formatted correctly
{
if($um->isDOBFormatted($dob))
{
if($email1 == $email2)
{
if($pass1 == $pass2)
{
if($um->isPasswordClean($pass1))
{
if($um->isTelephoneVerified($tel))
{
//everything is OKAY --- PROCEED WITH ADDING USER
$user = $um->registerUser($uname,$fname,$lname,$dob,$tel,$email1,$pass1);
if(isset($user))///
{
//successful registration
$response["error"] = false;
$response["id"] = $user;
echo json_encode($response);
}
}
}
}
}
}
}
}
}
}
}?>
deregister.php
<?php
if(isset($_POST['uname']) && isset($_POST['pass1'] && isset($_POST['pass2'])
{
$uname = $_POST['uname'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
if($um->isUserExists($uname))
{
if($pass1 == $pass2)
{
if(true)//$um->isPasswordFor($uname, $pass))
{
$um->deregisterUser($uname, $pass1);
$response["error"] = false;
$response["text"] = "User removed!";
echo json_encode($response);
}
else
{
$response["error"] = true;
$response["text"] = "Wrong username and password combination!";
echo json_encode($response);
}
}
else
{
$response["error"] = true;
$response["text"] = "Passwords don't match!";
echo json_encode($response);
}
}
else
{
$response["error"] = true;
$response["text"] = "User(".$uname.") not in database!";
echo json_encode($response);
}
}?>
users.php
<?php
error_reporting( -1 );
require('userManagement.php');
$um = new UserManagement();
$response = array("error" => FALSE);
//check if user logged in and authenticated
if(true)
{
echo "user logged in.";
echo $httpVerb = trim(strtoupper($_SERVER['REQUEST_METHOD']));
switch($httpVerb)
{
case "GET":
$response["error"] = false;
$response["httpVerb"] = $httpVerb;
echo json_encode($response);
break;
case "PUT":
$response["error"] = false;
$response["httpVerb"] = $httpVerb;
echo json_encode($response);
break;
case "POST":
include('register.php');
break;
case "DELETE":
include('deregister.php');
break;
default:
echo "http verb ".$httpVerb." is not supported for this resource.";
$response["error"] = true;
$response["httpVerb"] = $httpVerb;
echo json_encode($response);
break;
}
}
else
{
echo "need to login first.";
}?>
Any ideas what i'm doing wrong?
You can't use DELETE as a form action.
From the specs, we have:
The method and formmethod content attributes are enumerated attributes
with the following keywords and states:
The keyword get, mapping to the state GET, indicating the HTTP GET method.
The keyword post, mapping to the state POST, indicating the HTTP POST method.
The invalid value default for these attributes is the GET state.
I have this PHP login script that SHOULD be taking the entered username & password, checking it against a value in MySQL (with the password encrypted via SHA1) and then redirecting the user to the "dash.php" if login is successful or printing an error if not. However whenever I submit the form, it just reloads the login.php... Did I make a stupid error somewhere or am I missing something? Sorry about the huge post!
login.php (containing form):
//Form Action
<?php
error_reporting(E_ALL);
ini_set('display_errors','1');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require ('scripts/mysqli_connect.php');
require ('scripts/login_functions.php');
list ($check, $data) = check_login($dbc, $_POST['username'], $_POST['password']);
if($check) {
redirect_user('dash.php');
} else {
$errors = $data;
}
mysqli_close($dbc);
}
?>
// Website HTML
//Form
<form class="contact-form" method="post" action="login.php">
<div class="col-sm-5 col-sm-offset-1">
<div class="form-group">
<label>Username: </label>
<input type="text" name="username" id="username" size="15" class="form-control" required="required" placeholder="username">
</div>
<div class="form-group">
<label>Password: </label>
<input type="password" name="password" id="password" size="15" class="form-control" required="required" placeholder="password">
</div>
<div class="form-group">
<input type="submit" name="submit" value="Login" />
</div>
</div>
</form>
login_functions.php:
<?php
function redirect_user ($page = '../login.php') {
$url = "http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
$url = rtrim($url, '/\\');
$url .= '/' . $page;
//Redirect User
header("Location: $url");
exit(); //Quit the script.
}
function check_login($dbc, $username = '', $password = '') {
$errors = array();
if(empty($username)) {
$errors[] = 'You forgot to enter your username.';
} else {
$u = mysqli_real_escape_string($dbc, trim($username));
}
if(empty($password)) {
$errors[] = 'you forgot to enter your passord.';
} else {
$p = mysqli_real_escape_string($dbc, trim($password));
}
if (empty($errors)) {
$q = "SELECT username, password FROM users WHERE username='$u' AND password=sha1('$p')";
$r = #mysqli_query ($dbc, $q);
//Check Results
if(mysqli_num_rows($r) == 1) {
$row = mysqli_fetch_array ($r, MYSQLI_ASSOC);
return array(true, $row);
} else {
$errors[] = 'The username/password combination is incorrect.';
}
}
}
?>
You are not returning you errors:
return array(true, $row);
} else {
$errors[] = 'The username/password combination is incorrect.';
$return array(false, $errors);
}
And you are not displaying your errors:
// Website HTML
<?php if ($errors):?>
<?php echo '<p>' . implode('</p><p>', $errors) . '<p>';?>
<?php endif;?>
//Form
<form class="contact-form" method="post" action="login.php">
so i edited my code but still unable to get the results part of code is responsible for reporting error that do not work too
i'm open to other ways of coding to do the work as long as it fits in the code here comes the code
<?php
require 'core.inc.php';
if(!loggedIn()) {
//check mikunim ke tamame field ha dar form vojod darand va set shudan
if(isset($_POST['username'])&&isset($_POST['password'])&&isset($_POST['password_again'])&&isset($_POST['firstname'])&&isset($_POST['surname'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$password_again = $_POST['password_again'];
$firsname = $POST['firstname'];
$surename = $POST['surename'];
//HALA CHECK MIKUNIM KHALI HASTAND YA NA
if(!empty($username)&&!empty($password)&&!empty($email)&&!empty($firstname)&&!empty($surename)){
echo 'ok' ;
} else {
echo ' All fields are required';
}
}
?>
<form action="register.php" method="POST">
Username:<br> <input type="text" name="username"><br> <br>
Password:<br> <input type="password" name="password"><br><br>
Password again:<br> <input type="password" name="password_again"><br><br>
Firstname:<br> <input type="text" name="firstname"><br><br>
Surname:<br> <input type="text" name="surename"><br><br>
<input type="submit" value="register">
</form>
<?php
} else if (loggedIn()) {
echo 'you \'re already logged in';
}
i edited again now i get this
Notice: Undefined index: HTTP_REFERER
$http_referer = $_SERVER['HTTP_REFERER']
i used this from tutorial
change this
$firsname = $POST['firstname'];
$surename = $POST['surename'];
to this:
$firstname = $_POST['firstname'];
$surename = $_POST['surename'];