Home / PHP/MySQL Tutorials / PHP Forms / Archive by category 'Php Forms Examples'

Php Forms Examples

Passing Complex Values In A Querystring

 
string serialize ( mixed value )
mixed unserialize ( string str ) <html>
<?php
class someclass {
  protected $someval;
  public function setsomeval($newval) {
    $this->someval = $newval;
  }
  public function getsomeval() {
    return $this->someval;
  }
}
$myclass = new someclass ( );
$myclass->setsomeval ( "Hello World!" );
$myarray = array ();
$myarray [0] = "Hello";$myarray = serialize ( $myarray );
$myarray = urlencode ( $myarray );
$myclass = serialize ( $myclass );
$myclass = urlencode ( $myclass );
?>
</head>
<body>
<a
  href="index.html?passedarray=<?php
  echo $myarray;
  ?>. &amp;passedclass=<?php
echo $myclass;
?>">Output Current Value</a>
<?phpif (isset ( $_GET ['passedclass'] ) && isset ( $_GET ['passedarray'] )) {
 
  $newclass = new someclass ( );
  $newclass = $_GET ['passedclass'];
  $newclass = stripslashes ( $newclass );
  $newclass = unserialize ( $newclass );
  echo "Object: " . $newclass->getsomeval () . "<br />";
 
  $newarray = array ();
  $newarray = $_GET ['passedarray'];
  $newarray = stripslashes ( $newarray );
  $newarray = unserialize ( $newarray );
  print_r ( $newarray );}
?>
</div>
</body>
</html>

Passing Numeric Values In A Querystring

 
<html>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
  <div align="center">
    <p>Click a link to change the text color of the verbiage below:</p>
    <a href="index.php?color=1">Green</a><br />
    <a href="index.php?color=2">Red</a><br />
    <a href="index.php?color=3">Blue</a><br />
    <a href="index.php">Reset</a>
    <?php
      if (isset ($_GET['color'])){
        $color = intval ($_GET['color']);
      } else {
        $color = "";
      }
      if ($color == 1){
        $fontcolor = "00FF00";
      } elseif ($color == 2){
        $fontcolor = "FF0000";
      } elseif ($color == 3){
        $fontcolor = "0000FF";
      } else {
        $fontcolor = "000000";
      }
      ?><p style="color: #<?php echo $fontcolor; ?>; font-weight: bold;">Hello World!</p><?php
    ?>
  </div>
</body>
</html>

Properly Checking For Submission Using Image Widgets

 
<input TYPE="image" NAME="submit_one" SRC="b.gif">
<input TYPE="image" NAME="submit_two" SRC="b2.gif">//Properly determining which submission button was clicked in PHP:<?php
     if(isset($_GET['submit_one_x'])) {     } elseif(isset($_GET['submit_two_x'])) {
     } else {     }
?>

Responding To Checkboxes

 
    <html>
<head>
<title>Checkbox Demo</title>
</head>
<body>
<h1>Checkbox Demo</h1><h3>Demonstrates checkboxes</h3>
<form action ="HandleFormCheckBox.php"><ul>
  <li><input type ="checkbox" name ="chkFries" value ="11.00">Fries</li>
  <li><input type ="checkbox" name ="chkSoda"  value ="12.85">Soda</li>
  <li><input type ="checkbox" name ="chkShake" value ="1.30">Shake</li>
  <li><input type ="checkbox" name ="chkKetchup" value =".05">Ketchup</li>
</ul>
<input type ="submit">
</form></body>
</html><!-- HandleFormCheckBox.php
<html>
<head>
<title>Checkbox Demo</title>
</head>
<body>
<h3>Demonstrates reading checkboxes</h3>
<?
print <<<here
chkFries: $chkFries <br />
chkSoda: $chkSoda <br />
chkShake: $chkShake <br />
chkKetchup: $chkKetchup <br />
<hr />HERE;$total = 0;if (!empty($chkFries)){
  print ("You chose Fries <br />");
  $total = $total + $chkFries;
}if (!empty($chkSoda)){
  print ("You chose Soda <br />");
  $total = $total + $chkSoda;
}if (!empty($chkShake)){
  print ("You chose Shake <br />");
  $total = $total + $chkShake;
}if (!empty($chkKetchup)){
  print ("You chose Ketchup <br />");
  $total = $total + $chkKetchup;
}print "The total cost is \$$total";?>
</body>
</html>
-->

