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

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>

Related

php $_SESSION variables lost after redirection with header...again

I know this question has been asked many times before over the years. However, I am facing the wall after attempting to correctly implement all the potential solutions that others have listed in this post: "https://stackoverflow.com/questions/17242346/php-session-lost-after-redirect".
I know my session variables exist before using "header("location: nextPage.php");" to redirect. As soon as I put the line in the code, the session variables disappear. I am posting all my code because I did tried all the solutions I have seen. So maybe, the problem is my code and someone can find what I am doing wrong.
Thank you in advance.
<?php
session_save_path('/home/myHome/cgi-bin/tmp');
session_start();
$fnameErr = $lnameErr = $ssnErr = $dofbErr = $occpErr = $filstatErr = "";
$fname = $mname = $lname = $ssn = $dofb = $occp = $filstat = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
global $fnameErr, $lnameErr;
if (empty($_POST["fname"])) {
$fnameErr = "Your first name is required";
} else {
$fname = test_input($_POST["fname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$fname)) {
$fnameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["lname"])) {
$lnameErr = "Your last name is required";
} else {
$lname = test_input($_POST["lname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$lname)) {
$lnameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["ssn"])) {
$ssnErr = "Your social security number is required";
} else {
$ssn = test_input($_POST["ssn"]);
// check if name only contains letters and whitespace
if (!preg_match("/[0-9]{3}-[0-9]{2}-[0-9]{4}/",$ssn)) {
$ssnErr = "There is an error in your social security number";
}
}
if (empty($_POST["dofb"])) {
$dofbErr = "Your date of birth is required";
} else {
$dofb = $_POST["dofb"];
}
if (empty($_POST["occp"])) {
$occpErr = "Your occupation is required";
} else {
$occp = test_input($_POST["occp"]);
}
if (isset($_REQUEST["filstat"]) && $_REQUEST["filstat"] == "disabled selected hidden") {
$filstatErr = "Your filing status is required";
} else {
$filstat = test_input($_POST["filstat"]);
}
if(isset($_POST['next'])){
if ($fnameErr == "" && $lnameErr == "" && $ssnErr == "" && $dofbErr == "" && $occpErr == "" && $filstatErr == "") {
session_write_close();
header("location: nextPage.php");
exit();
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<script src="https://kit.fontawesome.com/1bd5f284bd.js" crossorigin="anonymous"></script>
<title>Welcome</title>
</head>
<body>
<div class="grid-container">
<div class="header">
<h1>someTitle</h1> <h5>subTitle</h5>
</div>
<div class="menu">
<ul>
<li><a class="active" href="index.php"><i class='fas fa-user-alt'></i>Personal Info</a></li>
<li><i class='fas fa-city'></i>W-2 Employer info</li>
<li><i class='fas fa-dollar-sign'></i>W-2 Earned Income</li>
<li><i class='fas fa-hand-holding-usd'></i>Cash Income</li>
<li><i class='fas fa-book-reader'></i>Review</li>
<li><i class='fas fa-upload'></i>Submit</li>
</ul>
</div>
<div class="main">
<h2>Please complete your personal information below</h2>
<p class="error">* required field</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<label for="fname">First Name:<span class="error"> * <?php echo $fnameErr;?></span></label>
<input type="text" id="fname" name="fname" maxlength="40" placeholder="Your name.." value="<?php echo $fname; ?>">
<label for="mname">Middle Initial:</label>
<input type="text" id="mname" name="mname" maxlength="1" value="<?php echo $mname; ?>">
<label for="lname">Last Name:<span class="error"> * <?php echo $lnameErr;?></span></label>
<input type="text" id="lname" name="lname" maxlength="50" placeholder="Your last name.." value="<?php echo $lname; ?>">
<label for="ssn">Social Security Number:<span class="error"> * <?php echo $ssnErr;?></span></label>
<input type="text" id="ssn" name="ssn" minlength="9" maxlength="11" placeholder="000-00-0000" value="<?php echo $ssn; ?>" onBlur = "myFunc()">
<label for="dofb">Date of Birth:<span class="error"> * <?php echo $dofbErr;?></span></label>
<input type="date" id="dofb" name="dofb" maxlength="10" min="1930-01-01" max="2000-12-31" value="<?php echo $dofb; ?>">
<label for="occp">Occupation<span class="error"> * <?php echo $occpErr;?></span></label>
<input type="text" id="occp" name="occp" maxlength="40" placeholder="Your principal work" value="<?php echo $occp; ?>">
<label for="filstat">Filing Status:<span class="error"> * <?php echo $filstatErr;?></span></label>
<select id="filstat" name= "filstat" required>
<option value="disabled selected hidden">Choose Filing Status</option>
<option value="Single">Single</option>
<option value="Married filing jointly">Married filing jointly</option>
<option value="Head of Household">Head of Household</option>
</select>
<input type="reset" value="Reset">
<input type="submit" name="next" value="Next">
</form>
</div>
<div class="instructions">
<h2>Help Center</h2>
<p>Instructions to what needs to be done go here.</p>
</div>
<div class="footer">
<p>© Copyright 2020–2021 websiteName ® All rights reserved</p>
</div>
</div>
<script type="text/javascript">
function myFunc() {
var patt = new RegExp("\d{3}[\-]\d{2}[\-]\d{4}");
var x = document.getElementById("ssn");
var res = patt.test(x.value);
if(!res){
x.value = x.value
.match(/\d*/g).join('')
.match(/(\d{0,3})(\d{0,2})(\d{0,4})/).slice(1).join('-')
.replace(/-*$/g, '');
}
}
</script>
</body>
</html>

Why the error message is not showing in my PHP code after adding CSS?

I've wrote this code for a comment section for my website. But that was suppose to show error message beside the '*' sign when anyone types in incorrect email or empty comment. It was doing good, but after I've added the CSS styles it is not working.
I'm reading the input and passing that to PHP. After PHP checks that, I save that to a comment folder. Or else if the format is wrong, I give an error message. But now the error message is not showing for some reason.
Link of the code running in a host https://cryptocrack.000webhostapp.com/comment/test/index.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" name="viewport" content="width=device-width , initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="wrapper">
<div class="title">
<h2>Leave a comment</h2>
</div>
<div class="contact-form">
<div class="input-fields">
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" name="name" class="input" placeholder="Name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
<input type="text" name="email" class="input" placeholder="Email Address" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
</div>
<div class="msg">
<textarea name="comment" placeholder="Comment"><?php echo $comment;?></textarea>
<span class="error">* <?php echo $commentErr;?></span>
<br><br>
<input type="submit" name="submit" class="btn" value="Submit">
</div>
</form>
</div>
</div>
<div class="cm">
<div class="tl">
<h1>Comments</h1>
</div>
<br><br>
<?php
// define variables and set to empty values
date_default_timezone_set("Asia/Dhaka");
$nameErr = $emailErr = $commentErr = "";
$name = $email = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Comment is required";
} else {
$comment = test_input($_POST["comment"]);
}
if($nameErr==""&&$emailErr==""&&$commentErr==""){
$cd=date("d.m.Y l h:i:s a");
$d=(string)mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y"));
$cf = fopen(getcwd()."/comments/".$d.".txt", "w");
fwrite($cf, $name."\n");
fwrite($cf, $cd."\n");
fwrite($cf, $email."\n");
fwrite($cf, $comment);
fclose($cf);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$dir=getcwd()."/comments/";
$cm = scandir($dir,1);
$len = count($cm)-2;
for($i=0;$i<$len;$i++){
$f=fopen($dir.$cm[$i],"r");
echo "<div class=\"name\">" .fgets($f)."</div><div class=\"date\">".fgets($f)."</div><div class=\"email\">".fgets($f)."</div><br>";
while(!feof($f)){
echo fgets($f)."<br>";
}
echo "<br><br>";
}
?>
</div>
</body>
</html>
<?php if(isset($nameErr)){ echo $nameErr; } ?>
use that instead of
<?php echo $nameErr;?>
You get error cause the variables are not defined.

Return different text each time the form is submitted PHP

I have a form that writes an array to CSV, and then displays a password. Each time the form is used data is written to a new line in the CSV and the same password is displayed.
I would like to display a different password each time the form is submitted.
So the first time someone uses the form, their $name,$starttime,$endtime,$today,$message & #pwrd[0] are all written to the CSV, and then #pwrd[0] is displayed on the page.
The second time someone fills the form, their $name,$starttime,$endtime,$today,$message & #pwrd[1] are all written to the CSV, and then #pwrd[1] is displzyed on the page.
Essentially I want to give out different credentials to each visitor, and record their details each time. Ideally these creds are pulled from a fairly secure place, but an array,text file or CSV will do for this application..
Many Thanks in advance!! :)
<?php
//index.php
$error = '';
$name = '';
$starttime = '';
$endtime = '';
$timedate = 'timedate';
$today = date("Y-m-d H:i:s");
$message = '';
$pwrd = array("User1 / Password1", "User2 / Password2", "User3 / Password3");
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["starttime"]))
{
$error .= '<p><label class="text-danger">Start Time and Date is required eg: 01/01/2020 08:00</label></p>';
}
else
{
$starttime = clean_text($_POST["starttime"]);
}
if(empty($_POST["endtime"]))
{
$error .= '<p><label class="text-danger">Start Time and Date is required eg: 23/01/2020 18:00</label></p>';
}
else
{
$endtime = clean_text($_POST["endtime"]);
}
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,
'today' => $today,
'starttime' => $starttime,
'endtime' => $endtime,
'message' => $message,
'pwrd' => $pwrd[0]
);
fputcsv($file_open, $form_data);
$error = '<label class="text-success">The Temporary login details are </label>';
$name = '';
$today = '';
$starttime = '';
$endtime = '';
$message = '';
$pwrd[0] = '';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Enter the temporary staff details below to receive login details</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">Enter the temporary staff details below to receive login details</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 Temp Staff Name</label>
<input type="text" name="name" placeholder="Enter Full Name of Temporary Staff" class="form-control" value="<?php echo $name; ?>" />
</div>
<div class="form-group">
<label>Enter Start Time & Date</label>
<input type="text" name="starttime" class="form-control" placeholder="Enter Start Time & Date, eg: 01/01/2020 08:00" value="<?php echo $starttime; ?>" />
</div>
<div class="form-group">
<label>Enter Finish Time & Date</label>
<input type="text" name="endtime" class="form-control" placeholder="Enter Finish Time & Date, eg: 23/01/2020 18:00" value="<?php echo $endtime; ?>" />
</div>
<div class="form-group">
<label>Enter Your Name</label>
<textarea name="message" class="form-control" placeholder="Enter Your Name"><?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>
<a href='index.php'>Back to Main page</a>
</body>
</html>

