Working with forms in PHP

Transcription

1 Synopsis In this tutorial, you will learn how to use forms with PHP. Page 1

2 Forms and PHP One of the most popular ways to make a web site interactive is the use of forms. With forms you can have users register for different things, submit any information you can imagine, upload files, and all types of other things. In this tutorial, we will go through the basics of forms and how to handle the data that comes from those forms with PHP. For the scope of this tutorial, I will assume that you have a basic knowledge of HTML and PHP. Though, you can probably get by without a great understanding of either. I will cover several different form elements, including textboxes, checkboxes, select (or drop-down) boxes, radio buttons, and textareas. In this tutorial, I am going to show you how to access the information that has been entered into a form. It is up to you to decide what you want to do with it. You can put that information into a database, a flat file, it off, or countless other things. All I will be showing you is how to get to that data. Ok, enough of that. Let's get to it! A simple form OK, let's start off with a very basic form. Just a single button. <HTML> <HEAD> <TITLE>A simple form</title> </HEAD> <BODY> <FORM method="post" action="form.php"> <INPUT type="submit" name="mybutton" value="click me!"> </FORM> </BODY> </HTML> OK, put that into a file and call it whatever you want. I will be calling it form.html. That will give you a very basic form with one button on it. You can see the "action" of the form is "form.php". That means that whatever data the form contains will be sent to the script form.php. The next step is to create the script form.php. <HTML> <HEAD> <TITLE>Doing something with the form</title> </HEAD> <BODY> <? if(isset($_post['mybutton'])) { echo "Great! You clicked the button!\n"; } else { Page 2

3 echo "Hmm...you must have come to this script without clicking the button.\n"; }?> </BODY> </HTML> Save that code as form.php in the same directory as form.html. Now when you bring up form.html and click the button, you should get a message saying "Great! You clicked the button!". Let's examine the code in form.php a little bit. We are going to be using this code for the basis of everything else in this tutorial. The first few lines are self explanatory. They are just the HTML needed for a proper HTML page. The first code is: if(isset($_post['mybutton'])) { What that is doing is checking to see if the variable $_POST['mybutton'] has been assigned a value or not. If it has, the "if statement" evaluates as true and then the line: echo "Great! You clicked the button!\n"; is executed. If the "if statement" evaluates as false then the "else" portion of that statement is executed: echo "Hmm...you must have come to this script without clicking the button.\n"; So what is this $_POST stuff? $_POST is a superglobal array. This array is available to a script at anytime no matter what the scope. If you aren't sure what scope is, don't worry about it right now. Just realize that you can use $_POST anywhere in your script. Anything submitted via the POST method is available in the $_POST array. You may have noticed that the index of the $_POST array is the name we gave to the HTML form element. Whatever you call your form element (a form element being a button, textbox, checkbox, etc), that is what the index of the $_POST array will be in order to access the data from that element. The $_POST array is only available in PHP versions and later. If you are using an earlier version, you will need to use the $HTTP_POST_VARS array. The $HTTP_POST_VARS array works the same as the $_POST array, except it is not a superglobal. That is, it is not available in all scopes. In fact, if register_globals is turned off in your php.ini you will need to put "global $HTTP_POST_VARS;" at the top of the form.php script for it to work. Page 3

4 Text Boxes Now, we will add another element to our form - a textbox. In form.html, after the line: <FORM method="post" action="form.php"> add the line: Fill in the text box: <INPUT type="text" name="mytextbox" size="20"><br> This will add a text box called "mytextbox" that is 20 characters long to our simple form. Now, let's do something with the data that is entered in the textbox in out form.php script. After this line in form.php: echo "Great! You clicked the button!\n"; add this line: echo "<BR>You typed <b>". $_POST['mytextbox']. "</b> in the textbox.\n"; Now, go ahead and try it out again. As you can see, we have passed the data in the textbox from the first page to the next. It really is that simple. This is basically how it is going to work for each of the other form elements. There are a few subtle differences, but we will go through those. Checkboxes Now let's take a look at checkboxes. First a very simple checkbox situation - just a single checkbox. In form.html, after the line: Fill in the text box: <INPUT type="text" name="mytextbox" size="20"><br> add this line: Check me or not: <INPUT type="checkbox" name="mycheckbox" value="1"><br> In form.php after the line: Page 4

5 echo "<BR>You typed <b>". $_POST['mytextbox']. "</b> in the textbox.\n"; add the lines: if(isset($_post['mycheckbox'])) { echo "<BR>You checked the checkbox.\n"; } else { echo "<BR>You didn't check the checkbox.\n"; } Ok, that was a very simple checkbox example, let's do something with multiple checkboxes. In form.html, change the line: Check me or not: <INPUT type="checkbox" name="mycheckbox" value="1"><br> to read: Check me or not: <INPUT type="checkbox" name="mycheckbox[]" value="1"><br> Notice we have added opening and closing brackets [] to the name of the checkbox. This will create an array for our checkbox values. Now, let's add a couple more checkboxes. After the current checkbox line in form.html, add these lines: Check me or not: <INPUT type="checkbox" name="mycheckbox[]" value="2"><br> Check me or not: <INPUT type="checkbox" name="mycheckbox[]" value="3"><br> In form.php we will now need to determine which checkboxes have been checked. Luckily for us, PHP gives us an easy way to loop through all the values in an array - a foreach loop. Continuing along in our form.php script, add these lines after the last ones we added: foreach($_post['mycheckbox'] as $value) { echo "<BR>You clicked checkbox number ". $value, "\n"; } If you type asdasd in the textbox and check checkboxes number 1 and 3, your output should look like: Page 5

