/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] PHP form: check if user input matches values in .txt files

After looking at some examples, I’m not sure if I’m on the right path for this.

I am working on having the user input checked after Submit Form is pressed to ensure the Student Name and Student Number match an existing record in [B]student.txt[/B] and the course selected is an existing course in [B]courses.txt[/B] and the maximum enrolment number has not been reached. If the student name or student number does not match an existing record the student must not be told which part of the student information does not match.

If the student name and student number match one of the records in [B]student.txt[/B] and if the course selected has not reached maximum enrolment and if the student has not enrolled in the course already, the student can be enrolled into the course and this data – student name, student number and course name and course number will be written into [B]enrollment.txt[/B].

In this section of coding under [I]// Check to see if input of $studentname matches a name in student.txt[/I], if I don’t comment out [I]//echo “<option value=”$field[1]”>$field[0] $field[1]</option>n”;[/I], the student names and student numbers are displayed so I know the file is being red and exploded.

I have a PHP form with 2 user inputs, 1 user select, a clear button and submit button:
– Input box for Student Name
– Input box for Student Number
– Drop down list with 4 available courses with the course name and
course code

I have [B]courses.txt[/B] that stores the 4 available courses with the course name, course code and the maximum number of people who can enroll all separated by a colon:

[CODE]
Animation Film Design:AFD-250:6
Digital Sculpture:DS-410:4
History of Animation:HA-240:6
Visual Effects:VE-298:4[/CODE]

I have [B]student.txt[/B] that stores the current list of student names and their student number all separated by a colon:

[CODE]
Riley Anderson:PX-06-009
Tinker Bell:DY-43-200
Carl Fredricksen:PX-45-767
Edith Gru:DW-21-492
Mad Hatter:DY-03-195
Buzz Lightyear:PX-34-121
Stuart Little:CP-17-199
Bob Minion:DW-34-628
Thomas O’Malley:DY-21-987
Kitty Softpaws:DW-07-201
James Sullivan:PX-01-111
Mike Wazowski:PX-68-524
Sheriff Woodie:PX-32-597[/CODE]