Saying “Hello”

 
<?
if (array_key_exists('my_name',$_POST)) {
    print "Hello, ". $_POST['my_name'];
} else {
    print<<<_HTML_
<form method="post" action="$_SERVER[PHP_SELF]">
 Your name: <input type="text" name="my_name">
<br/>
<input type="submit" value="Say Hello">
</form>
_HTML_;
}
?>

Send Email With Cc And Bcc

 
     <html>
  <head>
  <title>Send email with CC and BCC</title>
  </head>
  <body>
  <form action="sendemailWithCC_BCC.php" method=post name=form1>
  <table>
    <tbody>
    <tr>
      <td>
       <div align=right><b>To</b></div></td>
      <td>
        <p>Name <input name=mailtoname size=35><br />E-mail
                <input name=mailtomail size=35></p></td></tr>
    <tr>
      <td>
        <div align=right><b>CC</b></div></td>
      <td><input name=mailcc size=35> </td></tr>
    <tr>
      <td>
        <div align=right><b>BCC</b></div></td>
      <td><input name=mailbcc size=35> </td></tr>
    <tr>
      <td>
        <div align=right><b>Priority</b></div></td>
      <td><select name=mailpriority>
            <option value=1>Highest</option>
            <option value=2>High</option>
            <option selected value=3>Normal</option>
            <option value=4>Low</option>
            <option value=5>Lowest</option>
          </select>
      </td></tr>
    <tr>
      <td><div align=right><b>Subject</b></div></td>
      <td><input name=mailsubject size=35></td></tr>
    <tr>
      <td>
        <div align=right><b>Message</b> </div></td>
      <td><textarea cols=50 name=mailbody rows=7></textarea> </td></tr>
    <tr>
      <td colSpan=2>
        <div align=center><input name=Submit type=submit value=Submit></div>
    </td>
    </tr>
   </tbody>
   </table>
  </form>
  </body>
  </html>
 
 
 
 
<!-- sendemailWithCC_BCC.php  <html>
  <head>
  <title>Mail Sent</title>
  </head>
  <body>
  <?php
 
    $message= " " ;
    if (empty ( $mailtoname) || empty ( $mailtomail) ) {
       die ( "Recipient is blank! ") ;
    }else{
       $to = $mailtoname . " <" . $mailtomail . ">" ;
    }
 
    if ( empty ( $mailsubject) ) {
      $mailsubject=" ";
    }    if (($mailpriority>0) && ($mailpriority<6)) {
       $mailheader = "X-Priority: ". $mailpriority ."\n";
    }    $mailheader.= "From: " . "Sales Team <sales@yourdomain.com>\n";
    $mailheader.= "X-Sender: " . "support@yourdomain.com\n";
    $mailheader.= "Return-Path: " . "support@yourdomain.com\n";    if (!empty($mailcc)) {
      $mailheader.= "Cc: " . $mailcc ."\n";
    }    if (!empty($mailbcc)) {
      $mailheader.= "Bcc: " . $mailbcc ."\n";
    }
 
    if (empty($mailbody)) {
      $mailbody=" ";
    }
 
    $result = mail ($to, $mailsubject, $mailbody, $mailheader);
    echo "<center><b>Mail sent to ". "$to". "<br />";
    echo $mailsubject. "<br />";
    echo $mailbody. "<br />";
    echo $mailheader. "<br />";
    if ($result) {
       echo "<p><b>Email sent successfully!</b></p>";
    }else{
       echo "<p><b>Email could not be sent. </b></p>";
    }
  ?>
  <div align="center">
  <table><tr><td width="66"><div align="right"><b>To</b></div></td>
             <td width="308"><b><?php echo $mailtoname . " [". $mailtomail . " ]";?></b></td></tr>
 
         <tr><td width="66"><div align="right"><b>CC</b></div></td>
             <td width="308"><b><?php echo $mailcc;?></b></td></tr>
         <tr><td width="66"><div align="right"><b>BCC</b></div></td>
             <td width="308"><b><?php echo $mailbcc; ?></b></td></tr>
         <tr><td width="66"><div align="right"><b>Priority</b></div></td>
             <td width="308"><b><?php echo $mailpriority;?></b></td></tr>
         <tr><td width="66"><div align="right"><b>Subject </b></div></td>
             <td width="308"><b><?php echo $mailsubject;?></b></td></tr>
         <tr><td width="66"><div align="right"><b>Message</b></div></td>
             <td width="308"><b><?php echo $mailbody;?></b></td></tr>
  </table>
  </div>
  </body>
  </html>