After submit form csv file saved and i want redirect another website

I have a form set up and a php file (as shown below) that I have saved data in csv file to validate the input and then redirect to a different website (index.html). The validation and csv export works perfectly, but I can't figure out how to get the form to redirect to the wanted page instead of just showing the post return.
<?php
//index.php
$error = '';
$name = '';
$email = '';
$phone = '';
$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["phone"]))
{
$error .= '<p><label class="text-danger">phone is required</label></p>';
}
else
{
$phone = clean_text($_POST["phone"]);
}
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("enquiry_form_data.csv", "a");
$no_rows = count(file("enquiry_form_data.csv"));
if($no_rows > 1)
{
$no_rows = ($no_rows - 1) + 1;
}
$form_data = array(
'sr_no' => $no_rows,
'name' => $name,
'email' => $email,
'phone' => $phone,
'message' => $message
);
fputcsv($file_open, $form_data);
$error = '<label class="text-success">Thank you for contacting us</label>';
$name = '';
$email = '';
$phone = '';
$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"> <br />
<div class="col-md-6" style="margin:0 auto; float:none;">
<form method="post">
<h3 align="center">Find your dream Holiday today!</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 phone</label>
<input type="text" name="phone" class="form-control" placeholder="Enter phone" value="<?php echo $phone; ?>" />
</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>
I have a form set up and a php file (as shown below) that I have saved data in csv file to validate the input and then redirect to a different website (index.html). The validation and csv export works perfectly, but I can't figure out how to get the form to redirect to the wanted page instead of just showing the post return.
Try below code:
<?php
header('Location: http://www.example.com/');
?>

PHP logic error in a php form code

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.

Categories