Now we will create a small site, which is designed to give an initial understanding of working with PHP.
To create programs in PHP, we need a text editor. You can take any text editor. The most popular program today is Visual Studio Code.
Let’s move on to the directory that is intended to store the website files (In the previous topic, the C:\localhost\firstsite directory was created for this purpose.) Let’s create a text file in this directory and name it index.php. Open it in a text editor and add the following code to it:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My First PHP Website</title> </head> <body> <h2>Enter your details:</h2> <form action="data.php" method="POST"> <p>Enter a name: <input type="text" name="firstname" /></p> <p>Enter last name: <input type="text" name="lastname" /></p> <input type="submit" value="Submit"> </form> </body> </html>
The HTML code contains a form with two text fields. When the button is clicked, the form data is sent to the data.php script, as it is specified in the action.
Now let’s create this script that will process the data. Add a new text file to the C:\localhost folder. Let’s rename it to data.php. By default, php program files have the .php extension.
So let’s add the following code to the data.php file:
<?php $name = $_POST["firstname"]; $surname = $_POST["lastname"]; echo "Your name: <b>".$name . " " . $surname . "</b>"; ?>
To add PHP expressions, tags are used , between which there are instructions in the PHP language. In the php code, we get the submitted form data and display it on the page.
Each individual PHP expression must end with a semicolon. In this case, we have three expressions. Two of them receive the submitted form data, for example, $name = $_POST[“firstname”];.
$nameis a variable that will store some value. All variables in PHP are preceded by a $ sign. And since the form on the index.php page uses the POST method to submit, $_POST[“firstname”]we can use the expression to get the value that was entered in the text field with the attribute name=”first name”. And this value gets into the $name variable.
With the echo statement, you can display any value or text that comes after the statement on the page. In this case ( echo “Your name: “.$name . ” ” . $surname . ““), the quoted text is concatenated with the values of the $name and $surname variables using a dot and displayed on the page.
Now let’s access the input form by navigating to http://localhost/firstsite/index.php (or http://localhost/firstsite ):