6 Great! You clicked the button! You typed asdasd in the textbox. You checked the checkbox. You clicked checkbox number 1 You clicked checkbox number 3 In form.html, you could very easily change the values of the checkboxes to anything you like. If you changed the value of checkbox 3 to dog, your output would look like: Great! You clicked the button! You typed asdasd in the textbox. You checked the checkbox. You clicked checkbox number 1 You clicked checkbox number dog That really doesn't make sense, but it shows you how the data is stored. The value that we are printing out isn't necessarily a numeric value. It is whatever value we assign that checkbox. Radio Buttons Radio buttons are very similar to checkboxes. The only real difference is that when you call radio buttons by the same name, only one of them can be selected. That really makes our life easier, as we don't have to loop through and figure out which ones are selected. Add this next to form.html: Choose one: Blue <INPUT type="radio" name="myradio" value="blue" CHECKED> Green <INPUT type="radio" name="myradio" value="green"> Yellow <INPUT type="radio" name="myradio" value="yellow"><br> And to form.php: echo "<BR>The color you picked was ". $_POST['myradio']. "\n"; Very straightforward, just like the others. Page 6

Practice Problems: These problems are intended to clarify some of the basic concepts related to access to some of the form controls. In the process you should enter the problems in the computer and run

How to Make a Working Contact Form for your Website in Dreamweaver CS3 Killer Contact Forms Dreamweaver Spot With this E-Book you will be armed with everything you need to get a Contact Form up and running

Web Design 1A First Website Intro to Basic HTML So we're set? Have your text-editor ready. Be sure you use NotePad, NOT Word or even WordPad. Great, let's get going. Ok, let's just go through the steps

Web Programming with PHP 5 The right tool for the right job. PHP as an Acronym PHP PHP: Hypertext Preprocessor This is called a Recursive Acronym GNU? GNU s Not Unix! CYGNUS? CYGNUS is Your GNU Support

PHP Tutorial From beginner to master PHP is a powerful tool for making dynamic and interactive Web pages. PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.

IT 3203 Introduction to Web Development Tables and Forms September 3 HTML Tables Tables are your friend: Data in rows and columns Positioning of information (But you should use style sheets for this) Slicing

1 About Forms For a website to be successful, it is important to be able to get feedback from visitors to your site. This could be a request for information, general comments on your site or even a product

HTML Forms Pat Morin COMP 2405 HTML Forms An HTML form is a section of a document containing normal content plus some controls Checkboxes, radio buttons, menus, text fields, etc Every form in a document

Columbia Weather Systems Weather MicroServer Tutorial How to Displaying your weather station s data on the Internet is a great way to disseminate it whether for general public information or to make it

Computer Programming In QBasic Name: Class ID. Computer# Introduction You've probably used computers to play games, and to write reports for school. It's a lot more fun to create your own games to play

Understanding Cross Site Scripting Hardik Shah Understanding cross site scripting attacks Introduction: there are many techniques which a intruder can use to compromise the webapplications. one such techniques

Web Design and Development ACS-1809 Chapter 13 Using Forms 11/30/2015 1 Chapter 13: Employing Forms Understand the concept and uses of forms in web pages Create a basic form Validate the form content 11/30/2015

Your First Web Page It all starts with an idea Every web page begins with an idea to communicate with an audience. For now, you will start with just a text file that will tell people a little about you,

Dreamweaver Tutorials This tutorial will explain how to create an online contact form. There are two pages involved: the form and the confirmation page. When a user presses the submit button on the form,

Real 1 We have seen only how SQL is used at the generic query interface an environment where we sit at a terminal and ask queries of a database. Reality is almost always different: conventional programs

CST 250 MySQL Notes (Source: www.w3schools.com) MySQL is the most popular open-source database system. What is MySQL? MySQL is a database. The data in MySQL is stored in database objects called tables.

Part II of The Pattern to Good ILE with RPG IV Presented by Scott Klement http://www.scottklement.com 2008, Scott Klement There are 10 types of people in the world. Those who understand binary, and those

FORM-ORIENTED DATA ENTRY Using form to inquire and collect information from users has been a common practice in modern web page design. Many Web sites used form-oriented input to request customers opinions

