Early exit gives blank page PHP? - php

I'm trying to clean up my code by "early exits" and keep getting a blank page everytime I use the return statement.
Should I move the php code to a seperate file?
Also I would be happy to get some tips of cleaning up my code.Thanks!!
<?php
$capt_error = "";
$mismatch = "";
$name = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
session_start();
// validate captcha
if (empty($_POST["capt"])) {
$capt_error = "Fältet är obligatoriskt.";
return null; // HERE, I GET A BLANK PAGE
} else {
if($_POST['capt'] != $_SESSION['rand']) {
$name = $_POST["name"];
$message = $_POST['message'];
$mismatch = "Inmatningen av CAPTHA är fel. Vänligen prova igen.";
}
else {
// write to file but only if cookie is not set
$ip_address = $_SERVER['REMOTE_ADDR'];
$time_stamp = date('Y-m-d H:i');
$data = "\n" . $_POST['name'] . ',' . $_POST['message'] . ',' . $ip_address . ',' . $time_stamp;
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if ($ret == false) {
die('Fel vid skrivning till fil. Skrivrättigheter saknas');
}
// set cookie
$cookie_name = $_POST['name'];
$cookie_value = $ip_address;
setcookie($cookie_name, $cookie_value, null, "/");
}
}
}
?>
<link rel="stylesheet" href="labb1.css" type="text/css">
<html>
<head>
<title>Labb 1</title>
</head>
<body>
<h1 class="title">Laboration 1 - Gästboken</h1>
<table border="1">
<thead>
<tr>
<th colspan="3" class="table-title">Min Gästbok</th>
</tr>
</thead>
<tbody>
<tr>
<td class="bold">FRÅN</td>
<td class="bold">INLÄGG</td>
<td class="bold">LOGGNING</td>
</tr>
<?php
// open file
$f = fopen("data.txt", "r");
// while not end of file
while (!feof($f)) {
// split values with -
$arr = explode(",", trim(fgets($f), "\r\n"));
print "<tr>";
print "<td>$arr[0]</td>";
print "<td>$arr[1]</td>";
print "<td>IP: $arr[2]<br>TID: $arr[3]</td>";
print "</tr>";
}
?>
</tbody>
</table>
<form action="" method="post">
<div class="border">
<div>
<span>Namn:</span>
<input type="text" name="name" value="<?php echo $name;?>">
</div>
<div>
<span>Meddelande:</span>
<textarea name="message" rows="5"><?php echo $message;?></textarea>
</div>
<div>
<?php
$rand = substr(str_shuffle(str_repeat("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
session_start();
$_SESSION["rand"] = $rand;
print "<span>CAPTCHA skriv detta i rutan nedan: </span> <span class='red bold'>$rand</span>"
?>
<span class="error">* <?php echo $capt_error; ?></span>
<input type="text" name="capt">
<span class="error"><?php echo $mismatch?></span>
</div>
<div>
<input type="submit" value="Skicka">
</div>
<div>
<span class="red">*</span> är ett obligatoriskt fält
</div>
</div>
</form>
</body>
</html>

You seem to be using the return statement incorrectly in your code. The following is from the docs:
http://php.net/manual/en/function.return.php
If called from the global scope, then execution of the current script file is ended. If the current script file was included or required, then control is passed back to the calling file.
What you seem to want to do is to capture the error message and then use it later on in your code - which is perfectly fine to do. Just set a variable with the error, continue your code and check the variables later on.

Related

Display of database fetched data in HTML through PHP

I have an textarea to create an article, which then gets loaded into the db.
Also i have a function to fetch an article by chapter number to display it on the site.
The function works well, but the fetched data, or better said all echos from the PHP function get right into the body-tag which kills my layout.
I'd like to know, how can I display the data from the PHP output into a specific area in my HTML?
index.html:
<body>
<div class="main">
<h1>WebDev's Playground</h1>
<p>Momentaner Versuch: Formatierte Texte in Datenbanken speichern.</p>
<div class="playground">
<form action="?send=1" method="post">
<label for="heading">Überschrift</label>
<input name="heading" type="text" style="display:block;" />
<label for="chapter">Kapitel</label>
<input name="chapter" type="number" style="display:block;"/>
<textarea name="textbereich" rows="10" cols="130"></textarea>
<input type="submit" style="display:block;" />
</form>
</div>
<div>
<form action="?read=1" method="post">
<input name="chapter" type="number">
<button type="submit">Auslesen</button>
</form>
</div>
</div>
</body>
And this is from my logic.php:
//BEGINNING fetching data / ouput data
if (isset($_GET['read'])) {
$id = "";
$chapter = $_POST['chapter'];
$heading = "";
$textbereich = "";
$error = false;
$errormessage = "Es ist folgender Fehler aufgetreten: ";
if (!$error) {
$statement = $pdo->prepare("SELECT * FROM beitraege WHERE chapter = :chapter");
$result = $statement->execute(array("chapter" => $chapter));
$ergebnis = $statement->fetch(PDO::FETCH_ASSOC);
print ("<h2>" . $ergebnis['heading'] . "</h2>");
print ("<p>Kapitel: " . $ergebnis['chapter'] . "</p>");
print ("<pre>" . $ergebnis['content'] . "</pre>");
}
}
//END fetching data/ output data
?>
Solution: I have to store the data in variables and call them on the HTML in the wanted area.
$outputHeading = "";
$outputChapter = "";
$outputContent = "";
if (!$error) {
$statement = $pdo->prepare("SELECT * FROM beitraege WHERE chapter = :chapter");
$result = $statement->execute(array("chapter" => $chapter));
$ergebnis = $statement->fetch(PDO::FETCH_ASSOC);
$outputHeading = $ergebnis['heading'];
$outputChapter = $ergebnis['chapter'];
$outputArticle = $ergebnis['content'];
}
and in HTML:
<div>
<form action="?read=1" method="post">
<input name="chapter" type="number">
<button type="submit">Auslesen</button>
</form>
<h2><?php echo $outputHeading;?></h2>
<h2><?php echo $outputChapter; ?></h2>
<pre><?php echo $outputContent; ?></pre>
</div>
I hope this text area you are getting data and store it into DB,
<textarea name="textbereich" rows="10" cols="130"></textarea>
but when you are fetching from DB your tag should be
<textarea name="textbereich" rows="10" cols="130"><?php echo $value; ?></textarea>
so that the value will be populated in text Area

PHP setcookie is not working

I know there are quite a few threads out there that deals with this question but every question seems unique (or so...)
I'm having trouble setting a cookie so that I can validate the user against it later
A php newbie....what might be the problem here?
I've checked the php.ini file and cookies are allowed.
<?php
$capt_error = "";
$already_made_post = "";
$mismatch = "";
$name = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
session_start();
if (empty($_POST["capt"])) {
$capt_error = "Fältet är obligatoriskt.";
} else {
// validate captcha
if($_POST['capt'] != $_SESSION['rand']) {
$name = $_POST["name"];
$message = $_POST['message'];
$mismatch = "Inmatningen av CAPTHA är fel. Vänligen prova igen.";
}
else {
$ip_address = $_SERVER['REMOTE_ADDR'];
$time_stamp = date('Y-m-d H:i');
$cookie_name = $_POST['name'];
$cookie_value = $ip_address;
// write to file but only if cookie is not set
if(isset($_COOKIE[$cookie_value]) && $_COOKIE[$cookie_value] == $cookie_value) {
$already_made_post = "Du har redan ett inlägg i gästboken!";
}
else {
$data = "\n" . $_POST['name'] . ',' . $_POST['message'] . ',' . $ip_address . ',' . $time_stamp;
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if ($ret == false) {
die('Fel vid skrivning till fil. Skrivrättigheter saknas');
}
// set cookie
setcookie($cookie_name, $cookie_value); // IS NOT SET
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
}
}
}
}
?>
<link rel="stylesheet" href="labb1.css" type="text/css">
<html>
<head>
<title>Labb 1</title>
</head>
<body>
<h1 class="title">Laboration 1 - Gästboken</h1>
<table border="1">
<thead>
<tr>
<th colspan="3" class="table-title">Min Gästbok</th>
</tr>
</thead>
<tbody>
<tr>
<td class="bold">FRÅN</td>
<td class="bold">INLÄGG</td>
<td class="bold">LOGGNING</td>
</tr>
<?php
// open file
$f = fopen("data.txt", "r");
// while not end of file
while (!feof($f)) {
// split values with -
$arr = explode(",", trim(fgets($f), "\r\n"));
print "<tr>";
print "<td>$arr[0]</td>";
print "<td>$arr[1]</td>";
print "<td>IP: $arr[2]<br>TID: $arr[3]</td>";
print "</tr>";
}
?>
</tbody>
</table>
<form action="" method="post">
<div class="border">
<div>
<span>Namn:</span>
<input type="text" name="name" value="<?php echo $name;?>">
</div>
<div>
<span>Meddelande:</span>
<textarea name="message" rows="5"><?php echo $message;?></textarea>
</div>
<div>
<?php
$rand = substr(str_shuffle(str_repeat("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
session_start();
$_SESSION["rand"] = $rand;
print "<span>CAPTCHA skriv detta i rutan nedan: </span> <span class='red bold'>$rand</span>"
?>
<span class="error">* <?php echo $capt_error; ?></span>
<input type="text" name="capt">
<span class="error"><?php echo $mismatch?></span>
</div>
<div>
<input type="submit" value="Skicka">
</div>
<div>
<span class="red">*</span> är ett obligatoriskt fält
</div>
<div>
<span class="error"><?php echo $already_made_post?></span>
</div>
</div>
</form>
</body>
</html>
session_start(); should be at the top of the page for the sessions to work. In your code above it only gets called when the user submits the form. Move it to line 2.
I read your code and now I see this
setcookie($cookie_name, $cookie_value); // IS NOT SET
if(!isset($_COOKIE[$cookie_name])) {
From common pitfalls
Cookies will not become visible until the next loading of a page that
the cookie should be visible for.
You have not set the expire perameter:
Set your cookies like this
$expire=time()+60*60*24*30;
setcookie ("name","value", $expire,"/");
$expire variable holds the value time when our cookies should expire,

Pass variable from one script to another on same page?

All,
I've been struggling with this and I don't know exactly what I'm doing wrong. I have a PHP file that has multiple scripts in it, including PHP and jquery sections. I'm trying to pass a PHP variable from the html Head section to the Body. Each are each in their own php script section because I have a jquery script in between, also in the Head. Below is the relevant code. How do I pass the $reset_question php variable from the top section to the bottom section?
I just added the button "submit 3" to bring up the form I'm having problems with. Maybe something in my syntax?
<head>
<?php
require_once('../connectvars.php');
session_start();
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Clear the error message
$error_msg = "";
// other code that I'm not having a problem with
if (!isset($_SESSION['email'])) {
if (isset($_POST['submit3'])) {
// Grab the user-entered log-in data
$email = mysqli_real_escape_string($dbc, trim($_POST['email']));
$first_name = mysqli_real_escape_string($dbc, trim($_POST['first_name']));
$last_name = mysqli_real_escape_string($dbc, trim($_POST['last_name']));
if (!empty($first_name) && !empty($last_name) && !empty($email) ) {
// Make sure someone isn't already registered using this username
$query = "SELECT * FROM user_database WHERE email = '$email' AND first_name = '$first_name' AND last_name = '$last_name'";
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) == 1) {
// The username exists
$query = "SELECT reset_question FROM user_database where email='$email'";
mysqli_query($dbc, $query);
// Confirm success with the user
while($row = mysqli_fetch_array($data)) {
$reset_question = $row['reset_question'];
}
exit();
}
else {
// An account doesn't exist for this e-mail
echo '<p class="error">All of your information was not recognized. Please complete the information correctly or sign-up to register.</p>';
$email = "";
}
}
else {
echo '<p class="error">You must enter all of the required data.</p>';
}
$_SESSION['reset_question'] = $reset_question;
}
}
// Insert the page header
require_once('../reference/header_sub.php');
// If the session var is empty, show any error message and the log-in form; otherwise confirm the log-in
if (empty($_SESSION['email'])) {
echo '<p class="error">' . $error_msg . '</p>';
// closing bracket is down below
?>
// other code that I'm not having a problem with
//jquery script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<script>
// jquery isn't having any issues that I can see
</script>
</head>
<body>
<div id="allcontent" style="position:relative;top:-20px;">
<?php
// Insert the tabbed navigation
require_once('../reference/tabs_sub.php');
?>
<br />
<fieldset>
<!-- html forms that I've not having problems with -->
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table class="reset">
<tr><td colspan="2" ><legend style="font-weight:bold;font-size:15px;height:25px;">Reset your password</legend></td></tr>
<tr><td class="register" ><label for="first_name">First Name:</label></td>
<td><input style="width:200px;" type="text" name="first_name" value="<?php if (!empty($first_name)) echo $first_name; ?>" /><br /></td></tr>
<tr><td class="register" ><label for="last_name">Last Name:</label></td>
<td><input style="width:200px;" type="text" name="last_name" value="<?php if (!empty($last_name)) echo $last_name; ?>" /><br /></td></tr>
<tr><td class="register" ><label for="email">E-mail:</label></td>
<td><input style="width:200px;" type="text" name="email" value="<?php if (!empty($email)) echo $email; ?>" /><br /></td><td><input type="submit" value="Submit" name="submit3" class="submit3"/></td></tr>
</table>
</form>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
<table class="answer">
<tr><td colspan="2" class="remember" >Please answer the following question!</td></tr>
<tr><td class="remember" >What is: <?php $_SESSION['reset_question']; ?>?</td></tr>
<tr><td ><input style="width:200px;" type="text" name="reset_answer" value="<?php if (!empty($reset_answer)) echo $reset_answer; ?>"/></td></tr>
</table>
</form>
</fieldset>
<?php
} // closing bracket from above opening bracket
else {
// Confirm the successful log-in
echo('<p class="login">You are logged in as ' . $_SESSION['email'] . '.</p>');
require_once('/download.php');
}
?>
<?php
// Insert the page footer
require_once('../reference/footer.php');
mysqli_close($dbc);
?>
</div>
</body>
it looks like your variable $reset_question only exists in the scope of the while loop
while($row = mysqli_fetch_array($data)) {
$reset_question = $row['reset_question'];
//....
}
Instead initialize the variable outside of the while loop.
$reset_question = '';
while($row = mysqli_fetch_array($data)) {
$reset_question = $row['reset_question'];
//....
}
Declare your variable out of any brackets. Just in php script scope and you will get it anywhere down in file, nothing else is needed to pass (access) it in lower script.
Best place to declare/initialize it is before
$reset_question = 'Defaut Question';
if (!empty($first_name) && !empty($last_name) && !empty($email) )
{
If you do not get anything in $reset_question in your conditions then you will get 'Defaut Question'
Upadte : One more try and i am sure you will get at least "What is Defaut Question?"
write $reset_question = 'Defaut Question'; just after $error_msg = ""; as
$error_msg = "";
$reset_question = 'Defaut Question';

Php Login/registration data stored in txt

I'm trying to make a simple login/reg, but the login doesn't work, only with the last line of my txt file, probably because of the other lines contain the '\n' on the end of every line, but it worked before, I don't know what went wrong... What do I have to do to make it work? Here's my code:
login.php:
<?php
if(isset($_POST["name"]) && isset($_POST["password"])){
$file = fopen('data.txt', 'r');
$good=false;
while(!feof($file)){
$line = fgets($file);
$array = explode(";",$line);
if($array[0]==$_POST["name"] && $array[1]==$_POST["password"]){
$good=true;
break;
}
}
if($good){
$message="Welcome";
}else{
$message="Try again";
}
include 'message.html';
fclose($file);
}else{
include 'login.html';
}
?>
reg.php:
<?php
if(isset($_POST["name"]) && isset($_POST["password"])){
$f=fopen("data.txt","a");
fputs($f,$_POST["name"].";".$_POST["password"]."\r\n");
fclose($f);
}else{
include 'reg.html';
}
?>
And this is how the data.txt looks like:
Viktor;1234
Eve;12345
Cathlin;12356
I created a demo for PHP registration and login, and tested fine.
This is the reg html:
<html>
<head>
<title> Reg Page </title>
</head>
<body>
<form action="" method="post">
<table width="200" border="0">
<tr>
<td> UserName</td>
<td> <input type="text" name="user" > </td>
</tr>
<tr>
<td> PassWord </td>
<td><input type="password" name="pass"></td>
</tr>
<tr>
<td> <input type="submit" name="reg" value="REG"></td>
<td></td>
</tr>
</table>
</form>
</body>
</html>
The registration php as below:
<?php
if(isset($_POST["user"]) && isset($_POST["pass"]))
{
// check if user exist.
$file=fopen("data.txt","r");
$finduser = false;
while(!feof($file))
{
$line = fgets($file);
$array = explode(";",$line);
if(trim($array[0]) == $_POST['user'])
{
$finduser=true;
break;
}
}
fclose($file);
// register user or pop up message
if( $finduser )
{
echo $_POST["user"];
echo ' existed!\r\n';
include 'reg.html';
}
else
{
$file = fopen("data.txt", "a");
fputs($file,$_POST["user"].";".$_POST["pass"]."\r\n");
fclose($file);
echo $_POST["user"];
echo " registered successfully!";
}
}
else
{
include 'reg.html';
}
?>
The login form:
<html>
<head>
<title> Login Page </title>
</head>
<body>
<form action="" method="post">
<table width="200" border="0">
<tr>
<td> UserName</td>
<td> <input type="text" name="user" > </td>
</tr>
<tr>
<td> PassWord </td>
<td><input type="password" name="pass"></td>
</tr>
<tr>
<td> <input type="submit" name="login" value="LOGIN"></td>
<td></td>
</tr>
</table>
</form>
</body>
</html>
The login php:
<?php session_start(); ?> // session starts with the help of this function
<?php
if(isset($_SESSION['use'])) // Checking whether the session is already there or not if
// true then header redirect it to the home page directly
{
header("Location:home.php");
}
else
{
include 'login.html';
}
if(isset($_POST['login'])) // it checks whether the user clicked login button or not
{
$user = $_POST['user'];
$pass = $_POST['pass'];
if(isset($_POST["user"]) && isset($_POST["pass"])){
$file = fopen('data.txt', 'r');
$good=false;
while(!feof($file)){
$line = fgets($file);
$array = explode(";",$line);
if(trim($array[0]) == $_POST['user'] && trim($array[1]) == $_POST['pass']){
$good=true;
break;
}
}
if($good){
$_SESSION['use'] = $user;
echo '<script type="text/javascript"> window.open("home.php","_self");</script>';
}else{
echo "invalid UserName or Password";
}
fclose($file);
}
else{
include 'login.html';
}
}
?>
I put the source code at here for reference.
Use trim() to strip away whitespaces from the beginning and end of the strings.
http://php.net/manual/en/function.trim.php
while(!feof($file)){
$line = fgets($file);
list($user, $pass) = explode(';', $line);
if(trim($user) == $_POST['name'] && trim($pass) == $_POST['password']){
$good=true;
break;
}
}

Form validation using PHP

I want to validate my form so ALL of the fields are required. If a field is NOT inserted or left blank it will display an error message AFTER submission. Could anyone help?
Form
<html>
<head>
<title>Form Input Data</title>
</head>
<table>
<body><table border="1">
<table bgcolor="lightblue"></body>
<form method="post" action="insert_ac.php">
<br>
<tr><td align="left"><strong>Nurse Information</strong></td></tr>
<tr>
<td><font color="red">Please select your name</font></td>
</tr>
<tr>
<td>Fullname</td>
<td><select name="valuelist">;
<option value="valuelist" name="nurse_name" value='<?php echo $nurse_name; ?>'></option>
<?php
$value=$_POST ["valuelist"];
$con = mysql_connect("localhost","root","") or die('Could not connect:'.mysql_error());
mysql_select_db("a&e", $con) or die('Could not select database.');
$fetch_nurse_name = mysql_query("SELECT DISTINCT Fullname FROM nurse");
while($throw_nurse_name = mysql_fetch_array($fetch_nurse_name)) {
echo '<option value=\"'.$throw_nurse_name[0].'">'.$throw_nurse_name[0].'</option>';
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td>Please register name here:</td>
<tr>
<td>Fullname</td>
<td><input type="text" name="nurse_forename" size="30"> </td>
</tr>
</tr>
I would do something like this:
$req = ['field1', 'field2', 'field...'];
$status = true;
foreach ($req as $field) {
if (empty($_POST[$field])) {
echo 'Field ' . $field . ' is empty';
$status = false;
}
}
if ($status) {
// ok
} else {
// not okay!
}
You create an array ($req), with all field names and loop over them. Check every field against empty() (check the php manual for this function).
Here is a better (and mostly) correct HTML snippet... Please indent properly and read any HTML tutorial for well formed code. Your HTML is **.
<?php
$value=$_POST["valuelist"];
$con = mysql_connect("localhost","root","") or die('Could not connect:'.mysql_error());
mysql_select_db("a&e", $con) or die('Could not select database.');
$fetch_nurse_name = mysql_query("SELECT DISTINCT Fullname FROM nurse");
?>
<html>
<head>
<title>Form Input Data</title>
</head>
<body>
<form method="post" action="insert_ac.php">
<table border="1" bgcolor="lightblue">
<tr>
<td align="left"><strong>Nurse Information</strong></td>
</tr>
<tr>
<td><font color="red">Please select your name</font></td>
</tr>
<tr>
<td>Fullname</td>
<td>
<select name="valuelist">
<option value="valuelist" value="<?php echo $nurse_name; ?>"></option>
<?php
while($throw_nurse_name = mysql_fetch_array($fetch_nurse_name)) {
echo '<option value="'.$throw_nurse_name[0].'">'.$throw_nurse_name[0].'</option>';
}
?>
</select>
</td>
</tr>
<tr>
<td>Please register name here:</td>
</tr>
<tr>
<td>Fullname</td>
<td><input type="text" name="nurse_forename" size="30"> </td>
</tr>
</table>
</form>
</body>
</html>
If you have only the two given fields, this would do it:
$status = false;
$name = '';
if (!empty($_POST['nurse_forename'])) {
$name = $_POST['nurse_forename'];
$status = true;
} elseif (!empty($_POST['valuelist'])) {
$name = $_POST['valuelist'];
$status = true;
} else {
$status = false;
// none of nurse_forname OR valuelist is filled
// abort.
}
Something like
foreach($_POST as $form_entry)
if(empty($form_entry))
echo 'you have to fill in all fields';
if (isset($_POST['variable']{0})) {
echo 'I exist and I have at least one char!';
else
echo 'I dont exist or I have no chars!';
It checks whether $_POST['variable'] exists and has at least one char.
if($_POST['valuelist'] == NULL or $_POST['nurse_forename'] == NULL){
die('empty');
}
Untested.
Try it this way:
if(empty($_POST['nurse_forename'])){
echo "Field Nurse-Forename is empty";
}
You also could check like this:
if($_POST['nurse_forename']==""){
echo "Nurse-Forename is empty";
}
You cannot check for all fields with one command (because you cannot distinct between one and more empty fields). You could do it a little more elegant using OOP, but I think for the code you posted above the example should do.
Also You can try this, It's validating all form items.
if (isset ( $_POST ['submit_button_name'] )) {
$validated = true;
array_walk_recursive ( $_POST, function ($value, $key) {
global $validated;
if (! trim ( $value ))
$validated = false;
} );
if ($validated) {
// insert function and redirect
} else {
// print Your message
}
}
// Your form
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?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"]);}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>

Categories