I'm still starting to learn PHP and i don't know which part did i miss why i can't access the variable from other php file even though i include this in my index file.
Here's how i include the other php into my index file
index.php
<?php
include 'includes/signup.inc.php';
?>
With in this index.php I have this form:
<form id="form" action="includes/signup.inc.php" method="POST">
<div id="form1">
<label for="fname">First Name:</label>
<input type="text" name="fname"><span><?php echo $fnameerr?></span>
<br>
</div>
</form>
the variable $fnameerr is a variable from other php file inside includes folder named signup.inc.php if I only have this code inside signup.inc.php
<?php
include 'dbh.inc.php';
$fname = $lname = $email = $uid = $pw = "";
$fnameerr = $lnameerr = $emailerr = $uiderr = $pwerr = "";
this variable $fnameerr can be seen from index.php. But when i start to include this code:
<?php
include 'dbh.inc.php';
$fname = $lname = $email = $uid = $pw = "";
$fnameerr = $lnameerr = $emailerr = $uiderr = $pwerr = "";
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (empty($_POST['fname']))
{
$fnameerr = "First Name Required";
}
else
{
$fname = cleandata($_POST['fname']);
}
if (empty($_POST['lname']))
{
$lnameerr = "Last Name Required";
}
else
{
$lname = cleandata($_POST['lname']);
}
if (empty($_POST['email']))
{
$emailerr = "Email Required";
}
else
{
$email = cleandata($_POST['email']);
}
if (empty($_POST['uid']))
{
$uiderr = "User ID Required";
}
else
{
$uid = cleandata($_POST['uid']);
}
if (empty($_POST['pw']))
{
$pwerr = "Password Required";
}
else
{
$pw = cleandata($_POST['pw']);
}
}
function cleandata($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (!empty($fname) || !empty($lname) || !empty($email) || !empty($uid) || !empty($pw))
{
$sql = "INSERT INTO userlist(fname, lname, email, uid, pw) VALUES('$fname', '$lname', '$email', '$uid', '$pw');";
}
mysqli_query($conn, $sql);
header("location:../index.php");
?>
I can't access my index.php instead i am redirected to dashboard.
Related
I want to change page after validation in PHP but, it appears on the same page with the validation.
Here is the logical process i want
if validation didnt complete/invalid input
display error messages, and user must input again in the same page.
if form is validated complete with no invalid input.
User will be moved to a new page for reviewing the inputed data.
And this is my PHP
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
if($nameErr == "" && $emailErr == "" && $genderErr == "" && $websiteErr == "") {
header('Location: http://subc.chaidar-525.com');
exit();
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I use some referance from W3School, and it makes the review of data is in the same page as the form and validation, and i want the user will be transfered to another new page for reviewing their inputed data.
Use a session, roughly like this:
session_start();
if($nameErr == "" && $emailErr == "" && $genderErr == "" && $websiteErr == "") {
$_SESSION['inputdata'] = $_POST;
//A neater version would be to assign all vars, like:
//$_SESSION['gender'] = $gender;
header('Location: http://subc.chaidar-525.com');
exit();
}
on the next page, use this:
session_start();
$input_data = $_SESSION['inputdata'];
Using PHP, the validation on my form is correct and I even use a redirect header when the form is submitted correctly, this part works just fine, however, when the form is validated or showing errors a entry is submitted when it should not, is their anything I need to be added to my code base to fix this bug, take a look at my code below..
<?php
$e_first = ""; $e_last = ""; $e_email = ""; $success = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
require_once("config.php");
require_once("database.php");
require_once("controller.php");
$firstname = sanitize($_POST['firstname']);
$lastname = sanitize($_POST['lastname']);
$email = sanitize($_POST['email']);
$submit = sanitize($_POST['submit']);
if (empty($firstname)) {
$e_first = "First Name is required";
} else {
$firstname;
if (!preg_match("/^[a-zA-Z ]*$/", $firstname)) {
$e_first = "Only letters and white space allowed";
}
}
if (empty($lastname)) {
$e_last = "Last Name is required";
} else {
$lastname;
if (!preg_match("/^[a-zA-Z ]*$/", $lastname)) {
$e_last = "Only letters and white space allowed";
}
}
if (empty($email)) {
$e_email = "Email Address is required";
} else {
$email;
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$e_email = "Invalid Email Address";
}
}
$users = [
'firstname' => $firstname,
'lastname' => $lastname,
'email' => $email
];
$control = new Controller();
$control->addCustomer($users);
if (isset($submit)) {
switch (false) {
case !empty($firstname) || $firstname == $e_first :
$success = "";
break;
case !empty($lastname) || $lastname == $e_last :
$success = "";
break;
case !empty($email) || $email == $e_email :
$success = "";
break;
default :
$success = "Thank you $firstname $lastname";
header("Location: success.php");
break;
}
}
}
function sanitize($data) {
$data = htmlspecialchars($data);
$data = stripslashes($data);
$data = strip_tags($data);
$data = trim($data);
return $data;
}
?>
The bit where you add the user should be after you check for errors
default :
$control = new Controller();
$control->addCustomer($users);
$success = "Thank you $firstname $lastname";
header("Location: success.php");
break;
Trying to create my server.php script, so everythning was fine, till now. I wanted to prevent form resubmission and added header('location: index.php'); to my script. And then I faced the problem:ERR_TOO_MANY_REDIRECTS. And as many of you already understand my database was full of a junk. So, here is my code:
<?php
$username = $email = $password = "";
$usernameErr = $emailErr = $passwordErr = "";
$servername = 'localhost';
$serveruser = 'root';
$serverpassword = 'root';
$db = 'example';
$conn = new mysqli($servername, $serveruser, $serverpassword, $db);
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['register'])) {
$username = mysqli_real_escape_string($conn,$_POST['username']);
$email = mysqli_real_escape_string($conn,$_POST['email']);
$password = mysqli_real_escape_string($conn,$_POST['password']);
if(empty($username)) {
$usernameErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
if(!preg_match("/^[a-zA-z ]*$/", $username)){
$usernameErr = "Only letters and whitespaces allowed";
}
}
if(empty($email)) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Wrong email format";
}
}
if(empty($password)) {
$passwordErr = "Password required";
} else {
$password = test_input($_POST["password"]);
}
}
if ($usernameErr == "" && $emailErr == "" && $passwordErr == "") {
$sql = "INSERT INTO users (username, email, password)
VALUES('$username','$email','$password')";
if($conn->query($sql) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
header("location: index.php");
}
function test_input($data) {
$data = trim($data);
$data = htmlspecialchars($data);
$data = stripslashes($data);
return $data;
}
?>
To prevent TOO MANY REDIRECT put this code
if ($usernameErr == "" && $emailErr == "" && $passwordErr == "") {
$sql = "INSERT INTO users (username, email, password)
VALUES('$username','$email','$password')";
if($conn->query($sql) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
header("location: index.php");
}
within
if(isset($_POST['register'])) { //.................}
this block after checking errors
And to prevent re-submission of form use accepted answer on this question
Preventing form resubmission
You can do couple of ways to stop this:
1) You can write either of these, unset($_POST['register']); or $_POST = array(); just before header('location:index.php');so it will not pass through if(isset($_POST['register'])) condition and so it will not go in infinite loop.
2) Or use full URL in header like this: header("location: mydomain.com/index.php"); It will stop infinite loop too.
I already searched for an answer here, but none of them could help me fix my problem.
I have a form with the following HTML code at the beginning:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" id="registration_form">
Standard form, whenever there is an error, the user will be redirected back to to registration form. Everytime, he is on that page, the following PHP code will be executed:
<?php
$fnameErr = $lnameErr = $emailErr = $pwErr = $pw_confErr = "";
$fname = $lname = $email = $pw = $pw_conf = "";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fnameErr = "(Please submit first name)";
}
else {
$fname = test_input($_POST["fname"]);
}
if (empty($_POST["lname"])) {
$lnameErr = "(Please submit last name)";
}
else {
$lname = test_input($_POST["lname"]);
}
if (empty($_POST["email"])) {
$emailErr = "(Please submit email address)";
}
else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "(Email address is not valid)";
}
}
include ("script/registration_email_compare.php");
if (empty($_POST["pw"])) {
$pwErr = "(Please submit password)";
}
else {
$pw = test_input($_POST["pw"]);
$pwHash = password_hash($pw, PASSWORD_DEFAULT);
}
if (empty($_POST["pw_conf"])) {
$pw_confErr = "(Please confirm password)";
}
else {
$pw_conf = test_input($_POST["pw_conf"]);
}
if ($_POST["pw"] !== $_POST["pw_conf"]) {
$pwErr = "(Please confirm password)";
$pw_confErr = "";
}
if (empty($fnameErr) && empty($lnameErr) && empty($emailErr) && empty($pwErr) && empty($pw_confErr))
{
ob_start();
include ("script/registration_db_add.php");
include ("script/registration_send_mail.php");
header("Location: registration_success.php");
exit;
}
}
?>
My problem now is that the user is added to my database, but he is not redirected to registration_success, but instead is redirected back to registration.php, where an empty page is returned.
I have no idea how to fix that error and couldn't find any suitable solutions, so I'm happy for any help.
Another extra info: my script is working on localhost, but not after I published it, that's pretty weird actually.
I have a form which needs to be validated using php before inserting form values into a database.
it worked just fine if the fields are empty, however when I included a code to ensure only letters and white spaces are allowed in the first and last name fields it broke the validation process i.e. when I typed in any combinations of letters in the fields it displayed an error message saying "only letters and white spaces are required".
Secondly, when all fields are empty, the form displays the appropriate error message and does no submit the form to the database. However, when I type in a message in the textarea field with other fields empty, the form submits the data to the database as well as displays error messages for the other empty fields.
Any help to resolve these issues would be much appreciated.
Here is the code:
<?php
$fnameErr = $lnameErr = $emailErr = $amountErr = $phoneErr = $genderErr = $messageErr = $categoryErr = $countryErr = "";
$fname = $lname = $email = $amount = $phone = $gender = $message = $category = $country = "";
$ipaddress ="";
$defaultMessage = "Please type your message here.";
$formErrors = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//for first name
$name= $_POST["fname"];
if (empty($_POST["fname"])){
$fnameErr = "Please, enter your first name";
$formErrors = true;
}elseif(!preg_match("/^[a-zA-Z]*&/", $name)){
$fnameErr = "Only letters and white spaces are allowed in the first name field";
$formErrors = true;
}else{
$fname = $_POST["fname"];
$formErrors = false;
}
//Last Name match
// for last name
$name2= $_POST["lname"];
if (empty($_POST["lname"])){
$lnameErr = "Please, enter your last name";
$formErrors = true;
}elseif(!preg_match("/^[a-zA-Z]*&/", $name2)){
$lnameErr = "Only letters and white spaces are allowed in the Last name field";
$formErrors = true;
}else{
$lname = $_POST["lname"];
$formErrors = false;
}
// for email format
$emailf =($_POST["email"]);
if (empty($_POST["email"])) {
$emailErr = "Please, enter your email";
$formErrors = true;
}elseif (!filter_var($emailf, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
$formErrors = true;
}else {
$email = $_POST["email"];
$formErrors = false;
}
//for phone
if (empty($_POST["phone"])){
$phoneErr = "Please, enter your phone number";
$formErrors = true;
}else{
$phone = $_POST["phone"];
$formErrors = false;
}
// for amount
if (!isset($_POST["amount"])) {
$amountErr = "You must select an amount";
$formErrors = true;
}
else {
$amount = $_POST["amount"];
$formErrors = false;
}
// for gender
if (!isset($_POST["gender"])) {
$genderErr = "You must select your gender";
$formErrors = true;
}
else {
$gender = $_POST["gender"];
$formErrors = false;
}
// for country
if (empty($_POST["country"]) || $_POST["country"] == "Country") {
$countryErr = "Please, select your country";
$formErrors = true;
}
else {
$country = $_POST["country"];
$formErrors = false;
}
// for category
if (empty($_POST["category"]) || $_POST["category"] == "Category") {
$categoryErr = "Please, select a category";
$formErrors = true;
} else {
$category = $_POST["category"];
$formErrors = false;
}
// for message
if (empty($_POST["message"]) || $_POST["message"] == $defaultMessage){
$messageErr = "Please type your prayer request";
$formErrors = true;
}else{
$message = $_POST["message"];
$formErrors = false;
}
if (empty($formErrors) ) {
//connect to database
require_once("../../includes/connect_to_db.php");
// set time zone to uk
$timezone = date_default_timezone_set("Europe/london");
//setting values
$Timestamp = date('Y-m-d h:i:s');
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$gender = isset($_POST["gender"]) ? $_POST["gender"] : '';
$message = $_POST["message"];
$country = $_POST["country"];
$category = $_POST["category"];
//echo $gender . "value";
//var_dump(billingDate);
// var_dump($customer);
//Escape all string
$firstname = mysqli_real_escape_string($connection, $fname);
$lastname = mysqli_real_escape_string($connection, $lname);
$emailNew = mysqli_real_escape_string($connection, $email);
$phoneNew = mysqli_real_escape_string($connection, $phone);
$genderNew = mysqli_real_escape_string($connection, $gender);
$messageNew = mysqli_real_escape_string($connection, $message);
$countryNew = mysqli_real_escape_string($connection, $country);
$categoryNew = mysqli_real_escape_string($connection, $category);
//querying the database
$query = "INSERT into counselling ( ";
$query .= "Timestamp, FirstName, LastName, ";
$query .= "Email, PhoneNumber, Category, Country, Gender, Message";
$query .= ")";
$query .= "VALUES ('{$Timestamp}', '{$firstname}', '{$lastname}', ";
$query .= "'{$emailNew}', '{$phoneNew}', '{$categoryNew}', '{$countryNew}', '{$genderNew}', '{$messageNew}' ";
$query .= ")";
echo $query;
$result = mysqli_query($connection, $query) ;
//check for query error
if($result){
//query success redirect_to ("somepage.php");
//redirect_to("confirmation.php");
echo "Success";
} else {
die("Database query failed");
}
} // end of if
} // End of form submission conditional.
?>
Your need to refactor your code with proper logic.
<?php
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$errors = array();
if(trim($fname) == ''){
$errors['fname'] = "First name is required";
}
if(trim($lname) == ''){
$errors['lname'] = "Last name is required";
}
if(count( $errors) > 0){
//form invalid
}
else{
//form is valid
}