Implementing Specialized Data Capture Applications with InVision Development Tools (Part 2) [This is the second of a series of white papers on implementing applications with special requirements for data

Chapter 1 1.1 What Is PHP? This presentation is to answer the question, what is PHP? PHP is one of the most popular scripting languages that are used for web development. The cool thing about PHP is it's

Form and function The simplest and really the only method to get information from a visitor to a Web site is via an HTML form. Form tags appeared early in the HTML spec, and closely mirror or exactly duplicate

A send-a-friend application with ASP Smart Mailer Every site likes more visitors. One of the ways that big sites do this is using a simple form that allows people to send their friends a quick email about

HTML Forms and CONTROLS Web forms also called Fill-out Forms, let a user return information to a web server for some action. The processing of incoming data is handled by a script or program written in

WWLash02 6/14/02 3:20 PM Page 18 CHAPTER TWO USING VARIABLES Now that we have discussed some PHP background information and learned how to create and publish basic PHP scripts, let s explore how to use

Using the ISCR FTP Program (RMCDS Configuration) This document was last modified August 29, 2011 This document explains how to make a backup of cases in RMCDS (Rocky Mountain Cancer Data Systems) and send

The PHP 5.4 Features You Will Actually Use About Me Lorna Jane Mitchell PHP Consultant/Developer Author of PHP Master Twitter: @lornajane Website: http://lornajane.net 2 About PHP 5.4 New features Traits

Tutorial: Creating a form that emails the results to you. 1. Create a new page in your web site Using the Wizard Interface. a) Choose I want to add a form that emails the results to me in the wizard. b)

FORMS IN HTML A form is the usual way information is gotten from a browser to a server HTML has tags to create a collection of objects that implement this information gathering The objects are called widgets

Motivation When interacting with the user, we need to ensure that the data entered is valid. If an erroneous data is entered in the form, this should be detected and the form should be redisplayed to the

FEATURE FileMaker for PHP Developers FileMaker is a popular and powerful desktop database application toolkit. Recently, FileMaker, Inc. released a beta version of the FileMaker API for PHP, which allows

Instructions for Embedding a Kudos Display within Your Website You may use either of two technologies for this embedment. A. You may directly insert the underlying PHP code; or B. You may insert some JavaScript

User Testing for Pre-Phase 2, Search 360 Janifer Holt and Barbara DeFelice Charge To test the usability of the search box display format (including, terminology where to add help ) and the subject categories

Tutorial: Using PHP, SOAP and WSDL Technology to access a public web service. ** Created by Snehal Monteiro for CIS 764 ** In this small tutorial we will access the Kansas Department of Revenue's web service

How to build Dashboard - Step by Step tutorial/recipe Contents How to build Dashboard - Step by Step tutorial/recipe...1 How to create Excel Dashboard [ as direct connection ]...2 Purpose of this Dashboard

How to Create a Simple WordPress Store Online for Free The Internet is one of the most fertile grounds on which you can build a business to sell your products or services. This is because of the fact that

Paper 5-26 The Basics of Dynamic SAS/IntrNet Applications Roderick A. Rose, Jordan Institute for Families, School of Social Work, UNC-Chapel Hill ABSTRACT The purpose of this tutorial is to introduce SAS

Citrix Single Sign-On Self-Service Password Reset Citrix Single Sign-On (SSO) Self-Service tools enable you to take control when you forget your password. Using the three security questions you established

Radio Toolbox And Player Embedding In this tutorial we are going to explain how to use our radio toolbox and the embeddable radio player for your web site. Registration Before we can start using the toolbox

QaTraq Pro Scripts Professional Test Scripts Module for QaTraq QaTraq Professional Modules QaTraq Professional Modules are a range of plug in modules designed to give you even more visibility and control

Killer Keyword Strategies - Day 1 "A Guaranteed Way To Find A Starving Crowd Using The Power Of Keyword Research..." The single biggest mistake many people make when starting a business is they'll create

First Bytes Programming Lab 2 This lab is available online at www.cs.utexas.edu/users/scottm/firstbytes. Introduction: In this lab you will investigate the properties of colors and how they are displayed

WEEK THREE Python Lists and Loops You ve made it to Week 3, well done! Most programs need to keep track of a list (or collection) of things (e.g. names) at one time or another, and this week we ll show

CEFNS Web Hosting a Guide for CS212 INTRODUCTION: TOOLS: In CS212, you will be learning the basics of web development. Therefore, you want to keep your tools to a minimum so that you understand how things

Website Planning Checklist The following checklist will help clarify your needs and goals when creating a website you ll be surprised at how many decisions must be made before any production begins! Even

The basics of HTML forms How form content is submitted GET, POST Elements that you can have in forms Responding to forms Common Gateway Interface (CGI) Later: Servlets Generation of dynamic Web content

Template Creation Tutorial Overview: The Files Template Control File: The Template Control File (.tcf) will generate a form of text your user will want inserted directly into the new page, such as title

Creating Forms Creating an email form within the dotcms platform, all the HTML for the form must be in the Body field of a Content Structure. All names are case sensitive. In order for the form to process