PHP Forms – Part3

php forms

This is the part 3 of the PHP form. If you didn’t read the previous lessons, please read the previous ones-

1. PHP Forms Part1
2. PHP Forms Part2

Processing form with multi-valued elements

Sometimes, user can select or choose more than one value for a single form element, for example, multi-select boxes or checkboxes. You know, for a single-valued element, such as textbox, the name of the element contains the value. If you use the same name for the multi-valued element(s), the value of the last selected element will be saved. To collect multiple values of a single element, you can declare the element name as array. Check the following example

Example:

<form name="form1" method="POST" action="form-process7.php">
    <p>
        <label>Which skill(s) you have?</label><br />
        <select name="Skill[]" size="7" multiple="multiple" id="select">
          <option value="HTML">HTML</option>
          <option value="CSS">CSS</option>
          <option value="JavaScript">JavaScript</option>
          <option value="jQuery">jQuery</option>
          <option value="PHP">PHP</option>
          <option value="MySQL">MySQL</option>
        </select>
    </p>
    <p>
        <input name="send" id="send" type="submit" value="Submit">
    </p>
</form>

multi-valued elements in php

And, here is the form processing script (form-process7.php)

<?php
    // First check whether the form has been submitted
    if(isset($_POST['send'])){
        if(isset($_POST['Skill'])){
            echo "You know ";
            foreach ( $_POST['Skill'] as $value ){
                echo $value . " ";
            }
        }
    }else{
        echo "Unauthorized access to this page.";
    }
?>

Form input:
Let’s run the form and select PHP and MySQL and submit the form.

Output:
You know PHP and MySQL

Explanation:
User may or may not select any skill. So, in line 4 in the form-process7.php script, we first check whether any skill has been selected. If selected, then the codes inside line 5 to 8 will be executed. As we can’t determine how many skill(s) a user selects, so, we use foreach loop to run as many times as the array element has.

Using hidden fields

As the names says hidden form field is not visible in the form, but, like the other form element it has a name and its value. You need to define type as hidden to mention the field as hidden. For many reason, you may use hidden form fields to pass a value.

Example:

<form name="form1" method="POST" action="form-process8.php">
    <p>
        <label>Your Comment : </label><br />
        <textarea name="Comment" id="Comment" cols="45" rows="5"></textarea>
    </p>
    <p>
        <input name="Serial" type="hidden" value="12">
        <input name="send" id="send" type="submit" value="Submit">
    </p>
</form>

And, here is the form processing script (form-process8.php)

<?php
    // First check whether the form has been submitted
    if(isset($_POST['send'])){
        $Comment=htmlspecialchars($_POST['Comment']);
        $Serial=$_POST['Serial'];
        echo "User Serial = " . $Serial;
    }else{
        echo "Unauthorized access to this page.";
    }
?>

Form input:
Enter anything in the form and press enter

Output:
User Serial 12

Explanation:
In the form script(form8.php), a hidden field named “Serial” which has a value of 12 is included in line 7. In the form processing script (form-process8.php), we just print the name of the hidden field and it displays its value in line 6.

Uploading the file

Sometimes you want users upload files (image, txt, etc.) by the form. To upload files you have to change/add few things in both HTML script and in php script.

  1. Changes in the HTML script:
    • Enctype attribute: Add the enctype attribute of the <form> tag as “multipart/form-data”, like the following-
      <form enctype=”multipart/form-data”>
    • Method attribute: Change the method attribute of the <form> tag to POST, like the following-
      <form method=”POST”>
    • Input type: To upload a file, add an input tag with file type, like following-
      <input type=”file” name=”upload”>
  2. Changes in the PHP script: After a file is uploaded, it is stored in the temporary location in the server which is defined in the php.ini file. You can find the path of your server’s temporary location searching with the upload_tmp_dir string in the php.ini file. From this temporary location the file is moved to the new location. The following changes are to be made.
  • is_uploaded_file: This function is used to test whether the file was uploaded successfully to the temporary location of the server.
  • $_FILE array: After uploading a file, the information about it can be accessed by PHP’s superglobal array $_FILE. $_FILE array provides five things about each uploaded file. You can use these to check whether the uploaded file has right characteristics.
    • $_FILE[‘filename’][‘name’]: The original name of the file on the client machine
    • $_FILE[‘filename’][‘type’]: The type of the file. Ex, image/jpeg
    • $_FILE[‘filename’][‘size’]: The size of the uploaded file in bytes.
    • $_FILE[‘filename’][‘tmp_name’]: The name with path of the temporary file that PHP gives to the uploaded file.
    • $_FILE[‘filename’][‘error’]: The error code resulting from the uploaded file.
  • move_uploaded_file(): You need to decide where to move the temporary file and what to name it. move_uploaded_file() function helps to accomplish the both tasks. It has two parameters. First one defines the new name of the file and the second one set the destination of the file.

