How to install Docker on Ubuntu 24.04
Last update: December 31, 2024
Welcome back! In this article, we’ll dive into writing your first PHP program and explore how PHP integrates with HTML to create dynamic web pages. Let’s get started. --- ## 1. Setting Up Your First PHP Program PHP scripts are executed on the server, and their output is sent as HTML to the browser. To begin, create a file with a `.php` extension. Here’s your first PHP script: ```php ``` ### Key Points: - **PHP Tags**: PHP code is enclosed within ` `. - **`echo` Statement**: Outputs text to the browser. Save this file as `hello.php` and run it through your PHP server. You should see "Hello, world!" displayed in your browser. ### Important Step: Right-click on the browser and select "View Page Source" (or its equivalent). You will notice that only the output (`Hello, world!`) is visible in the HTML source. The `echo` command itself is not included. **Why?** PHP is a server-side language. The PHP interpreter processes the code on the server, and only the resulting output is sent to the browser. This makes PHP ideal for securely generating dynamic content. --- ## 2. Mixing PHP and HTML PHP is most powerful when combined with HTML. Let’s enhance the above example by integrating it into an HTML structure: ```php``` ### Explanation: - PHP runs only inside the ` ` tags. - HTML outside these tags is output as-is, allowing you to blend dynamic and static content effortlessly. When you view the page source, you will see the HTML structure but not the `echo` statement, for the same reason mentioned earlier: PHP executes server-side, and only its output is sent to the browser. --- ## 3. Practical Example: Displaying the Current Date PHP offers built-in functions like `date()` to generate dynamic content. Here’s an example: ```php
Today’s date is:
``` ### Output: This code will display the current date in a readable format, such as "Monday, January 1, 2025." ### Important Step: View the page source again. The PHP code using `date()` is not shown—only the output (the generated date) appears. **Why?** The `date()` function, like `echo`, runs on the server, and only its output is sent to the browser. This reinforces the security and utility of PHP for generating dynamic content without exposing the server logic. --- ## 4. Linking HTML and PHP Pages A key use case is linking an HTML page to a PHP script. For instance: ### Example HTML (`index.html`): ```html