How to Write Your First PHP Program
PHP is a programming language that runs on a server. You can use it to create dynamic websites, process forms, and work with databases. This tutorial covers the basics so you can write and run your first program.
PHP is a programming language that runs on a server. You can use it to create dynamic websites, process forms, and work with databases. This tutorial covers the basics so you can write and run your first program.
1. Create a PHP file
With PHP installed on your computer, create a folder for your project and a file named index.php.
Add this code:
<?php
echo "Hello, world!";The <?php tag starts PHP code. The echo command displays text, and the semicolon ends the statement.
2. Run your code
Open a terminal inside your project folder and run:
php -S localhost:8000Open http://localhost:8000 in your browser. You should see:
Hello, world!This built-in server is intended for local development. Press Ctrl+C in the terminal when you want to stop it.
3. Use variables
Variables store information. In PHP, variable names start with $.
<?php
$name = "Gary";
$age = 30;
echo "My name is $name, and I am $age years old.";Text goes inside quotation marks. Numbers can be written without them.
4. Make decisions
Use an if statement to display different messages based on a condition.
<?php
$temperature = 75;
if ($temperature >= 70) {
echo "It is warm outside.";
} else {
echo "It is cool outside.";
}PHP checks whether the temperature is at least 70 and runs the matching section of code.
5. Repeat actions with a loop
A loop lets you repeat code without writing the same statement several times.
<?php
for ($number = 1; $number <= 5; $number++) {
echo "Number: $number<br>";
}This displays the numbers 1 through 5. The HTML <br> tag puts each result on a new line in the browser.
6. Create a function
Functions let you reuse code.
<?php
function greet(string $name): string
{
return "Hello, $name!";
}
echo greet("Gary");The function receives a name and returns a greeting. You can call it again with a different name.
7. Combine PHP and HTML
PHP can generate content inside a regular HTML page.
<?php
$title = "My First PHP Website";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?php echo htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); ?></title>
</head>
<body>
<h1><?php echo htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); ?></h1>
<p>Today is <?php echo date("F j, Y"); ?>.</p>
</body>
</html>The page displays your title and the server’s current date. htmlspecialchars() escapes special characters so text can be displayed safely in HTML.
Try changing the title, adding another variable, or writing a function of your own. Small experiments are a useful way to practice PHP.