This script uses an HTML form to send your name to a PHP script. The PHP script then takes your name and dynamically writes a “hello” message, and also prints a hyperlink so that you can click back to the HTML form. Although very simple this demonstrates a core value of PHP where you can take information from a user, and then code a response based on it.
This project requires 2 files. The form.html is a form for taking information from the user, when the user clicks “submit” the value is sent to the parse.php script which then writes out a response.
Line 1 – A title for this app. In this example we didn’t use HTML formatting, but the title could be within <h> tags, or modified with CSS. A <br> tag is used so that the form is printed on to a line below the title.
Line 3 – Opens the form with the <form> tag. With action= wedesignate what PHP script we should send the variable value to. Method= states how we send the variable value, and generally this will be with POST.
Line 4 – We write a prompt for the user “Your name?”, and then create a text box. For a text box type= should be set to text. Next you name the text value so that the PHP script will be able to identify it so we call it “first_name”.
Line 5 – We add an input of “submit”. This creates a submit button that will send the variables to the PHP script that was designated on the 3rd line at action= , and then sends it as a POST per method=.
Line 6 – We close the whole form
This is a form <br> <form action="parse.php" method="post"> Your name? <input type ="text" name = "first_name"> <input type ="submit"> </form>Code language: HTML, XML (xml)
Line 1 – We open the PHP script
Line 3 – We create a variable named $name and set the value of it by taking what comes in as POST with the name of “first_name”. (note all variable names start with $)
Line 5 – We create a variable for a message as $message and set the value to “Hello”
Line 7 – We print out on the screen the value for $message a space and then the value for $name
Line 9 – We print out a <br> HTML tag to create a new line (browsers will print text based on HTML tags. If a text file has multiple lines, but there are no HTML tags the browser will display all text on one line.)
Line 11 – We print out a message “You have written your first program!”
Line 13 – We print out a <br> HTML tag to create a new line
Line 15 – We print out a hyperlink so that users can click back to the form. You should not create “dead ends” in your scripts both for users, and also for you own use and troubleshooting
$name = $_POST['first_name']; $message = "Hello"; echo "$message $name"; echo "<br>"; echo "You have written your first program!"; echo "<br>"; echo "<a href='form.html'>GO BACK</a>";Code language: HTML, XML (xml)