[code=php]<html>
<head>
<title>Registration Form</title>
<style>
body{background-color: #ffffe6; width:610px;}
h1 {color: #29a3a3;}
.inputbox {padding: 7px; border: #FF9966 1px solid; border-radius: 4px;}
.btn {padding: 10px; background-color: #29a3a3; border: solid 1px #FF9966; border-radius: 4px; color: #FFFFFF; font-weight: bolder; cursor: pointer;}
</style>
</head>
<body>
<?php
ini_set(‘display_errors’, 1);
error_reporting(E_ALL);
// Sanitization and Validation coding will go here

// Define and set variables
$studentname = “”;
$studentnumber = “”;
$courses = ” “;
$datafile = “student.txt”;
$in = fopen (‘courses.txt’, ‘r’) or die (“courses.txt cannot be opened for reading.”);

// Check to see if input of $studentname matches a name in student.txt
if (isset ($_POST[‘student.txt’])) {
$studentname = htmlentities ($_POST[‘student.txt’]);
$DB = fopen ($datafile, ‘r’) or die (“$datafile cannot be opened for reading.”);

$found = FALSE;
while ($record = fgets ($DB) and ! $found) {
$field = explode (“:”, htmlentities (trim ($record)));
$found = $studentname === $field[0];
}

fclose ($DB);

if ($found) {
echo “<p>$field[0] $field[1].</p>n”;
}
}

$DB = fopen ($datafile, ‘r’) or die (“$datafile cannot be opened for reading.”);
while ($record = fgets ($DB) ) {
$field = explode (“:”, htmlentities (trim ($record)));
//echo “<option value=”$field[1]”>$field[0] $field[1]</option>n”;
}
fclose ($DB);

$filename = ‘test.txt’;
if(file_exists($filename)) {
if($handle = fopen($filename, ‘r’)) {
$name = array();
while(($file = fgets($handle)) !==FALSE) {
preg_match(‘#(.*):(.*)#’, $file, $match);
$array = explode(‘,’, $match[2]);
foreach($array as $val) {
$name[$match[1]][] = $val;
}

}
}
}

?>

<h1>Course Registration</h1>
<form method=”post” action=”index.php”>
<fieldset><legend><strong>Student Information</strong></legend>
<dl>
<dt>Student Name:</dt>
<dd><input class=”inputbox” name=”studentname” type=”text” id=”studentname” value=”<?php echo $studentname;?>” required autofocus placeholder=”Please enter your first and last name” tabindex=”10″ size=”50″></dd>
<br>
<br>
<dt>Student Number:</dt>
<dd><input class=”inputbox” name=”studentnumber” type=”text” id=”studentnumber” value=”<?php echo $studentnumber;?>” required placeholder=”Please enter using the following format: PX-03-046″ tabindex=”20″ size=”50″></dd>
</dl>
<br>
</fieldset>
<br>
<fieldset><legend><strong>Course Selection</strong></legend>
<br>
Select a Course:<select name=”courses” tabindex=”30″>n”;
<option value=”-1″ >Available Courses…</option>
<?php
while(($fields = fgetcsv($in, null, ‘:’)) != false) {
if (count($fields) > 1) {
echo ”
<option value=”$fields[1]”>$fields[0] $fields[1]</option>”;
}
}
?>
</select>
<br>
<br>
<br>
<br>
<br>
<br>
</fieldset>
<div>
<p>
<input name=”reset” type=”reset” tabindex=”40″ value=”Clear Form” class=”btn”>
<input name=”submit” type=”submit” tabindex=”50″ value=”Submit Form” class=”btn”>
</p>
</div>
</form>
</body>
</html>[/code]

[ATTACH]17047[/ATTACH]

Thank you

[canned-message]attachments-removed-during-migration[/canned-message]

to post a comment
PHP

8 Comments(s)

Copy linkTweet thisAlerts:
@NogDogMar 11.2016 — In the spirit of divide and conquer, let's look at the validation of the student name and number. We can use the same sort of file parsing as we did for the course data. This time, let's put it all into a function, so that we can keep it separated from the main flow, and also have something that could easily be re-used anywhere you need to do that validation.

[code=php]
<?php

/**
* Validate student name/number against text file
*
* @param string $studentName
* @param string $studentNumber
* @return bool
*/
function validateStudent($studentName, $studentNumber)
{
$found = false;
$fh = fopen('student.txt', 'r');
while(($line = fgetcsv($fh, null, ':')) != false) {
if(count($line) > 1) {
if($line[0] == $studentName and $line[1] == $studentNumber) {
$found = true;
break;
}
}
}
return $found;
}

// let's try it out (this is just to test the function)
$testData = array(
array('name' => 'NogDog', 'number' => 'ABC-123'),
array('name' => '', 'number' => ''),
array('name' => 'Kitty Softpaws', 'number' => 'DW-07-201')
);
echo '<pre>';
foreach($testData as $student) {
echo "Name: '{$student['name']}', Number: '{$student['number']}' = ";
if(validateStudent($student['name'], $student['number'])) {
echo "VALIDn";
}
else {
echo "INVALIDn";
}
}
echo '</pre>';
[/code]

The test section at the end outputs:
<i>
</i>Name: 'NogDog', Number: 'ABC-123' = INVALID
Name: '', Number: '' = INVALID
Name: 'Kitty Softpaws', Number: 'DW-07-201' = VALID

Where I used $student['name'] and $student['number'] in the test, you'd actually use the values from the form: $_POST['studentname'] and $_POST['studentnumber'] where/when you want to actually validate those inputs. The nice thing about this is that the function definition can be anywhere within the file (just not inside any kind of conditional or loop block), so you can keep it out of the way of the main flow of the script.
Copy linkTweet thisAlerts:
@BlondieCauthorMar 13.2016 — I spent a considerable amount of time with the code you provided to see what it did, how it did it, tested it with my file of student names so I can understand it. The next step I tried was calling the function and then Googling this as of course I have a glitch. But not as bad as some I was having earlier in the day. I called the function in the first block of code below. The glitch is the second echo message is returned even when I enter a valid student name student number unlike in your function test it returned "VALID" when it was a valid student name and student number.
[code=php]if (isset ($_POST[$studentname], $_POST[$studentnumber])) {
validateStudent($_POST['studentname'], $_POST['studentnumber']);
echo "Student name and number is valid.n";
}
else {
echo '<p style="color: red; text-align: center; font-size: 15px; font-weight: bold;">**The information you have entered is not valid. Please enter your information again.**</p>';
}[/code]


Complete code with your test code commented out...
[code=php]<html>
<head>
<title>Registration Form</title>
<style>
body{background-color: #ffffe6; width:610px;}
h1 {color: #29a3a3;}
.inputbox {padding: 7px; border: #FF9966 1px solid; border-radius: 4px;}
.btn {padding: 10px; background-color: #29a3a3; border: solid 1px #FF9966; border-radius: 4px; color: #FFFFFF; font-weight: bolder; cursor: pointer;}
</style>
</head>
<body>

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Define and set variables
$student = "";
$studentname = "";
$studentnumber = "";
$studentfile = "student.txt";
$coursename = "";
$coursenumber = "";
$coursefile = "course.txt";
$in = fopen ('course.txt', 'r') or die ("course.txt cannot be opened for reading.");

// Sanitization and Validation coding will go here

/**
* Validate student name/number against text file
*
* @param string $studentName
* @param string $studentNumber
* @return bool
*/
function validateStudent($studentName, $studentNumber) {
$found = false;
$fh = fopen('student.txt', 'r');
while(($line = fgetcsv($fh, null, ':')) != false) {
if(count($line) > 1) {
if($line[0] == $studentName and $line[1] == $studentNumber) {
$found = true;
break;
}
}
}
return $found;
}

//Test the function)
//$studentfile = array(
//array('name' => '', '' => 'ABC-123'),
//array('name' => '', '' => ''),
//array('name' => '', '' => 'DW-07-201')
//);
//echo '<pre>';

//foreach($studentfile as $student) {
//echo "Name: '{$_POST['studentname']}', Number: '{$_POST['studentnumber']}' = ";
//if(validateStudent($_POST['studentname'], $_POST['studentnumber'])) {
//echo "VALID.n";
//}
//else {
//echo "INVALID.n";
//}
//}
//echo '</pre>';


if (isset ($_POST[$studentname], $_POST[$studentnumber])) {
validateStudent($_POST['studentname'], $_POST['studentnumber']);
echo "Student name and number is valid.n";
}
else {
echo '<p style="color: red; text-align: center; font-size: 15px; font-weight: bold;">**The information you have entered is not valid. Please enter your information again.**</p>';
}

?>

<h1>Course Registration</h1>
<form method="post" action="index.php">
<fieldset><legend><strong>Student Information</strong></legend>
<dl>
<dt>Student Name:</dt>
<dd><input class="inputbox" name="studentname" type="text" id="studentname" value="<?php echo $studentname;?>" required autofocus placeholder="Please enter your first and last name" tabindex="10" size="50"></dd>
<br>
<br>
<dt>Student Number:</dt>
<dd><input class="inputbox" name="studentnumber" type="text" id="studentnumber" value="<?php echo $studentnumber;?>" required placeholder="Please enter using the following format: PX-03-046" tabindex="20" size="50"></dd>
</dl>
<br>
</fieldset>
<br>
<fieldset><legend><strong>Course Selection</strong></legend>
<br>
Select a Course:<select name="courses" tabindex="30">n";
<option value="-1" >Available Courses...</option>
<?php
while(($fields = fgetcsv($in, null, ':')) != false) {
if (count($fields) > 1) {
echo "
<option value="$fields[1]">$fields[0] $fields[1]</option>";
}
}
?>
</select>
<br>
<br>
<br>
<br>
<br>
<br>
</fieldset>
<div>
<p>
<input name="reset" type="reset" tabindex="40" value="Clear Form" class="btn">
<input name="submit" type="submit" tabindex="50" value="Submit Form" class="btn">
</p>
</div>
</form>
</body>
</html>[/code]
Copy linkTweet thisAlerts:
@SempervivumMar 13.2016 — checked after Submit Form is pressed to ensure the Student Name and Student Number match an existing record in student.txt and the course selected is an existing course in courses.txt[/QUOTE]I wonder if it would be better to prevent the user from inputting wrong values by creating select elements based on the text files.
Copy linkTweet thisAlerts:
@ginerjmMar 13.2016 — Sempervivum - People can still submit form data that breaks those attempts.

BlondieC - still mixing your html and php code all together I see. Tsk, Tsk.
Copy linkTweet thisAlerts:
@NogDogMar 13.2016 — Your if condition tests if the variables are set, but not if they are valid. Youu could add an "and" to the condition:
[code=php]
if( isset($_POST[$studentname], $_POST[$studentnumber]) and
validateStudent($_POST['studentname'], $_POST['studentnumber'])) {
// good
}
else {
// bad
}
[/code]
Copy linkTweet thisAlerts:
@BlondieCauthorMar 13.2016 — Are you speaking to this code below? It was the only way I could get the course values to display where I need them to. Should I be doing this as a function and then just calling the function there?
[code=php]<fieldset><legend><strong>Course Selection</strong></legend>
<br>
Select a Course:<select name="courses" tabindex="30">n";
<option value="-1" >Available Courses...</option>
<?php
while(($fields = fgetcsv($in, null, ':')) != false) {
if (count($fields) > 1) {
echo "
<option value="$fields[1]">$fields[0] $fields[1]</option>";
}
}
?>
</select> [/code]


Sempervivum - People can still submit form data that breaks those attempts.

BlondieC - still mixing your html and php code all together I see. Tsk, Tsk.[/QUOTE]
Copy linkTweet thisAlerts:
@NogDogMar 13.2016 — Nope, I was referencing this code:
[code=php]
if (isset ($_POST[$studentname], $_POST[$studentnumber])) {
validateStudent($_POST['studentname'], $_POST['studentnumber']);
echo "Student name and number is valid.n";
}
else {
echo '<p style="color: red; text-align: center; font-size: 15px; font-weight: bold;">**The information you have entered is not valid. Please enter your information again.**</p>';
}
[/code]

As written, the if() only checks if the input values are set. Within the block of code that gets executed if the if() is true, you call the validation function, but don't actually do anything with it, so it serves no actual purpose. Moving the call to the validation function into the if() condition makes it actually help determine what happens (the if block only gets executed if the variables are set AND then they pass validation).
Copy linkTweet thisAlerts:
@BlondieCauthorMar 14.2016 — It's getting there. ?

[code=php]<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Define and set variables
$student = "";
$studentname = "";
$studentnumber = "";
$studentfile = "student.txt";
$course = "";
$coursename = "";
$coursenumber = "";
$coursemax = 0;
$coursefile = "course.txt";
$in = fopen ('course.txt', 'r') or die ("course.txt cannot be opened for reading.");

// Sanitization and Validation coding will go here
if (isset($_POST['submit'])) {
$studentname = $_POST['studentname'];
$studentnumber = $_POST['studentnumber'];
}

if (isset($_POST['studentname'])) {
$studentname = strip_tags ($_POST['studentname']);
$studentname = htmlentities ($_POST['studentname']);
}

if (isset($_POST['studentnumber'])) {
$studentnumber = strip_tags ($_POST['studentnumber']);
$studentnumber = htmlentities ($_POST['studentnumber']);
}

if (isset($_POST['course'])) {
$course = strip_tags ($_POST['course']);
$course = htmlentities ($_POST['course']);
}

//$studentname = trim($_POST['studentname']); //getting undefined index message

//$studentnumber = trim($_POST['studentnumber']); //getting undefined index message


// Validate student name/number against text file

function validateStudent($studentName, $studentNumber)
{
$found = false;
$fh = fopen('student.txt', 'r');
while(($line = fgetcsv($fh, null, ':')) != false) {
if(count($line) > 1) {
if($line[0] == $studentName and $line[1] == $studentNumber) {
$found = true;
break;
}
}
}
return $found;
}

// Validate course name/number against text file
function validateCourse($courseName, $courseNumber, $courseMax)
{
$found = false;
$fh = fopen('course.txt', 'r');
while(($line = fgetcsv($fh, null, ':')) != false) {
if(count($line) > 1) {
if($line[0] == $courseName and $line[1] == $courseNumber and $line[2] == $courseMax) {
$found = true;
break;
}
}
}
return $found;
}


//$DB = fopen ($coursefile, 'r') or die ("$coursefile cannot be opened for reading.");
//while ($record = fgets ($DB) ) {
//$field = explode (":", htmlentities (trim ($record)));
//echo "<option value="$field[1]">$field[0] $field[1] $field[2]</option>n";
//}
//fclose ($DB);


if( isset( $studentname, $studentnumber)) {
$valid = validateStudent($studentname, $studentnumber);
if( !$valid ){
echo '<p style="color: red; text-align: center; font-size: 15px; font-weight: bold;">**The information you have entered is not valid. Please enter your information again.**</p>';
} else {
echo '<p style="color: black; text-align: center; font-size: 15px; font-weight: bold;">Your information has been entered correctly</p>';
}
}




?>
<html>
<head>
<title>Registration Form</title>
<style>
body{background-color: #ffffe6; width:610px;}
h1 {color: #29a3a3;}
.inputbox {padding: 7px; border: #FF9966 1px solid; border-radius: 4px;}
.btn {padding: 10px; background-color: #29a3a3; border: solid 1px #FF9966; border-radius: 4px; color: #FFFFFF; font-weight: bolder; cursor: pointer;}
</style>
</head>
<body>
<h1>Course Registration</h1>
<form method="post" action="index.php">
<fieldset><legend><strong>Student Information</strong></legend>
<dl>
<dt>Student Name:</dt>
<dd><input class="inputbox" name="studentname" type="text" id="studentname" value='<?php echo htmlentities($studentname) ?>' required autofocus placeholder="Please enter your first and last name" tabindex="10" size="50"></dd>
<br>
<br>
<dt>Student Number:</dt>
<dd><input class="inputbox" name="studentnumber" type="text" id="studentnumber" value='<?php echo htmlentities($studentnumber) ?>' required placeholder="Please enter using the following format: PX-03-046" tabindex="20" size="50"></dd>
</dl>
<br>
</fieldset>
<br>
<fieldset><legend><strong>Course Selection</strong></legend>
<br>
Select a Course:<select name="course" tabindex="30">n";
<option value="-1" >Available Courses...</option>
<?php
while(($fields = fgetcsv($in, null, ':')) != false) {
if (count($fields) > 1) {
echo "
<option value="$fields[1]">$fields[0] $fields[1]</option>";
}
}
?>
</select>
<br>
<br>
<br>
<br>
<br>
<br>
</fieldset>
<div>
<p>
<input name="reset" type="reset" tabindex="40" value="Clear Form" class="btn">
<input name="submit" type="submit" tabindex="50" value="Submit Form" class="btn">
</p>
</div>
</form>
</body>
</html> [/code]
×

Success!

Help @BlondieC spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...