Example:

<style type="text/css">
    span {
        font-size: 9px;
    }
 </style>

<form  name="form1" method="POST" action="form-process9.php" enctype="multipart/form-data">
    <p>
        <label><strong>Upload your photo : </strong></label>
        <br />
        <span><strong>Max file size:</strong> 100kb.<br />
        <strong>File type:</strong> GIF, JPEG, PNG<br /></span>
        <input type="file" name="Photo" id="fileField" />
    </p>
    <p>
        <input name="Serial" type="hidden" value="12">
        <input name="send" id="send" type="submit" value="Submit">
    </p>
</form>

And, here is the form processing script (form-process8.php)

<?php
    // First check whether the form has been submitted
    if(isset($_POST['send'])){
        $Success = 1;
        //Check whether the file is successfully uploaded
        if (is_uploaded_file($_FILES['Photo']['tmp_name'])) {
            if($_FILES['Photo']['size'] > 102400){
                echo "File size more than 100kb is not allowed.<br />";
                $Success = 0;
            }
            if( ($_FILES['Photo']['type'] != "image/jpeg") &&
                ($_FILES['Photo']['type'] != "image/gif") &&
                ($_FILES['Photo']['type'] != "image/png")
              ){
                echo "Only jpeg/gif/png files are allowed.<br />";
                $Success = 0;
            }
            // Check if the file fullfil all the criteria.
            if($Success == 1){
                // Upload the file to /img directory in the current folder
                move_uploaded_file($_FILES['Photo']['tmp_name'], "./img/".$_FILES['Photo']['name']);
                echo "File uploaded successfully.";
            }
        }else{
            echo "file is not uploaded.";
        }
    }else{
         echo "Unauthorized access to this page.";
    }
 ?>

Sticky form

You might have come to a form that required you to fill lots of fields. If you make any mistake filling up the form & submit it, you’re brought to the same form with the values you entered in the correct fields. This is sticky form. Sticky form remembers the values you entered in the input fields. Another example of sticky form is Google search box.

Notes

Sticky form helps user to type the same form again supplying the values in the inputs.

To make a sticky form is very easy.

Example:

<form name="form1" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <p>
      <label> Your Name (required) : </label><br />
        <input name="Name" type="text" id="Name" value="<?php if(isset($_POST['Name'])){ echo $_POST['Name']; }?>">
    </p>
    <p>
<label> Your Message (required) : </label>
     <br />
     <label for="Message"></label>
     <textarea name="Message" id="Message" cols="45" rows="5"><?php if(isset($_POST['Message'])){ echo $_POST['Message']; }?></textarea>
    </p>
    <p>
        <input name="send" id="send" type="submit" value="Submit">
    </p>
 </form>

Explanation:

After submitting the form, the same page will be displayed (<?php echo $_SERVER['PHP_SELF']; ?> in action attribute will take the form in the same page). Both Name and Message fields are required. If you mistakenly don’t fill one field and click submit button, you’ll see the value in the field that you’ve entered and empty the other one. In line 4, if the Name field is not empty, that means the form has been submitted, the value is printed. Same is done in line 10 for Message field.

‹‹ PHP Forms – Part2 : Previous Lesson


Pin It

↑ Back to Top