First PHP Program
First PHP Program
Let’s write a simple PHP program that asks the user for their name and then greets them with a message that includes their name.
What is a PHP program?
A PHP program is a script written in the PHP programming language that runs on a web server. It is primarily used to create dynamic and interactive web pages by processing server-side logic, handling form submissions, interacting with databases, and generating HTML content sent to the user’s web browser.
Steps to create a PHP program
Launch Phpstorm IDE and create a PHP project, such as my_first_app.
Choose the project folder inside your web server’s root directory( htdocs for XAMPP)
XAMPP is a free, open-source, cross-platform web server solution stack that includes Apache, MySQL, and PHP. It simplifies setting up a local development environment for PHP applications by providing an easy-to-use control panel and pre-configured components.
Create a PHP File, such as index.php. The IDE will create a file named index.php inside the my_first_app directory.
PHP Code Listing
Add the following PHP code
<?php
/*
* First PHP Program
* PHP Tutorials - www.TestingDocs.com
*/
// HTTP POST request
if($_SERVER["REQUEST_METHOD"] =="POST") {
$name = $_POST["name"];
// Greet the user
echo "<h2> Hello, $name! </h2><br>";
}
?>
<!DOCTYPE html>
<html lang= "en">
<head>
<meta charset= "UTF-8">
<title></title>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for= "name">Enter your Name:</label>
<input type="text" id="name"
name="name" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Explanation
An HTML form is a mechanism for sending user input to a web server. It allows users to enter data through various fields (like text boxes, checkboxes, and buttons) and submit it to the server for processing. This is often used for tasks such as logging in, searching, or submitting feedback. Forms use methods like GET or POST to send data, with POST being the most common for sensitive or large amounts of data.
A POST HTTP request is used to submit data to a server to create or update a resource. Unlike GET requests, which retrieve data, POST requests send data to be processed by the server, such as form submissions or file uploads. The data is included in the request’s body rather than the URL.
Run the PHP program
Run the PHP program by following the below steps:
To start the Apache web server, launch the XAMPP control panel and click the Start button for the Apache component. Apache is a widely used open-source web server software that serves web content online.
Open a web browser and navigate to the following URL:
http://localhost/my_first_app/index.php
Enter your name and click on the Submit button.
The program should greet you with a greeting followed by your name.
That’s it. You have successfully run the first PHP program.
Video Tutorial
PHP Tutorials
PHP Tutorials on this website:
More Information on PHP