Writing Your First PHP Script

Introduction to PHP
What is PHP?
PHP (Hypertext Preprocessor) is a widely-used open-source scripting language that is especially suited for web development. It runs on the server side, which means it processes code on the server before sending the result to the user’s browser. PHP can generate dynamic web pages, handle forms, manage sessions, and interact with databases, making it a powerful tool for creating interactive websites.
Why Use PHP?
PHP is popular for several reasons:
-
Ease of Learning: Its syntax is similar to C, Java, and Perl, making it approachable for beginners.
-
Flexibility: PHP can be embedded directly into HTML, allowing you to mix static and dynamic content seamlessly.
-
Wide Support: Most web servers support PHP, and it works across multiple platforms like Windows, macOS, and Linux.
-
Large Community and Resources: Extensive documentation, tutorials, and libraries are available for PHP developers.
-
Integration Capabilities: PHP works well with databases (like MySQL), web frameworks, and APIs, making it ideal for modern web applications.
Setting Up Your Development Environment
Before writing your first PHP script, you need a development environment that can run PHP:
-
Local Server Installation: Tools like XAMPP, WAMP, or MAMP provide an easy way to run PHP on your computer. They include Apache (the web server), PHP, and MySQL (for databases).
-
Text Editor or IDE: You can use any code editor like VS Code, Sublime Text, or PHPStorm to write your scripts.
-
Testing Your Setup: Create a simple PHP file with
<?php echo "Hello, World!"; ?>and open it in your browser through the local server to confirm everything is working correctly.
Getting Started
Installing a Local Server (XAMPP, WAMP, MAMP)

To run PHP scripts on your computer, you need a local server environment. Tools like XAMPP, WAMP, or MAMP make this easy:
-
XAMPP: Works on Windows, macOS, and Linux. It includes Apache (web server), MySQL (database), and PHP.
-
WAMP: Windows-only package with Apache, MySQL, and PHP.
-
MAMP: Designed for macOS, but also works on Windows, providing a similar server setup.
Steps to install XAMPP (example):
-
Download XAMPP from the official website.
-
Run the installer and follow the instructions.
-
Start Apache and MySQL from the XAMPP control panel.
-
Your local server is now ready to run PHP scripts.
Creating Your First PHP File
Once your server is running, you can create your first PHP file:
-
Navigate to your local server’s root directory:
-
XAMPP:
C:\xampp\htdocs\(Windows) -
MAMP:
/Applications/MAMP/htdocs/(macOS)
-
-
Create a new folder for your project, e.g.,
my_first_php. -
Inside that folder, create a file called
index.php. -
Open the file in a text editor and write your first PHP code:
-
Save the file.
To view it in a browser, open http://localhost/my_first_php/ and you should see “Hello, World!” displayed.
Understanding PHP Syntax
PHP scripts are embedded in HTML using the <?php ?> tags. Here are the basics:
-
Opening and closing tags: Every PHP script starts with
<?phpand ends with?>. -
Statements: Each PHP statement ends with a semicolon (
;). -
Output: Use
echoorprintto display text or variables on the browser. -
Comments: Use
//for single-line comments and/* */for multi-line comments.
Example:
By understanding these basics, you can start writing simple scripts and gradually move to more complex PHP programs.
Your First PHP Script
Writing a Simple “Hello, World!” Script
The simplest way to start with PHP is by writing a script that displays text on the browser. This helps you confirm that your PHP setup is working.
Step-by-Step:
-
Open your text editor and create a new file named
hello.php. -
Write the following code:
-
Save the file in your local server’s root directory (
htdocsfor XAMPP). -
Open your browser and navigate to
http://localhost/hello.php.
You should see the text Hello, World! displayed.
Embedding PHP in HTML
PHP can be mixed with HTML, allowing you to create dynamic web pages. Here’s a simple example:
In this example:
-
The HTML provides the page structure.
-
The PHP code inside
<?php ?>dynamically outputs text into the HTML content. -
This combination is the foundation of most PHP-driven websites.
Running Your Script in a Browser
To see your PHP script in action:
-
Make sure your local server (Apache) is running.
-
Place your PHP file in the server’s root folder.
-
Open a web browser and enter the URL corresponding to your file, e.g.,
http://localhost/hello.phporhttp://localhost/my_first_php/index.php. -
If everything is set up correctly, your PHP-generated content will appear in the browser.
Tip: Never try to open a PHP file directly by double-clicking it in your file explorer, because PHP needs a server to process the code before displaying it in a browser.

