Lesson 1.3: Your First PHP Script
Beyond Hello World
Every programming tutorial starts with "Hello World". Boring, right? Let's build something more interesting - a dynamic personal profile page that changes based on time, calculates your age automatically, and displays real information. Way cooler than printing one line.
Fire up your editor. Create a new file called profile.php
. We're diving in!
PHP Tags and Syntax Basics
PHP code lives inside special tags. The parser ignores everything outside these tags, treating it as regular HTML.
<?php
// Your PHP code goes here
?>
That's the standard tag. You'll see shortcuts like <?
or <?=
in older code. Ignore them. Always use <?php
for compatibility and clarity.
Here's your first real PHP code:
<?php
$message = "Welcome to PHP development!";
echo $message;
?>
Save it. Run it. See your message? Congrats - you're officially a PHP developer!
Variables and Data Types
PHP variables start with $
. No need to declare types - PHP figures it out:
<?php
// Different variable types
$name = "Alex Morgan"; // String
$age = 28; // Integer
$height = 5.75; // Float
$isStudent = true; // Boolean
$hobbies = ["coding", "gaming", "reading"]; // Array
$address = null; // Null
// PHP is dynamically typed - variables can change types
$flexible = "I'm a string";
$flexible = 42; // Now I'm an integer
$flexible = true; // Now I'm a boolean
?>
Notice something? No var
, let
, or const
like JavaScript. Just $
and go. PHP keeps things simple.
Outputting Content
PHP offers several ways to display content:
<?php
$username = "CodeNinja";
$level = 42;
// echo - most common
echo "Player: " . $username;
// print - similar to echo
print "Level: " . $level;
// printf - formatted output
printf("Player %s reached level %d!", $username, $level);
// var_dump - debugging superhero
var_dump($username); // Shows type and value
// print_r - human-readable arrays
print_r($_SERVER); // Try this one!
?>
Each serves different purposes. You'll use echo
constantly, var_dump
for debugging, and others occasionally.
Building Your Profile Page
Delete everything. Let's build something real:
<?php
// Personal Information
$firstName = "Alex";
$lastName = "Morgan";
$birthYear = 1995;
$email = "[email protected]";
$city = "San Francisco";
$profession = "Web Developer";
// Calculate age dynamically
$currentYear = date('Y');
$age = $currentYear - $birthYear;
// Determine time-based greeting
$hour = date('H');
if ($hour < 12) {
$greeting = "Good morning";
} elseif ($hour < 17) {
$greeting = "Good afternoon";
} else {
$greeting = "Good evening";
}
// Skills array
$skills = [
"HTML5" => 90,
"CSS3" => 85,
"JavaScript" => 75,
"PHP" => 60,
"MySQL" => 55
];
// Calculate days until birthday
$today = new DateTime();
$birthday = new DateTime($currentYear . '-07-15'); // July 15th
if ($birthday < $today) {
$birthday->modify('+1 year');
}
$daysUntilBirthday = $today->diff($birthday)->days;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo $firstName . " " . $lastName; ?> - Profile</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
color: #333;
}
.profile-card {
background: white;
border-radius: 20px;
padding: 40px;
box-shadow: 0 20px 40px rgba(0,0,0,0.1);
max-width: 500px;
width: 90%;
}
.greeting {
color: #667eea;
font-size: 1.2rem;
margin-bottom: 10px;
}
h1 {
font-size: 2.5rem;
margin-bottom: 10px;
}
.subtitle {
color: #666;
margin-bottom: 30px;
}
.info-group {
margin-bottom: 25px;
}
.info-label {
font-weight: 600;
color: #764ba2;
display: inline-block;
width: 100px;
}
.skills {
margin-top: 30px;
}
.skill-item {
margin-bottom: 15px;
}
.skill-name {
display: flex;
justify-content: space-between;
margin-bottom: 5px;
}
.skill-bar {
background: #e0e0e0;
height: 10px;
border-radius: 5px;
overflow: hidden;
}
.skill-progress {
background: linear-gradient(90deg, #667eea, #764ba2);
height: 100%;
border-radius: 5px;
transition: width 2s ease;
}
.birthday-notice {
background: #f8f8f8;
padding: 15px;
border-radius: 10px;
margin-top: 20px;
text-align: center;
}
.timestamp {
text-align: center;
color: #999;
font-size: 0.9rem;
margin-top: 30px;
}
</style>
</head>
<body>
<div class="profile-card">
<p class="greeting"><?php echo $greeting; ?>! ๐</p>
<h1><?php echo $firstName . " " . $lastName; ?></h1>
<p class="subtitle"><?php echo $profession; ?> from <?php echo $city; ?></p>
<div class="info-group">
<span class="info-label">Age:</span>
<span><?php echo $age; ?> years old</span>
</div>
<div class="info-group">
<span class="info-label">Email:</span>
<span><?php echo $email; ?></span>
</div>
<div class="info-group">
<span class="info-label">Location:</span>
<span><?php echo $city; ?></span>
</div>
<div class="skills">
<h3>Skills & Proficiency</h3>
<?php foreach ($skills as $skill => $proficiency): ?>
<div class="skill-item">
<div class="skill-name">
<span><?php echo $skill; ?></span>
<span><?php echo $proficiency; ?>%</span>
</div>
<div class="skill-bar">
<div class="skill-progress" style="width: <?php echo $proficiency; ?>%"></div>
</div>
</div>
<?php endforeach; ?>
</div>
<?php if ($daysUntilBirthday <= 30): ?>
<div class="birthday-notice">
๐ Birthday coming up in <?php echo $daysUntilBirthday; ?> days!
</div>
<?php endif; ?>
<p class="timestamp">
Page generated on <?php echo date('F j, Y \a\t g:i A'); ?>
</p>
</div>
</body>
</html>
Save this. Run it. Pretty impressive for your first script, right?
Understanding What Just Happened
Let's break down the key concepts:
Variables and Calculations:
$currentYear = date('Y');
$age = $currentYear - $birthYear;
PHP handles math naturally. We grabbed the current year, subtracted birth year, got age. No complex type conversions needed.
Conditional Logic:
if ($hour < 12) {
$greeting = "Good morning";
} elseif ($hour < 17) {
$greeting = "Good afternoon";
} else {
$greeting = "Good evening";
}
PHP's if/else works like other languages. Clean, readable, logical.
Arrays and Loops:
$skills = ["HTML5" => 90, "CSS3" => 85];
foreach ($skills as $skill => $proficiency) {
// Display each skill
}
Associative arrays (key-value pairs) make data organization intuitive. The foreach loop iterates elegantly.
Mixing PHP with HTML:
<h1><?php echo $firstName . " " . $lastName; ?></h1>
See how PHP embeds within HTML? This flexibility makes PHP perfect for web development.
Common Beginner Mistakes
Let's address mistakes now, before they become habits:
Forgetting Semicolons:
// Wrong
$name = "Alex"
echo $name
// Right
$name = "Alex";
echo $name;
Undefined Variables:
// Wrong - $username never defined
echo "Hello " . $username;
// Right - always initialize
$username = "Guest";
echo "Hello " . $username;
Quote Confusion:
$name = "Alex";
// Single quotes - variables NOT parsed
echo 'Hello $name'; // Outputs: Hello $name
// Double quotes - variables parsed
echo "Hello $name"; // Outputs: Hello Alex
// Concatenation - always works
echo 'Hello ' . $name; // Outputs: Hello Alex
Missing Dollar Signs:
// Wrong
name = "Alex";
// Right
$name = "Alex";
String Manipulation
Strings are PHP's bread and butter. Master these operations:
<?php
$firstName = "alex";
$lastName = "MORGAN";
$email = " [email protected] ";
// Change case
echo ucfirst($firstName); // Alex
echo strtoupper($firstName); // ALEX
echo strtolower($lastName); // morgan
echo ucwords("hello world"); // Hello World
// Trim whitespace
echo trim($email); // "[email protected]"
// String length
echo strlen($firstName); // 4
// Replace text
echo str_replace("alex", "jordan", $email); // [email protected]
// Extract portion
echo substr($firstName, 0, 2); // "al"
// Find position
echo strpos($email, "@"); // 6
// Combine multiple operations
$username = strtolower(trim($firstName . "." . $lastName));
echo $username; // alex.morgan
?>
Try these functions. Modify them. String manipulation becomes second nature quickly.
Working with Dates and Time
PHP excels at date manipulation:
<?php
// Current date/time
echo date('Y-m-d'); // 2025-06-05
echo date('F j, Y'); // June 5, 2025
echo date('l'); // Thursday
echo date('g:i A'); // 3:45 PM
// Timestamp manipulation
$tomorrow = strtotime("+1 day");
echo date('Y-m-d', $tomorrow);
$nextWeek = strtotime("+1 week");
echo date('F j', $nextWeek);
// Custom calculations
$birthDate = strtotime("1995-07-15");
$ageInDays = floor((time() - $birthDate) / 86400);
echo "You are " . $ageInDays . " days old";
// DateTime object (more powerful)
$date = new DateTime();
$date->add(new DateInterval('P10D')); // Add 10 days
echo $date->format('Y-m-d');
?>
Dates confuse beginners initially. Practice these examples until they click.
Creating Dynamic Content
Let's build something that changes every page load:
<?php
// Random quotes
$quotes = [
"Code is poetry.",
"First, solve the problem. Then, write the code.",
"Programming isn't about what you know; it's about what you can figure out.",
"The best error message is the one that never shows up.",
"Simplicity is the soul of efficiency."
];
$randomQuote = $quotes[array_rand($quotes)];
// Random color generator
$colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7'];
$randomColor = $colors[array_rand($colors)];
// Visitor counter (using sessions - we'll cover this later)
session_start();
$_SESSION['visits'] = ($_SESSION['visits'] ?? 0) + 1;
$visits = $_SESSION['visits'];
?>
<!DOCTYPE html>
<html>
<head>
<title>Dynamic PHP Page</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: <?php echo $randomColor; ?>;
color: white;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.container {
text-align: center;
padding: 40px;
background: rgba(0,0,0,0.2);
border-radius: 10px;
}
.quote {
font-size: 2rem;
margin-bottom: 20px;
font-style: italic;
}
.visits {
font-size: 1.2rem;
}
</style>
</head>
<body>
<div class="container">
<div class="quote">"<?php echo $randomQuote; ?>"</div>
<div class="visits">You've visited this page <?php echo $visits; ?> time(s)</div>
<p>Refresh to see changes!</p>
</div>
</body>
</html>
Each refresh shows different quotes, colors, and increments the counter. That's dynamic content!
Debugging Your Code
Things will break. Here's how to fix them:
Enable Error Reporting:
<?php
// Add to top of script during development
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
Debug with var_dump():
$data = ["name" => "Alex", "age" => 28];
var_dump($data); // Shows structure and types
Check Variable Existence:
if (isset($username)) {
echo $username;
} else {
echo "Username not set";
}
Use die() for Quick Debugging:
$result = someFunction();
die(var_dump($result)); // Stops execution, shows value
Best Practices from Day One
Start with good habits:
Meaningful Variable Names:
// Bad
$n = "John";
$a = 25;
// Good
$userName = "John";
$userAge = 25;
Comment Your Code:
// Calculate discount based on user membership level
if ($membershipLevel === 'gold') {
$discount = 0.20; // 20% for gold members
} else {
$discount = 0.10; // 10% for everyone else
}
Consistent Formatting:
// Pick a style and stick to it
if ($condition) {
doSomething();
} else {
doSomethingElse();
}
Escape Output:
$userInput = $_GET['name'] ?? '';
echo htmlspecialchars($userInput); // Prevents XSS attacks
Challenge Exercises
Ready to practice? Try these:
- Temperature Converter: Create a script that converts Celsius to Fahrenheit
- Age Calculator: Calculate exact age in years, months, and days
- Random Password Generator: Generate secure passwords of specified length
- Simple Mad Libs: Create a story with user-provided words
- Countdown Timer: Show days until a specific date
Start simple. Add features gradually. Learning happens through doing.
Your First Mini-Project
Let's combine everything into a useful tool - a simple biorhythm calculator:
<?php
$birthDate = '1995-07-15'; // Change to your birthdate
// Calculate days lived
$birth = new DateTime($birthDate);
$today = new DateTime();
$daysLived = $today->diff($birth)->days;
// Biorhythm cycles
$physical = sin(2 * pi() * $daysLived / 23) * 100;
$emotional = sin(2 * pi() * $daysLived / 28) * 100;
$intellectual = sin(2 * pi() * $daysLived / 33) * 100;
// Format for display
$physical = round($physical);
$emotional = round($emotional);
$intellectual = round($intellectual);
?>
<!DOCTYPE html>
<html>
<head>
<title>Biorhythm Calculator</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
}
.rhythm {
margin: 20px 0;
}
.bar {
background: #e0e0e0;
height: 30px;
border-radius: 15px;
position: relative;
overflow: hidden;
}
.fill {
position: absolute;
height: 100%;
background: #4CAF50;
transition: width 1s ease;
}
.negative { background: #f44336; }
.label {
position: absolute;
width: 100%;
text-align: center;
line-height: 30px;
color: white;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Your Biorhythm Today</h1>
<p>Days lived: <?php echo number_format($daysLived); ?></p>
<div class="rhythm">
<h3>Physical: <?php echo $physical; ?>%</h3>
<div class="bar">
<div class="fill <?php echo $physical < 0 ? 'negative' : ''; ?>"
style="width: <?php echo abs($physical); ?>%;
<?php echo $physical < 0 ? 'right: 50%;' : 'left: 50%;'; ?>">
</div>
<div class="label"><?php echo $physical; ?>%</div>
</div>
</div>
<div class="rhythm">
<h3>Emotional: <?php echo $emotional; ?>%</h3>
<div class="bar">
<div class="fill <?php echo $emotional < 0 ? 'negative' : ''; ?>"
style="width: <?php echo abs($emotional); ?>%;
<?php echo $emotional < 0 ? 'right: 50%;' : 'left: 50%;'; ?>">
</div>
<div class="label"><?php echo $emotional; ?>%</div>
</div>
</div>
<div class="rhythm">
<h3>Intellectual: <?php echo $intellectual; ?>%</h3>
<div class="bar">
<div class="fill <?php echo $intellectual < 0 ? 'negative' : ''; ?>"
style="width: <?php echo abs($intellectual); ?>%;
<?php echo $intellectual < 0 ? 'right: 50%;' : 'left: 50%;'; ?>">
</div>
<div class="label"><?php echo $intellectual; ?>%</div>
</div>
</div>
</body>
</html>
This combines math, dates, conditionals, and dynamic styling. Real PHP in action!
What You've Learned
Look at what you've accomplished:
- โ PHP syntax and tags
- โ Variables and data types
- โ String manipulation
- โ Date/time functions
- โ Mixing PHP with HTML
- โ Basic debugging techniques
- โ Creating dynamic content
You've written more PHP than most people ever will. Feel proud!
Common Questions
Q: Why do some examples use echo and others print? A: They're nearly identical. Echo is marginally faster and more common. Pick echo and stick with it.
Q: Should I close PHP tags?
A: In files containing only PHP, omit the closing ?>
. It prevents accidental whitespace issues.
Q: How do I know if my code is "good"? A: Does it work? Can you understand it tomorrow? Would another developer understand it? Then it's good enough for now.
Next Steps
You're ready for more complex topics. Next lesson covers how PHP communicates with web servers - the request/response cycle that makes web applications possible.
Before moving on:
- Modify the profile page with your information
- Add a new feature (maybe favorite movies?)
- Try breaking something, then fix it
- Experiment with different date formats
Remember: every expert was once a beginner who didn't quit. You're on your way!
Quick Reference
PHP Tags:
<?php // Standard opening tag
?> // Closing tag (optional in PHP-only files)
Variable Rules:
- Start with $
- Case-sensitive
- Begin with letter or underscore
- Contain letters, numbers, underscores
Common Functions:
echo
- Output textvar_dump()
- Debug variablesdate()
- Format datesstrlen()
- String lengthucfirst()
- Capitalize first lettertrim()
- Remove whitespace
Escape Sequences:
\n
- New line\t
- Tab\"
- Double quote\\
- Backslash