<html>
<body>
<?php
$nameErr=$genderErr=$websiteErr="";
$name=$gender=$comment=$website="";
if($_SERVER["REQUEST_METHOD"]=="POST"){
if(empty($_POST["name"])){
$nameErr="Name is required";}
else{
$name=test_input($_POST["name"]);
if(!preg_match("/^[a-zA-Z-' ]*$/",$name)){
$nameErr="only letters and white space allowed";}}
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;}
?>
<style>.error{color:red;}</style>
<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" value="<?php echo $name;?>">
<span class="error">*<?php echo $nameErr;?></span>
<br><br>
Comment:<textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if(isset($gender)&&$gender=="female")echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if(isset($gender)&&$gender=="male")echo "checked";?> value="male">Male
<input type="radio" name="gender" <?php if(isset($gender)&&$gender=="other")echo "checked";?> value="other">Other
<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 $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
......................
File 1: demo_session1.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
File 2: demo_session2.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
Comments
Post a Comment