Basic PHP Concepts
Variables and Data Types
Variables in PHP are used to store data that can be used and manipulated in your scripts. A variable always starts with a dollar sign $, followed by the variable name.
Example:
<?php
$name = “John”; // String
$age = 25; // Integer
$height = 5.9; // Float
$isStudent = true; // Boolean
echo “type of {$name} is “.gettype($name).”<br>”;
echo “type of {$age} is “.gettype($age).”<br>”;
echo “type of {$height} is “.gettype($height).”<br>”;
echo “type of {$isStudent} is “.gettype($isStudent).”<br>”;
?>

Common Data Types in PHP:
-
String: Text, e.g.,
"Hello World" -
Integer: Whole numbers, e.g.,
25 -
Float (Double): Decimal numbers, e.g.,
3.14 -
Boolean: True or False values, e.g.,
trueorfalse -
Array: A collection of values, e.g.,
[1, 2, 3] -
NULL: Represents no value
Variables are case-sensitive ($Name and $name are different).
Comments in PHP
Comments are used to explain your code and are ignored by PHP. They help make your code easier to read and maintain.
Types of comments:
-
Single-line comment:
-
Another single-line style:
-
Multi-line comment:
Basic Output (echo, print)
PHP provides two main ways to display content to the browser: echo and print.
1. echo
-
Used to output one or more strings.
-
Can output multiple values separated by commas.
2. print
-
Can output a single string.
-
Returns
1, which allows it to be used in expressions.
Tip:echo is slightly faster than print, but both are commonly used for displaying text or variables on the browser.
Common Errors and Troubleshooting
Syntax Errors
Syntax errors occur when PHP cannot understand your code because of mistakes in writing it. These are the most common errors for beginners.
Common causes:
-
Missing semicolons (
;) at the end of a statement. -
Forgetting opening
<?phpor closing?>tags. -
Misspelled keywords (e.g.,
echinstead ofecho). -
Unmatched parentheses
()or braces{}.
Example:
Fix: Add the semicolon:
Server Not Running
PHP scripts require a server (like Apache) to run. If the server isn’t running, your PHP code won’t be processed.
How to check:
-
Open your local server control panel (XAMPP, WAMP, MAMP).
-
Ensure Apache is running.
-
Access your PHP file through
http://localhost/yourfile.phpin a browser.
Common issues:
-
Port conflicts (e.g., another program using port 80).
-
Firewall blocking the server.
Fix: Stop conflicting programs or change the port in your server settings.
Debugging Tips
Debugging is the process of finding and fixing errors in your code. Here are beginner-friendly tips:
-
Read Error Messages Carefully: PHP provides detailed error messages that tell you the file and line number of the problem.
-
Use
error_reporting(E_ALL);This ensures all errors and warnings are displayed.
-
Check Syntax Carefully: Look for missing semicolons, parentheses, or quotes.
-
Use Comments to Test Sections: Temporarily comment out parts of your code to isolate problems.
-
Google is Your Friend: Many errors have been encountered by others; searching the error message often gives solutions.
Tip: Always save your file and refresh the browser after changes to see the effect.
Next Steps
Once you have successfully written and run your first PHP script, it’s time to expand your knowledge and explore more advanced features of PHP. This will help you create more dynamic and interactive web applications.
Exploring PHP Functions
Functions are blocks of code that perform specific tasks. PHP has many built-in functions, and you can also create your own.
Example of a simple function:
echo greet(“John”);
-
Functions help you reuse code and keep your scripts organized.
-
PHP provides functions for string manipulation, math operations, arrays, dates, and more.
Working with Forms
PHP can handle user input through HTML forms. This allows you to create interactive pages, such as contact forms or login pages.
Basic example:
-
$_POSTcollects data sent from a form. -
Forms let you capture user input and use it dynamically in your scripts.
Connecting to a Database
PHP can interact with databases like MySQL to store and retrieve data. This is essential for building applications such as blogs, e-commerce sites, and login systems.
Basic example using MySQLi:
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die(“Connection failed: “ . $conn->connect_error);
}
echo “Connected successfully”;
-
This demonstrates a connection to a MySQL database.
-
Once connected, you can perform queries to insert, update, delete, or retrieve data.
Tip for Learning Next Steps
-
Start small: Experiment with simple functions, form handling, and database queries.
-
Test your scripts frequently to understand how each part works.
-
Gradually combine these features to build more complex projects.
Summary and Best Practices
After writing your first PHP script and exploring basic concepts, it’s important to review what you’ve learned and follow best practices to write clean, efficient, and maintainable code.
Recap of Key Points
-
PHP Basics: You learned how to write PHP code using
<?php ?>tags and output content withechoandprint. -
Variables and Data Types: You can store and manipulate data using strings, numbers, booleans, arrays, and more.
-
Embedding PHP in HTML: PHP can generate dynamic content within an HTML page.
-
Forms and User Input: You can capture user input using HTML forms and process it in PHP using
$_POSTor$_GET. -
Functions: Functions help organize your code and allow reuse of logic.
-
Database Interaction: PHP can connect to databases like MySQL to store and retrieve data, enabling dynamic applications.
Tips for Writing Clean PHP Code
-
Use Meaningful Variable Names: Instead of
$xor$y, use$usernameor$age. This makes your code readable. -
Comment Your Code: Explain complex sections with comments so you or others can understand it later.
-
Keep Code Organized: Separate logic into functions or include files for better structure.
-
Validate User Input: Always check user input to prevent errors and security issues like SQL injection.
-
Consistent Formatting: Indent code and use spacing consistently for readability.
-
Test Frequently: Run your scripts often to catch errors early.
Moving Forward
-
Practice by creating small projects such as a contact form, a simple calculator, or a mini blog.
-
Explore PHP frameworks like Laravel or CodeIgniter once you are comfortable with core PHP.
-
Learn advanced concepts like sessions, cookies, file handling, and security best practices.
By following these practices and continuing to experiment, you’ll build a strong foundation in PHP and be ready to develop more complex web applications.
Summary and Best Practices
Recap of Key Points
By now, you should have a clear understanding of the basics of PHP:
-
Writing PHP Scripts: Using
<?php ?>tags to embed PHP in your web pages. -
Outputting Content: Displaying information to the browser using
echoandprint. -
Variables and Data Types: Storing and manipulating data with strings, numbers, booleans, arrays, and NULL.
-
Comments: Adding explanations in your code for readability and maintenance.
-
PHP in HTML: Combining dynamic PHP content with static HTML to create interactive web pages.
-
Forms and User Input: Capturing user data through HTML forms and processing it safely using
$_POSTor$_GET. -
Functions: Organizing code into reusable blocks to simplify development and debugging.
-
Database Connections: Using PHP to connect to databases like MySQL to store, retrieve, and manage data dynamically.
Tips for Writing Clean PHP Code
Writing clean and organized code is crucial for both beginners and professionals. Here are some best practices:
-
Use Meaningful Names: Name variables and functions clearly, e.g.,
$userNameinstead of$x. -
Comment Your Code: Explain complex logic or important sections with comments.
-
Consistent Formatting: Indent code properly, use spaces, and follow a consistent style.
-
Keep Code Modular: Break code into functions or separate files to improve readability and maintainability.
-
Validate and Sanitize Input: Always check and clean user inputs to avoid errors and security issues.
-
Test Frequently: Run small sections of code regularly to catch bugs early.
-
Avoid Hardcoding: Use variables and configurations instead of embedding fixed values in multiple places.
-
Stay Organized: Group related code together, and separate presentation (HTML) from logic (PHP) when possible.
Following these practices will make your PHP code easier to read, debug, and maintain, and it will prepare you for building larger, more complex applications in the future.