-->

Set Cookie Data

 
<?php
  $user =  $_POST['user'];
  $color = $_POST['color'];
  $self =  $_SERVER['PHP_SELF'];  if( ( $user != null ) and ( $color != null ) )
  {
    setcookie( "firstname", $user , time() + 36000 );
    setcookie( "fontcolor", $color, time() + 36000 );
    header( "Location:getcookie.php" );
    exit();
  }
?><html> <head>
  <title>Set Cookie Data</title>
 </head> <body>  <form action ="<?php echo( $self ); ?>" method = "post">  Please enter your first name:
  <input type = "text" name = "user"><br /><br />  Please choose your favorite font color:<br />
  <input type = "radio" name = "color" value = "#FF0000">Red
  <input type = "radio" name = "color" value = "#00FF00">Green
  <input type = "radio" name = "color" value = "#0000FF">Blue
  <br /><br />
  <input type = "submit" value = "submit">
  </form> </body></html>

Simple File Upload Form

 
<html>
<head>
<title>A Simple File Upload Form</title>
</head>
<body>
<form enctype="multipart/form-data"
   action="<?print $_SERVER['PHP_SELF']?>" method="post">
<p>
<input type="hidden" name="MAX_FILE_SIZE" value="102400" />
<input type="file" name="fupload" /><br/>
<input type="submit" value="upload!" />
</p>
</form>
</body>
</html>

Time-Sensitive Form Example

 
<?
<form ACTION="index.php" METHOD=GET>
<input TYPE="hidden" NAME="time" VALUE="<?php echo time(); ?>">
Enter your message (5 minute time limit):<input TYPE="text" NAME="mytext" VALUE="">
<input TYPE="submit" Value="Send Data">
</form>if($_GET['time']+300 >= time()) {
     echo "You took too long!<br />";
     exit;
}
?>

Uploading A File

 
<?php if ($_SERVER['REQUEST_METHOD'] == 'GET') { ?>
<form method="post" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>"
      enctype="multipart/form-data">
<input type="file" name="document"/>
<input type="submit" value="Send File"/>
</form>
<?php } else {
    if (isset($_FILES['document']) &&
    ($_FILES['document']['error'] == UPLOAD_ERR_OK)) {
        $newPath = '/tmp/' . basename($_FILES['document']['name']);
        if (move_uploaded_file($_FILES['document']['tmp_name'], $newPath)) {
            print "File saved in $newPath";
        } else {
            print "Couldn't move file to $newPath";
        }
    } else {
        print "No valid file uploaded.";
    }
}
?>

Using Arrays With Form Data In Php

 
<select NAME="myselect[]" MULTIPLE SIZE=3>
<option VALUE="value1">A</option>
<option VALUE="value2">B</option>
<option VALUE="value3">C</option>
<option VALUE="value4">D</option>
</select>//The PHP code to access which value(s) were selected:<?php
     foreach($_GET['myselect'] as $val) {
          echo "You selected: $val<br />";
     }
     echo "You selected ".count($_GET['myselect'])." Values.";
?>

Validating Form Data

 
<?
if ($_POST['_submit_check']) {
    if (validate_form()) {
        process_form();
    } else {
        show_form();
    }
} else {
    show_form();
}function process_form() {
    print "Hello, ". $_POST['my_name'];
}function show_form() {
    print<<<_HTML_
<form method="POST" action="$_SERVER[PHP_SELF]">
Your name: <input type="text" name="my_name">
<br/>
<input type="submit" value="Say Hello">
<input type="hidden" name="_submit_check" value="1">
</form>
_HTML_;
}function validate_form() {
    if (strlen($_POST['my_name']) < 3) {
        return false;
    } else {
        return true;
    }
}
?>

