PHP logic error in a php form code - php

I'm unable to solve the logical error in the code. I'm not sure what is wrong though it seems the logic is correct
This is my php:
<?php require_once("includes/connection.php"); ?>
<?php
include_once("includes/form_functions.php");
if(isset($_POST['submit']))
{
$errors = array();
if(isset($_POST['txtSpace']))
{
$choice_spc_port = $_POST["txtSpace"];
}
if(isset($_POST['txtNumber']))
{
$choice_no = $_POST["txtNumber"];
}
if(isset($_POST['txtLocation']))
{
$choice_loc = $_POST["txtLocation"];
if($choice_loc =="txtSetXY")
{
$x = $_POST["txtXLocation"];
$y = $_POST["txtYLocation"];
if($x == "")
{
$message = "You forgot to enter X Value";
}
elseif($y == "")
{
$message = "You forgot to enter Y Value";
}
else
{
$choice_loc = $x . "," . $y;
}
}
}
$user_name = $_POST["txtUserName"];
$user_email = $_POST["txtUserEMail"];
$animal_name = $_POST["txtAnimalName"];
$disp_msg = $_POST["txtDispMsg"];
$comments = $_POST["txtComments"];
if(!isset($_POST['txtSpace']))
{
$message = "Please select Space Portion";
}
elseif(!isset($_POST['txtNumber']))
{
$message = "Please select the number of animals";
}
elseif(!isset($_POST['txtLocation']))
{
$message = "Please select the desired location of animal";
}
elseif($user_name == "")
{
$message = "Please enter your name.";
}
elseif($user_email == "")
{
$message = "Please enter your email.";
}
elseif($animal_name == "")
{
$message = "Please enter the name of the animal.";
}
elseif($disp_msg == "")
{
$message = "What message you want to dedicate to the animal?.";
}
else
{
// validation
$required_fields = array('txtUserName','txtUserEMail','txtAnimalName','txtDispMsg');
$errors = array_merge($errors, check_required_fields($required_fields, $_POST));
$user_name = trim(mysql_prep($_POST['txtUserName']));
$user_email = trim(mysql_prep($_POST['txtUserEMail']));
$animal_name = trim(mysql_prep($_POST['txtAnimalName']));
$disp_msg = trim(mysql_prep($_POST['txtDispMsg']));
if(empty($errors))
{
/*if($choice_loc == "txtSetXY")
{
$x = $_POST["txtXLocation"];
$y = $_POST["txtYLocation"];
$choice_loc = $x . "," . $y;
}*/
if($choice_no == "other")
{
$choice_no = $_POST["other_field"];
}
$insert = "INSERT INTO db_form (db_space_portion, db_number, db_location, db_user_name, db_user_email, db_animal_name, db_message, db_comments) VALUES ('{$choice_spc_port}', '{$choice_no}', '{$choice_loc}', '{$user_name}', '{$user_email}','{$animal_name}','{$disp_msg}','{$comments}')";
$result = mysql_query($insert);
if($result)
{
echo("<br>Input data is succeed");
}
else
{
$message = "The data cannot be inserted.";
$message .= "<br />" . mysql_error();
}
}
else
{
if(count($errors) == 1)
{
$message = "There was 1 error on the form.";
}
else
{
$message = "There were " . count($errors) ." errors on the form.";
}
}
}
}
else
{
$user_name = "";
$user_email = "";
$disp_msg = "";
$comments = "";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test Form</title>
<meta charset="utf-8">
<link rel="stylesheet" href="css/reset.css" type="text/css" media="all">
<link rel="stylesheet" href="css/layout.css" type="text/css" media="all">
<link rel="stylesheet" href="css/style.css" type="text/css" media="all">
<script type="text/javascript" src="js/jquery-1.9.0.min.js" ></script>
<script type="text/javascript" src="js/cufon-yui.js"></script>
<script type="text/javascript" src="js/cufon-replace.js"></script>
<script type="text/javascript" src="js/Copse_400.font.js"></script>
<script type="text/javascript" src="js/imagepreloader.js"></script>
<script type="text/javascript" src="js/functions.js"></script>
<!--[if lt IE 9]>
<script type="text/javascript" src="js/ie6_script_other.js"></script>
<script type="text/javascript" src="js/html5.js"></script>
<![endif]-->
</head>
<body id="page5">
<!-- START PAGE SOURCE -->
<div class="body7">
<div class="main">
<section id="content">
<div class="wrapper">
<article class="col24">
<div class="pad1">
<h4>Kindly Fill the form</h4>
<?php if(!empty($message)){ echo $message; } ?>
<?php if(!empty($errors)){ echo display_errors($errors);}?>
<form id="TestForm" name="TestForm" method="post" action="form.php">
<div>
<div class="wrapper"> <strong><span>*</span> Desired Space</strong>
<div class="formText">
<input type="radio" name="txtSpace" value="RJ"/>Space Top<br />
<input type="radio" name="txtSpace" value="SM" />Space Bottom<br />
</div>
</div>
<div class="wrapper"> <strong><span>*</span> Select the Number</strong>
<div class="formText">
<input type="radio" name="txtNumber" value="100"/>100
<input type="radio" name="txtNumber" value="200"/>200
<input type="radio" name="txtNumber" value="500"/>500
<input type="radio" name="txtNumber" value="1000"/>1000
<input type="radio" name="txtNumber" value="10000"/>10000
<input type="radio" name="txtNumber" value="other"/>other
<input type="text" name="other_field" id="other_field" onblur="checktext(this);"/>
</div>
</div>
<div class="wrapper"> <strong><span>*</span> Select X & Y Value</strong>
<div class="formText">
<input type="radio" name="txtLocation" value="txtSetXY"/> Specify Photo Location<br />
<div style="padding-left:20px;">
X: <input type="text" id="locField" name="txtXLocation"><br />
Y: <input type="text" id="locField" name="txtYLocation"><br />
</div>
<input type="radio" name="txtLocation" value="Default"/>Default
</div>
</div>
<div class="wrapper"> <strong><span>*</span> Your Name:</strong>
<div class="bg">
<input type="text" class="input" name="txtUserName">
</div>
</div>
<div class="wrapper"> <strong><span>*</span> Your Email:</strong>
<div class="bg">
<input type="text" class="input" name="txtUserEMail">
</div>
</div>
<div class="wrapper"> <strong><span>*</span> Name of the animal:</strong>
<div class="bg">
<input type="text" class="input" name="txtAnimalName">
</div>
</div>
<div class="wrapper">
<div class="textarea_box"> <strong><span>*</span> The Message you want for your favourite animal:</strong>
<textarea name="txtDispMsg" cols="1" rows="1"></textarea>
</div>
</div>
<div class="wrapper">
<div class="textarea_box"> <strong>Comments:</strong>
<textarea name="txtComments" cols="1" rows="1"></textarea>
</div>
</div>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</div>
</article>
</div>
</section>
</div>
</div>
</body>
</html>
Errors:
Check this php fiddle here.
line 25. This is never shown even if I leave x textfield blank
$message = "You forgot to enter X Value";
same is with line 29. This is never shown even if I leave y textfield blank
$message = "You forgot to enter Y Value";
However if I enter the values in x and y textfield i.e. in txtXLocation and in txtYLocation they are being saved in db meaning it is just not checking the validation.
Thanks in advance

make sure you have connection.php file in includes folder and you have given correct path to reach that file.

Related

PHP echo not returning <div> correctly

Can someone tell me why the <?php echo $userPasswordError; ?> line returns nothing (empty) instead of <div class="invalid-feedback">Too long.</div> when I enter a password which contain more than 1 character with the below code ?
If I change this line : $userPasswordError = '<div class="invalid-feedback">Too long.</div>';
with this $userPasswordError = 'Too long.'; , it works ! Output is "Too long.".
<?php
$user = $userPassword = '';
$userError = $userInvalid = $userPasswordError = $userPasswordInvalid = '';
$isvalidOrInvalidUser = $isvalidOrInvalidUserPassword = '';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Verify username.
if (!empty($_POST["user"])) {
if (strlen($_POST["user"]) <= 32) {
$user = $_POST["user"];
$userError = '<div class="valid-feedback">Correct.</div>';
$isvalidOrInvalidUser = 'is-valid';
}
else {
$userInvalid = $_POST["user"];
$userError = '<div class="invalid-feedback">Too long.</div>';
$isvalidOrInvalidUser = 'is-invalid';
}
}
else {
$userError = '<div class="invalid-feedback">Please, add username.</div>';
$isvalidOrInvalidUser = 'is-invalid';
}
// Verify password.
if (!empty($_POST["userpassword"])) {
if (strlen($_POST["userpassword"]) <= 1) {
$userPassword = $_POST["userpassword"];
$userPasswordError = '<div class="valid-feedback">Correct.</div>';
$isvalidOrInvalidUserPassword = 'is-valid';
}
else {
$userPasswordInvalid = $_POST["userpassword"];
$userPasswordError = '<div class="invalid-feedback">Too long.</div>';
$isvalidOrInvalidUserPasword = 'is-invalid';
}
}
else {
$userPasswordError = '<div class="invalid-feedback">Please, add password.</div>';
$isvalidOrInvalidUserPassword = 'is-invalid';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div class="form-row">
<div class="col-md-3 mb-3">
<label for="user">Username :</label>
<input type="text" class="form-control <?php echo $isvalidOrInvalidUser; ?>" id="user" name="user" placeholder="User here" value="<?php echo $user.$userInvalid; ?>">
<?php echo $userError; ?>
</div>
<div class="col-md-3 mb-3">
<label for="userpwd">User password :</label>
<input type="password" class="form-control <?php echo $isvalidOrInvalidUserPassword; ?>" id="userpassword" name="userpassword" value="<?php echo $userPassword.$userPasswordInvalid; ?>">
<?php echo $userPasswordError; ?>
</div>
</div>
<button class="btn btn-primary" type="submit">Add</button>
</form>
</body>
</html>
I finally know why.
$userPasswordError = '<div class="invalid-feedback">Too long.</div>';
$isvalidOrInvalidUserPasword = 'is-invalid';
The variable name of isvalidOrInvalidUserPasword is wrong, it should be $isvalidOrInvalidUserPassword (missing an s at Pasword).
If the input does not have class is-invalid, the error message will not visible!
Hope this helps!

How do I input/output .CSV data via a PHP page?

I have the assignment below and I'm stuck at Step # 3 with the code file named inputforassignment2.php --basically, I am trying to append (add) rows to the existing data (songs.csv file) via that file with input fields. I tried to fix that code (which i obtained from a website, see sample source code far below, but it's returning errors or creates blank and numerical data in rows for each input.
Assignment: Create a simple PHP page that reads/writes to and from a .CSV file
The .CSV file should contain a list of your favorite items (for
example: songs, games, books, authors, etc,..). Each record in your
file should contain at least 3 attributes for your favorite item.
Also, it should have at least 7 records. --this part is done
The PHP should read the file and display the records in a TABLE with
the corresponding headers for each attribute of your favorite item.
--this part is done
Also, in the page should be a link (<< I did that part) that takes to another page where a new record can be added to the file. Then the list should display all previous records plus the new one. (<< where I am stuck)
-all my current source files:
song.csv
Song Title,Artist,Track Year
FLY,Sik-K,2017
Doverstreet,RIN,2017
Half Moon,Dean,2016
Blacklist,Loopy,2017
N/A,JooYoung,2018
Heyahe,ONE,2017
ADY,Sik-K,2017
assignment2.php how this php code displays song.csv
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment 2</title>
</head>
<?php
echo "<table border=1> ";
$f = fopen("song.csv", "r"); //open a file in read mode
while (($line = fgetcsv($f)) !== false) { //read the each line of csv file
echo "<tr>"; //for printing in the table
foreach ($line as $cell) { //each data of line
echo "<td>" . htmlspecialchars($cell) . "</td>"; //print in the table
}
echo "</tr> ";
}
fclose($f); //close file
echo " </table>";
?>
Click here to add more songs!
<body>
</body>
</html>
inputformassignment2.php
<?php
//index.php
$error = '';
$name = '';
$email = '';
$subject = '';
function clean_text($string)
{
$string = trim($string);
$string = stripslashes($string);
$string = htmlspecialchars($string);
return $string;
}
if(isset($_POST["submit"]))
{
if(empty($_POST["name"]))
{
$error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
}
else
{
$name = clean_text($_POST["name"]);
if(!preg_match("/^[a-zA-Z ]*$/",$name))
{
$error .= '<p><label class="text-danger">Only letters and white space allowed</label></p>';
}
}
if(empty($_POST["subject"]))
{
$error .= '<p><label class="text-danger">Subject is required</label></p>';
}
else
{
$subject = clean_text($_POST["subject"]);
}
if($error == '')
{
$file_open = fopen("contact_data.csv", "a");
$no_rows = count(file("contact_data.csv"));
if($no_rows > 1)
{
$no_rows = ($no_rows - 1) + 1;
}
$form_data = array(
'sr_no' => $no_rows,
'name' => $name,
'email' => $email,
'subject' => $subject,
);
fputcsv($file_open, $form_data);
$error = '<label class="text-success">Thank you for contacting us</label>';
$name = '';
$email = '';
$subject = '';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Add A New Song</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<h2 align="center">Add A New Song</h2>
<br />
<div class="col-md-6" style="margin:0 auto; float:none;">
<form method="post">
<h3 align="center">Type below:</h3>
<br />
<?php echo $error; ?>
<div class="form-group">
<label>Song Title</label>
<input type="text" name="name" placeholder="Type your song title" class="form-control" value="<?php echo $name; ?>" />
</div>
<div class="form-group">
<label>Song Artist</label>
<input type="text" name="email" class="form-control" placeholder="Type the song artist here" value="<?php echo $email; ?>" />
</div>
<div class="form-group">
<label>Track Year</label>
<input type="text" name="subject" class="form-control" placeholder="Put the song's track year here" value="<?php echo $subject; ?>" />
</div>
<div class="form-group" align="center">
<input type="submit" name="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
</body>
</html>
sample source code obtained from website:
<?php
//index.php
$error = '';
$name = '';
$email = '';
$subject = '';
$message = '';
function clean_text($string)
{
$string = trim($string);
$string = stripslashes($string);
$string = htmlspecialchars($string);
return $string;
}
if(isset($_POST["submit"]))
{
if(empty($_POST["name"]))
{
$error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
}
else
{
$name = clean_text($_POST["name"]);
if(!preg_match("/^[a-zA-Z ]*$/",$name))
{
$error .= '<p><label class="text-danger">Only letters and white space allowed</label></p>';
}
}
if(empty($_POST["email"]))
{
$error .= '<p><label class="text-danger">Please Enter your Email</label></p>';
}
else
{
$email = clean_text($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error .= '<p><label class="text-danger">Invalid email format</label></p>';
}
}
if(empty($_POST["subject"]))
{
$error .= '<p><label class="text-danger">Subject is required</label></p>';
}
else
{
$subject = clean_text($_POST["subject"]);
}
if(empty($_POST["message"]))
{
$error .= '<p><label class="text-danger">Message is required</label></p>';
}
else
{
$message = clean_text($_POST["message"]);
}
if($error == '')
{
$file_open = fopen("contact_data.csv", "a");
$no_rows = count(file("contact_data.csv"));
if($no_rows > 1)
{
$no_rows = ($no_rows - 1) + 1;
}
$form_data = array(
'sr_no' => $no_rows,
'name' => $name,
'email' => $email,
'subject' => $subject,
'message' => $message
);
fputcsv($file_open, $form_data);
$error = '<label class="text-success">Thank you for contacting us</label>';
$name = '';
$email = '';
$subject = '';
$message = '';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>How to Store Form data in CSV File using PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<h2 align="center">How to Store Form data in CSV File using PHP</h2>
<br />
<div class="col-md-6" style="margin:0 auto; float:none;">
<form method="post">
<h3 align="center">Contact Form</h3>
<br />
<?php echo $error; ?>
<div class="form-group">
<label>Enter Name</label>
<input type="text" name="name" placeholder="Enter Name" class="form-control" value="<?php echo $name; ?>" />
</div>
<div class="form-group">
<label>Enter Email</label>
<input type="text" name="email" class="form-control" placeholder="Enter Email" value="<?php echo $email; ?>" />
</div>
<div class="form-group">
<label>Enter Subject</label>
<input type="text" name="subject" class="form-control" placeholder="Enter Subject" value="<?php echo $subject; ?>" />
</div>
<div class="form-group">
<label>Enter Message</label>
<textarea name="message" class="form-control" placeholder="Enter Message"><?php echo $message; ?></textarea>
</div>
<div class="form-group" align="center">
<input type="submit" name="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
</body>
</html>

My call to a function is apparently incorrect, I know it's not, but it's not clear why

I'm trying a tutorial about making a private inbox feature, everything went well apart from the fact I get a 500 server error every time I try to press send. I have checked out the logs for what could be causing this error and here's what I received: PHP Fatal error: Call to undefined function fetch_users_id() in /apps/bla/web/inboxPage.php on line 17, referer: http://hinat.local/inboxPage.php
I have checked the function to see if anything is out of place, but cannot spot anything that could be throwing it off.
Would appreciate another pair of eyes to help me see what I have done wrong here.
Thanks in advance!
inboxPage.php:
<?php
if(isset($_POST['to'], $_POST['subject'], $_POST['body'])){
$errors = array();
if(empty($_POST['to'])){
$errors[] = 'You must enter at least one name.';
} else if (preg_match('#^[a-z, ]+$#i', $_POST['to']) === 0){
$errors[] = 'The list of names you gave does not look valid.';
} else {
$user_names = explode(',',$_POST['to']);
//Will remove and trailing spaces before and after name
foreach ($user_names as &$name){
$name = trim($name);
}
$user_id = fetch_users_id($user_names);
if(count($user_id) !== count($user_names)){
$errors[] = 'The following users could not be found: ' . implode(', ', array_diff($user_names, array_keys($user_id)));
}
}
if(empty($_POST['subject'])){
$errors[] = 'The subject cannot be empty.';
}
if(empty($_POST['body'])){
$errors[] = 'The body cannot be empty.';
}
if(empty($errors)){
}
}
if(isset($errors)){
//Form has been submitted but errors have occured
if(empty($errors)){
echo '<div class="msg success"> Your message has been sent! Return to your Inbox</div>';
//Form has been submittied and errors have occured
} else {
foreach ($errors as $errors) {
echo '<div class="msg error">', $errors, '</div>';
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="site.css" >
<link href="https://fonts.googleapis.com/css?family=Lato:100,300,400" rel="stylesheet">
</head>
<body>
<!-- Header -->
<header class="primary-header container group">
<h1 class="logo">
<!-- <img src="../home/wendy/Pictures/Logo.png" alt="Website Logo"><br> -->
</h1>
<h3 class="tagline"> Cardiff, Wales </h3>
<nav class="nav primary-nav">
<ul>
<li>Home</li><!--
--><li>Login</li><!--
--><li>Register</li><!--
--><li>Tutors</li><!--
--><li>About Us</li><!--
--><li>Contact Us</li>
</ul>
</nav>
</header>
<form action="" method= "post">
<section class="row">
<div class="grid">
<div>
<label for="to">To</label>
<input type="text" name="to" id="to" value="<?php if (isset($_POST['to'])) echo htmlentities($_POST['to']); ?>" />
</div>
<div>
<label for="subject">Subject</label>
<input type="text" name="subject" id="subject" value="<?php if (isset($_POST['subject'])) echo htmlentities($_POST['subject']); ?>" />
</div>
<div>
<textarea name="body" rows="20" cols="110"><?php if (isset($_POST['body'])) echo htmlentities($_POST['body']); ?></textarea>
</div>
<div>
<input type="submit" value="send" />
</div>
</div>
</section>
</form>
<footer class="primary-footer container group">
<small> ©</small>
<nav class="nav">
<ul>
<li>Home</li><!--
--><li>Login<!--
--><li>Tutors<!--
--><li>Register<!--
--><li>About Us<!--
--><li>Contact Us
</ul>
</nav>
</footer>
</body>
</html>
users.php:
<?php
function fetch_users_id($user_names){
foreach($user_names as &$name) {
$name = mysql_real_escape_string($name);
}
$results = mysql_query("SELECT id, Username FROM users WHERE Username IN ('" . implode("', '", $user_names) . "')");
$names = array();
while (($row = mysql_fetch_assoc($results)) !== false){
$names[$row['Username']] = $row['id'];
}
return $names;
}
?>
The function fetch_users_id does not exist in inboxPage.php
You must include or require users.php in inboxPage.php if you want to use that function within that file.
<?php
include("users.php");

else statement no being accessed in php if statement

I am writing a log in script for a site, I have most things working except on a validation mysqli query the else tatement is not being accessed and I cannot figure out how to resolve it, the code below is the index page that has the html and then the php script that is called, All of the php validation works except for the bit of script that validates all the input fields match the database fields, i can get the validation side of the if statement to work and it sends me to the relevent page, the problem is that if the validation in the first part of the if statement shows invalid it doesnt then pass to the else statement, all i get is a blank white page and it is the same as the php page doing the validation not the page i need it to go too. Any help would be most appreciated.
HTML CODE ***********
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dot Mov Home</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="/styles/home.css" rel="stylesheet" type="text/css">
<!--The following script tag downloads a font from the Adobe Edge Web Fonts server for use within the web page. We recommend that you do not modify it.-->
<script>var __adobewebfontsappname__="dreamweaver"</script>
<script src="http://use.edgefonts.net/lemon:n4:default.js" type="text/javascript"></script>
<script src="/js/civem.js"></script>
<script type='text/javascript' src='http://code.jquery.com/jquery.min.js'></script>
<script src="http://code.jquery.com/jquery-1.7.min.js"></script>
<script src="/js/pswrd_strength.js"></script>
<script src="/js/email_dbvalidate.js"></script>
<script src="/js/username_dbvalidate.js"></script>
<script src="/js/confirm_password__dbvalidate.js"></script>
<script type="text/javascript">
function SwapDivsWithClick(div1,div2)
{
d1 = document.getElementById(div1);
d2 = document.getElementById(div2);
if( d2.style.display == "none" )
{
d1.style.display = "none";
d2.style.display = "block";
}
else
{
d1.style.display = "block";
d2.style.display = "none";
}
}
</script>
</head>
<body>
<div id="video_container">
<video muted autoplay loop >
<source src="/video/South Dakota Badlands Scenic Byway 720p (Video Only)_1.3gp" type="video/3gp">
<source src="/video/South Dakota Badlands Scenic Byway 720p (Video Only).webm" type="video/webm">
<source src="/video/South Dakota Badlands Scenic Byway 720p.ogg" type="video/ogg">
Your browser does not support the video tag. I suggest you upgrade your browser. </video>
</div>
<header>
<div class="upload">UPLOAD</div>
<div class="view">VIEW</div>
<div class="spacer1"></div>
<div class="search_bar">
<form action="/search_results.php" method="post" name="search_database" autocomplete="on">
<input type="text" class="search" placeholder="Search">
</form>
</div>
<div class="logo_text">.MOV </div>
<div class="tagline">Motorcycle Online Video</div>
</a></header>
<main>
<div id="login" style="display:block">
<form method="post" action="includes/login.inc.php" id="loginform">
<input name="email" type="email" id="email" form="loginform" placeholder="Please Enter Your Email">
<input name="password" type="password" id="password" form="loginform" placeholder="Please Enter Your Password" title="Please Enter Your Password">
<div class="submit_buttons">
<input type="submit" class="login_btn" form="loginform" formaction="includes/login.inc.php" title="Login" value="Login">
<div class="join_but">Or Join</div>
</div>
<div id="forgotten_password">Forgotten Password</div>
<div class="login_statements">
<div class="statement1">
<div class="by_joining">By Joining</div>
<div class="dot_mov">.MOV</div>
<div class="agree">You agree to our</div>
</div>
<div class="statement2">
<div class="terms_link">Terms of Service</div>
<div class="and">and</div>
<div class="service_link">Privacy Policy</div>
</div>
</div>
<div class="facebook_login">
<div class="facebook_icon"><img src="images/fb.png" class="fb_icon"></div>
<div class="fb_link">Login with FaceBook </div>
</div>
</form>
</div>
</div>
<div id="join" style="display: none;">
<form action="includes/register.inc.php" method="post" id="joinform">
<input name="name2" type="text" id="name2" form="joinform" placeholder="Please Enter Your Username" title="Please Enter Your Username">
<div id="user-name">
<h4>Username must meet the following requirements!<br>If you have forgotten your Password, click on "Forgotten Password"!</h4>
<div id="name_result"></div>
<div id="name_length" class="invalid">At least <strong>6 letters</strong></div>
</div>
<input name="email2" type="email" id="email2" form="joinform" placeholder="Please Enter Your Email" title="Please Enter a Valid Email">
<div id="user-email">
<h4>Email must be a valid Email format!<br>If the Email exists, Either Login using the Username the Email was setup with or check your Email is correct!</h4>
<div id="email_result">
<div id="email_validate" class="invalid">Email Valid</div>
<div id="emaildb_validate"></div>
</div>
</div>
<input name="password2" type="password" id="password2" form="joinform" placeholder="Please Enter Your Password" title="Please Enter Your Password">
<div id="pswd_info">
<h4>Password must meet the following requirements!<br>If the Password doesnt meet the requirements you will be required to fill in the form again!</h4>
<ul id="pswd_list">
<li id="letter" class="invalid">At least <strong>one letter</strong></li>
<li id="capital" class="invalid">At least <strong>one capital letter</strong></li>
<li id="number" class="invalid">At least <strong>one number</strong></li>
<li id="length" class="invalid">Be at least <strong>8 characters</strong></li>
</ul>
</div>
<input name="confirm_password2" type="password" id="confirm_password2" form="joinform" placeholder="Please Confirm Your Password" title="Please Confirm Your Password">
<div id="user-confirm_password">
<h4>Please Confirm Password<br>If the Passwords do not match, you wil be required to fill in the form again!</h4>
<div id="error" class="error"></div>
<div id="confirm_match" class="invalid">Passwords Match</div>
</div>
<div class="submit_buttons2">
<input name="join_btn2" type="submit" id="join_btn2" form="joinform" formaction="includes/register.inc.php" " formmethod="POST" title="Join" value="Join">
<div class="join_btn2">Or Login</div>
</div>
<div class="login_statements2">
<div class="statement1">
<div class="by_joining">By Joining</div>
<div class="dot_mov">.MOV</div>
<div class="agree">You agree to our</div>
</div>
<div class="statement2">
<div class="terms_link">Terms of Service</div>
<div class="and">and</div>
<div class="service_link">Privacy Policy</div>
</div>
</div>
<div class="facebook_login2">
<div class="facebook_icon"><img src="images/fb.png" class="fb_icon"></div>
<div class="fb_link">Login with FaceBook </div>
</div>
</form>
</div>
</div>
</div>
<div class="scroll_container">
<a data-scroll href="#body2"><div class="scroll_link">
<div class="arrow"><img src="/images/arrow.png" alt="" class="arrow_icon"/></div>
<div class="arrow3"><img src="/images/arrow.png" alt="" class="arrow_icon"/></div>
Scroll Down</div></a>
</div>
</main>
<div class="body2" id="body2">
<div class="vid_grid">
<div class="top_section">
<div class="top_left_quarter"></div>
<div class="top_right_quarter">
<div class="top_right_left_quarter"></div>
<div class="top_right_right_quarter"></div>
<div class="top_right_bottom_left"></div>
<div class="top_right_bottom_right"></div>
</div>
</div>
<div class="bottom_section">
<div class="bottpm_left_top"></div>
<div class="bottpm_left_bottom"></div>
<div class="bottom_middle"></div>
<div class="bottom_left_quarter"></div>
<div class="bottom_right_quarter"></div>
<div class="bottom_right_top"></div>
<div class="bottom_right_bottom"></div>
</div>
<div class="staff_picks">Staff Picks </div>
</div>
</div>
<footer class="footer">
<div id="breadcrumbs">Terms &vert; Privacy &vert; About Us &vert; Copyright &vert; Cookies &vert; &reg &copy 2015</div><img src="/images/.mov.png" alt="" width="42" height="14" class="logo"/>
<div class="social_media"><img src="/images/fb.png" alt="" width="30" height="30" class="fbicon"/><img src="/images/twitter.png" alt="" width="32" height="32" class="twittericon"/><img src="/images/googleplus.png" alt="" width="32" height="32" class="googleplusicon"/></div>
</footer>
<script src="/js/smooth-scroll.js"></script>
<script src="/js/smooth-scroll.min.js"></script>
<script type="text/javascript">
smoothScroll.init({
speed: 1000,
easing: 'easeInOutCubic',
offset: 0,
updateURL: true,
callbackBefore: function ( toggle, anchor ) {},
callbackAfter: function ( toggle, anchor ) {}
});
</script>
</body>
</html>
PHP ***************
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
$emailErr = $passwordErr = $password_matchErr = $email_exsistErr = '';
$email = $name = $password = $confirm_password = '';
if (isset($_POST['name2'], $_POST['email2'], $_POST['paswword2'], $_POST['confirm_password2'])) {
$error_msg .= "please fill in the form";
} else {
// Sanitize the data passed in 'name'
$name = filter_input(INPUT_POST, 'name2', FILTER_SANITIZE_STRING);
// Sanitize the data passed in 'email'
$email = filter_input(INPUT_POST, 'email2', FILTER_SANITIZE_EMAIL);
// validate the data passed in 'email'
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
// check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Not a valid email
$emailErr = "The email address you entered is not valid";
}
//Sanitize the data passed in 'password'
$password = filter_input(INPUT_POST, 'password2', FILTER_SANITIZE_STRING);
//validate the data passed in 'password'
if (preg_match("/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/", $password)) {
} else {
$passwordErr = "Password is invalid!<br>Please ensure your password is formatted as described when filling in the form!";
}
//Sanitize the data passed in 'confirm_password'
$confirm_password = filter_input(INPUT_POST, 'confirm_password2', FILTER_SANITIZE_STRING);
//check that password and confirm password match
if ($password != $confirm_password) {
// error matching passwords
$confirm_passwordErr = "Your passwords do not match.<br>Please type carefully.";
}
$results = $mysqli->query("SELECT * FROM signed_up WHERE email = `'$email'");`
while($row = $results->fetch_assoc()) {
if ($row["name"] == $name && $row["email"] == $email && $row["password"] == $password) {
$regErr = 'User Already Exsists!<br>Please Login';
$_SESSION['regErr'] = $regErr;
header('location: ../login.php');
} else {
//if ($emailErr == '' && $passwordErr == '' && $password_matchErr == '' && $email_exsistErr =='') {
echo '15';
$_SESSION['emailErr'] = $emailErr;
$_SESSION['passwordErr'] = $passwordErr;
$_SESSION['confirm_passwordErr'] = $confirm_passwordErr;
$_SESSION['email_exsistErr'] = $email_exsistErr;
header('Location: ../join.php');
exit();
}
}
}
//}
?>
This is the section of code where the issue is ***********
$results = $mysqli->query("SELECT * FROM signed_up WHERE email = '$email'");
while($row = $results->fetch_assoc()) {
if ($row["name"] == $name && $row["email"] == $email && $row["password"] == $password) {
$regErr = 'User Already Exsists!<br>Please Login';
$_SESSION['regErr'] = $regErr;
header('location: ../login.php');
} else {
//if ($emailErr == '' && $passwordErr == '' && $password_matchErr == '' && $email_exsistErr =='') {
echo '15';
$_SESSION['emailErr'] = $emailErr;
$_SESSION['passwordErr'] = $passwordErr;
$_SESSION['confirm_passwordErr'] = $confirm_passwordErr;
$_SESSION['email_exsistErr'] = $email_exsistErr;
header('Location: ../join.php');
exit();
}
}
}
//}
?>
edited code that now works ***********************
$results = $mysqli->query("SELECT * FROM signed_up WHERE email = '$email'");
while($row = $results->fetch_assoc()) {
if ($row["name"] == $name && $row["email"] == $email && $row["password"] == $password) {
$regErr = 'User Already Exsists!<br>Please Login';
$_SESSION['regErr'] = $regErr;
header('location: ../login.php');
}else{
$_SESSION['emailErr'] = $emailErr;
$_SESSION['passwordErr'] = $passwordErr;
$_SESSION['confirm_passwordErr'] = $confirm_passwordErr;
$_SESSION['email_exsistErr'] = $email_exsistErr;
header('Location: ../join.php');
exit();
}
}
}
Put your validation directly into SQL
$results = $mysqli->query("SELECT count(*) FROM signed_up WHERE email = '$email' AND name = '$name'");
if ($result->fetchColumn()){
echo "User already exists";
}else{
echo "New user";
}

SESSION variable value is not passing

I'm trying to pass a value from a select input control on an HTML form.
When I hardcode it, it gets echoed, when not, all I get is this:
The invention type did not go through correctly.
Here is my page1.php:
<?php
session_start();
$_SESSION['invtype'] = $invtype;
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
if (isset($_POST['Submit'])) {
if ($_POST['firstname'] != "") {
$_POST['firstname'] = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
if ($_POST['firstname'] == "") {
$errors .= 'Please enter a valid first name.<br/><br/>';
}
} else {
$errors .= 'Please enter your first name.<br/>';
}
if ($_POST['lastname'] != "") {
$_POST['lastname'] = filter_var($_POST['lastname'], FILTER_SANITIZE_STRING);
if ($_POST['lastname'] == "") {
$errors .= 'Please enter a valid last name.<br/><br/>';
}
} else {
$errors .= 'Please enter your last name.<br/>';
}
if (!$errors) {header("location: offerform_switch.php");
}
else {
echo '<div style="color: red">' . $errors . '<br/>
</div>';
}
}
?>
<!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" lang="en" xml:lang="en">
<head>
<title>Offer Form, Part 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="inventron_sage_short.css" type="text/css" />
<link rel="stylesheet" href="form.css" type="text/css" />
</head>
<body>
<div id = "logo">
<img src = "img/top.jpg" alt = "logo" />
</div>
<div id = "wrapper">
<div id="stylized" class="myform">
<form id="form" action="page1.php" method="post">
<p>
<label for="firstname">FIRST NAME*:
</label>
<input type="text" name="firstname" id="firstname" value="<?php echo $firstname?>" />
</p>
<p>
<label for="lastname">LAST NAME*:
</label>
<input type="text" name="lastname" id="lastname" value="<?php echo $lastname?>" />
</p>
<div id = "category">Categorize your invention:</div>
<div class="spacer"></div>
<p>
<select id="invtype" name="invtype">
<option value="0" selected="selected">Select type</option>
<option value="product">PRODUCT</option>
<option value="software">SOFTWARE</option>
</select>
<input type="submit" name="Submit" value="Next!" />
</div>
</div>
</body>
</html>
Here is my offerform_switch.php:
<?php
session_start();
// echo variable from the session, we set this on our other page
echo $_SESSION['invtype'];
$invtype = $_SESSION['invtype'];
//connect to your database ** EDIT REQUIRED HERE **
mysql_connect("mysql.myserver.com","myuser","mypassword"); //(host, username, password)
//specify database ** EDIT REQUIRED HERE **
mysql_select_db("invention") or die("Unable to select database"); //select which database we're using
switch ($invtype){
case "product":
include("page2_product.php");
break;
case "software":
include("page2_software.php");
break;
default:
echo "The invention type did not go through correctly.";
}
?>
What am I doing wrong?
Thank you!
It should be
$_SESSION['invtype'] = $_POST['invtype'];
You're missing "session_id();" right below the "session_start();". I don't know why exactly it's required, but if I remember correctly, it is.

Categories