Accessing Multiple Submitted Values

 
<form method="POST" action="index.php">
<select name="lunch[]" multiple>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<option value="d">D</option>
<option value="e">E</option>
</select>
<input type="submit" name="submit">
</form>
Selected buns:
<br/>
<?php
foreach ($_POST['lunch'] as $choice) {
    print "You want a $choice bun. <br/>";
}
?>

Access Widget’s Form Value

 
<input TYPE="text" NAME="myform.email">would be accessed in PHP as the following:<?php
    echo $_GET['myform_email'];
?>

A Form With Checkboxes Using The Same Name To Store Multiple Values

 
<html>
<head>
    <title>Using Default Checkbox Values</title>
</head>
<body>
<?php
$food = $_GET["food"];
if (!empty($food)){
    echo "The foods selected are: <strong>";
    foreach($food as $foodstuff){
        echo '<br />'.htmlentities($foodstuff);
    }
    echo "</strong>.";
}
else {
    echo ('
    <form action="'. htmlentities($_SERVER["PHP_SELF"]).'" method="GET">
        <fieldset>
            <label>
                Italian
                <input type="checkbox" name="food[]" value="Italian" />
            </label>
            <label>
                Mexican
                <input type="checkbox" name="food[]" value="Mexican" />
            </label>
            <label>
                Chinese
                <input type="checkbox" name="food[]" value="Chinese" checked="checked" />
            </label>
        </fieldset>
        <input type="submit" value="Go!" />
    </form> ');
    }
?>
</body>
</html>

An Html Form That Calls Itself

 
<html>
<head>
<title>An HTML Form that Calls Itself</title>
</head>
<body>
<div>
<?php
if ( ! empty( $_POST['guess'] ) ) {
    print "last guess: ".$_POST['guess'];
}
?>
<form method="post" action="<?php print $_SERVER['PHP_SELF']?>">
<p>
Type your guess here: <input type="text" name="guess" />
</p>
</form>
</div>
</body>
</html>

A Php Number-Guessing Script

 
<?php
$num_to_guess = 42;
$message = "";
if ( ! isset( $_POST['guess'] ) ) {
   $message = "Welcome!";
} else if ( $_POST['guess'] > $num_to_guess ) {
   $message = $_POST['guess']." is too big!";
} else if ( $_POST['guess'] < $num_to_guess ) {
   $message = $_POST['guess']." is too small!";
} else {
   $message = "Well done!";
}
?>
<html>
<head>
<title>A PHP Number Guessing Script</title>
</head>
<body>
<h1>
<?php print $message ?>
</h1>
<form method="post" action="<?php print $_SERVER['PHP_SELF']?>">
<p>
Type your guess here: <input type="text" name="guess" />
<input type="submit" value="submit" />
</p>
</form>
</body>
</html>

A Sample Form Element Validation Function

 
<?php
    function phone_validate($data, $desc) {
        $regex = "/^\([2-9][0-9]{2}\)[2-9][0-9]{2}-[0-9]{4}/i";
        if(preg_match($regex, $data) != 1) {
            return "The '$desc' field isn't valid!";
        }
        return true;
    }
?>

A Simple Html Form

 
    <html>
<head>
<title>A simple HTML form</title>
</head>
<body>
<form action="formDataRead.php" method="GET">
  <input type="text" name="user">
  <br />
  <textarea name="address" rows="5" cols="40">
  </textarea>
  <br />
  <input type="submit" value="hit it!">
</form>
</body>
</html><!--  formDataRead.php
<html>
<head>
<title>Reading input from the form</title>
</head>
<body>
<?php
print "Welcome <b>$user</b><p>\n\n";
print "Your address is:<p>\n\n<b>$address</b>";
?>
</body>
</html>-->

Build Query String Based On Form Input

 
    <?php
if (isset($_POST['submit'])) {
      $rowID = $_POST['id'];
      mysql_connect("mysql153.secureserver.net","w3mentor","password");
      mysql_select_db("w3mentor");
 
      $query = "SELECT * FROM Employee WHERE ID='$id'";
      $result = mysql_query($query);
      list($name,$productid,$price,$description) = mysql_fetch_row($result);
}?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
   <select name="id">
      <option name="">Choose a employee:</option>
      <option name="1">1</option>
      <option name="2">2</option>
      <option name="3">3</option>
   </select>
   <input type="submit" name="submit" value="Submit" />
</form>