How to Run PHP Files Locally Using XAMPP: Step-by-Step Tutorial for Beginners
PHP, which stands for Hypertext Preprocessor, is a widely used open-source server-side scripting language designed specifically for web development. It enables developers to create dynamic web pages that interact with databases and provide personalized content to users. Unlike static HTML pages, PHP scripts are executed on the server, generating HTML content dynamically before being sent to the user’s browser.
PHP files typically have a .php extension. They can perform various functions such as reading and writing files on the server, handling form data, managing sessions, encrypting data, and manipulating databases. These capabilities make PHP a powerful tool for creating interactive and data-driven websites.
PHP is popular among web developers because it is easy to learn and use. Its syntax is straightforward and resembles other programming languages, making it accessible to beginners and professionals alike. PHP also integrates seamlessly with many database systems, especially MySQL, allowing developers to build complex applications efficiently.
PHP is compatible with almost all web servers and operating systems, including Windows, Linux, and macOS. This flexibility means you can develop and test PHP applications on various platforms without compatibility issues.
PHP scripts cannot run by themselves on a computer. They require a web server to process the PHP code and deliver the generated HTML to the browser. When you write a PHP file on your local machine, it does not execute if you simply open it with a browser because the PHP code needs to be processed by a server.
A web server like Apache or Nginx interprets the PHP code, executes it, and sends the resulting output as an HTML response. This is why setting up a local web server environment is essential for developing and testing PHP applications on your computer.
Several software packages bundle the required components for running PHP locally. These include the web server (usually Apache), a database system (commonly MySQL or MariaDB), and PHP itself. The most popular packages for this purpose are XAMPP and WampServer.
WampServer is only available for Windows operating systems, limiting its use for developers working on Linux or macOS. On the other hand, XAMPP is a cross-platform package that runs on Windows, Linux, and macOS, making it the preferred choice for developers who use different operating systems.
XAMPP is an open-source, free software package that includes Apache (the web server), MariaDB (a MySQL-compatible database), PHP, and Perl. It provides an easy way to install and manage a local web server environment on your computer.
XAMPP simplifies the process of developing PHP applications locally by bundling all necessary components in one installation. This means you do not need to install and configure Apache, PHP, and MySQL separately. You can start coding and testing your PHP scripts immediately after installing XAMPP.
When a user requests a PHP page through a web browser, the request is sent to the web server. The server processes the PHP code inside the file and executes the instructions. This could include accessing a database, performing calculations, or generating HTML content dynamically.
After executing the PHP code, the server sends the output, usually HTML, back to the browser. The browser then renders the page for the user. This process happens behind the scenes, and the user only sees the resulting webpage without any PHP code.
PHP is used for a variety of tasks in web development, including:
The versatility of PHP makes it suitable for both simple websites and complex web applications.
A PHP file can contain HTML, CSS, JavaScript, and PHP code all within the same file. PHP code is embedded between <?php and ?> tags. When the server processes the file, only the PHP code inside these tags is executed.
Here is a simple example of PHP code embedded in an HTML page:
php
CopyEdit
<!DOCTYPE html>
<html>
<head>
<title>Sample PHP Page</title>
</head>
<body>
<h1>Welcome to My Website</h1>
<?php
echo “Today is “. date(“l, F j, Y”);
?>
</body>
</html>
In this example, the PHP script outputs the current date dynamically.
PHP is known for its simple syntax, making it accessible for beginners without extensive programming experience. Unlike some other languages that require understanding complex concepts upfront, PHP allows developers to quickly start writing functional code.
PHP can run on multiple operating systems, including Windows, Linux, and UNIX variants. This allows developers to build applications that work across different environments without needing significant modifications.
PHP offers great flexibility by allowing developers to modify existing projects easily. Whether you want to add new features or update your website’s design, PHP’s modular approach supports scalable development.
Since PHP is an open-source language, it is freely available to everyone. Developers do not need to pay for licenses or proprietary software, reducing the overall cost of development and deployment.
PHP is optimized for web development and typically runs faster than many other scripting languages. It processes scripts quickly and handles large amounts of traffic efficiently, even on slower network connections.
PHP supports the Model-View-Controller (MVC) design pattern, which helps organize code and separate business logic from presentation. This makes applications easier to maintain and extend.
PHP has a vast collection of libraries and frameworks that provide pre-written code for common tasks. These resources save developers time and effort by allowing them to reuse code instead of building everything from scratch.
To run PHP locally, you need a web server and a database management system. Apache is the most widely used web server for PHP development. For the database, MySQL or MariaDB is preferred because of its seamless integration with PHP.
You can install PHP separately on your machine, but it involves configuring the web server to work with PHP manually. This process can be complicated for beginners.
Instead of installing components individually, using an integrated package like XAMPP simplifies the setup. XAMPP automatically configures Apache, PHP, and MariaDB to work together. It also provides an easy-to-use control panel to start or stop the servers.
XAMPP is an open-source software package that provides an easy way to set up a local web server on your computer. It is designed for developers who want to test and develop web applications without needing an active internet connection or a remote server.
XAMPP includes several essential components for web development:
Apache acts as the backbone of XAMPP by serving web pages and handling requests from browsers. When you open a PHP page, Apache processes the request and hands the PHP code over to the PHP interpreter for execution.
MariaDB (or MySQL) stores data in databases. Many PHP applications rely on a database to store user information, content, or other dynamic data. XAMPP provides this database system out of the box.
PHP executes server-side scripts embedded within web pages, generating dynamic content based on user interactions or stored data.
Perl is included mainly for legacy support and specialized scripting, but is not essential for typical PHP development.
XAMPP is popular because it simplifies the otherwise complex task of configuring a web server environment. Setting up Apache, PHP, and MariaDB separately requires technical knowledge and can be time-consuming.
With XAMPP, developers get an all-in-one package that is ready to use immediately after installation. This allows beginners to start learning PHP quickly and enables professionals to test their projects locally before deploying them on a live server.
XAMPP also includes additional tools such as phpMyAdmin for database management, making it easier to interact with your databases through a graphical interface rather than command-line tools.
To begin, download the XAMPP installer suitable for your operating system. The official website offers versions for Windows, Linux, and macOS. Choose the latest stable release to ensure you have the most up-to-date features and security patches.
Once downloaded, run the installer file. During installation, you will be prompted to select which components to install. For PHP development, ensure that Apache, PHP, and MariaDB are selected. You can leave optional components unchecked if you do not need them.
You will also be asked to select the directory where XAMPP will be installed. The default location is usually C:\xampp on Windows or /opt/lampp on Linux. It is recommended to keep the default path for simplicity, but you may change it according to your preference.
After selecting components and the installation directory, proceed with the installation. This process typically takes a few minutes. When finished, you will have XAMPP installed and ready to use.
After installation, open the XAMPP Control Panel application. This panel allows you to manage the components easily. To start your local web server environment, click the “Start” buttons next to Apache and MariaDB.
Starting Apache launches the web server, which listens for requests from your browser. Starting MariaDB runs the database server necessary for data storage and retrieval.
Once started, the status indicators for Apache and MariaDB should turn green. This means both services are running correctly. If the services fail to start, common issues include port conflicts (e.g., other applications using port 80) or permission errors.
You can stop or restart Apache and MariaDB from the control panel as needed. Restarting is useful after making configuration changes or installing new PHP extensions.
The control panel also provides buttons to open the XAMPP folder, access logs, and launch utilities like phpMyAdmin for database management.
XAMPP serves web files from a specific folder named htdocs, located inside the XAMPP installation directory. For example, on Windows, it is usually at C:\xampp\htdocs.
Any PHP or HTML files placed inside the htdocs folder can be accessed through your web browser by navigating to http://localhost/.
It is best practice to create a separate folder inside htdocs for each PHP project you work on. This keeps files organized and avoids conflicts between different projects.
For example, to start a project named “demo”, create a folder named demo inside htdocs:
C:\xampp\htdocs\demo
Place all your project files, including PHP scripts, images, stylesheets, and JavaScript files, within this folder.
Create a new file named index.php inside your project folder. This file will serve as the entry point of your application.
Open index.php in a text editor and write a simple PHP script:
php
CopyEdit
<?php
echo “Hello, World! This is my first PHP script using XAMPP.”;
?>
Save the file.
With Apache running, open a web browser and navigate to:
http://localhost/demo/
The browser will execute the PHP script and display the output:
Hello, World! This is my first PHP script using XAMPP.
This confirms that your local web server is correctly processing PHP files.
XAMPP includes a PHP configuration file named php.ini, located inside the php folder of your XAMPP installation directory.
You can customize PHP settings such as maximum upload size, error reporting, and timezone by editing php.ini.
After making changes, restart Apache from the XAMPP control panel to apply the new settings.
PHP supports many extensions that add functionality, such as connecting to different types of databases or handling image processing.
In XAMPP, you can enable or disable PHP extensions by editing the php.ini file. Look for lines starting with extension= and uncomment the ones you need by removing the semicolon at the start.
Before writing any PHP code, it is important to organize your project files properly within the XAMPP environment. Begin by creating a dedicated folder for your project inside the htdocs directory of your XAMPP installation.
For example, create a folder named myproject:
C:\xampp\htdocs\myproject
This folder will contain all PHP files, assets, and resources for your project.
You can write PHP scripts using any text editor such as Notepad, Visual Studio Code, Sublime Text, or PHPStorm.
Open your text editor and write your PHP code. Save the file with a .php extension inside your project folder. For example, create a file named index.php inside myproject and write the following:
php
CopyEdit
<?php
echo “Welcome to my first PHP project using XAMPP!”;
?>
Save the file in the directory:
C:\xampp\htdocs\myproject\index.php
To run the PHP script, make sure Apache is running via the XAMPP Control Panel. Open your preferred web browser and type the URL:
http://localhost/myproject/
The server processes your PHP code, and the browser displays:
Welcome to my first PHP project using XAMPP!
If you see this output, it means your PHP script is running successfully on the local server.
In a real-world project, you will use multiple PHP files for different functionalities. For example, you might have index.php for the homepage, contact.php for a contact form, and about.php for an about page.
You can create these files inside your project folder and access them individually through URLs like:
http://localhost/myproject/contact.php
http://localhost/myproject/about.php
PHP allows you to include files within other files using include or require statements. This helps keep your code organized by separating reusable components like headers, footers, or database connections.
For example, create a header.php file:
php
CopyEdit
<?php
echo “<h1>Welcome to My Website</h1>”;
?>
And include it in index.php like this:
php
CopyEdit
<? php
include ‘header.php’;
echo “This is the homepage.”;
?>
When you visit index.php, the output will be:
Welcome to My Website
This is the homepage.
Using includes improves maintainability by avoiding duplicate code.
phpMyAdmin is a web-based graphical interface for managing MySQL or MariaDB databases. It is included in the XAMPP package and accessible through your browser.
Using phpMyAdmin, you can create, modify, and delete databases and tables without using command-line commands.
Make sure Apache and MariaDB are running in the XAMPP Control Panel.
Open your browser and navigate to:
http://localhost/phpmyadmin/
This will open the phpMyAdmin dashboard.
To create a new database:
Your database will now appear in the list and is ready to use.
To interact with a MySQL database from PHP, you need to establish a connection using PHP’s MySQLi or PDO extensions.
Here is an example of connecting to a MySQL database using MySQLi:
php
CopyEdit
<?php
$servername = “localhost”;
$username = “root”;
$password = “”;
$dbname = “your_database_name”;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die(“Connection failed: ” . $conn->connect_error);
}
echo “Connected successfully”;
?>
Save this script in your project folder and access it via the browser to verify the connection.
After connecting, you can run SQL queries to insert, retrieve, update, or delete data.
Example: Retrieving records from a table named users:
php
CopyEdit
$sql = “SELECT id, name, email FROM users”;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo “ID: “. $row[“id”]. ” – Name: ” . $row[“name”]. ” – Email: ” . $row[“email”]. “<br>”;
}
} else {
echo “0 results”;
}
$conn->close();
This script fetches all users and displays their details.
During development, seeing detailed error messages helps identify issues in your code quickly.
In your php.ini file (located in xampp/php/), ensure the following settings are enabled:
ini
CopyEdit
display_errors = On
error_reporting = E_ALL
Restart Apache after making changes for them to take effect.
XAMPP saves PHP errors in a log file located at:
xampp/php/logs/php_error_log
Reviewing this log helps diagnose errors that do not display in the browser.
Sessions are a way to store data on the server for individual users using a unique session ID. Sessions allow you to preserve user data across multiple pages, such as login information, shopping carts, or preferences.
When a user visits a website, PHP generates a unique session ID and stores data associated with this ID on the server. This session ID is sent to the user’s browser as a cookie or passed via URL.
Start a session using session_start() at the very beginning of your PHP script before any HTML output.
Example of setting and retrieving session variables:
php
CopyEdit
<?php
session_start();
// Set session variables
$_SESSION[“username”] = “JohnDoe”;
$_SESSION[“email”] = “john@example.com”;
// Retrieve session variables
echo “Username: “. $_SESSION[“username”] . “<br>”;
echo “Email: ” $_SESSION[“email”];
?>
Sessions continue to exist until you explicitly destroy them or the browser is closed.
To log users out or clear session data, you can use:
php
CopyEdit
<?php
session_start();
session_unset(); // Remove all session variables
session_destroy(); // Destroy the session
?>
This is useful for implementing user logout functionality.
Cookies are small files stored on the user’s computer by the browser. Unlike sessions, which store data on the server, cookies store data on the client-side and can persist for longer periods.
Cookies are typically used to remember user preferences or login information.
Example of setting a cookie:
php
CopyEdit
<?php
setcookie(“user”, “JohnDoe”, time() + (86400 * 30), “/”); // Expires in 30 days
?>
To retrieve a cookie:
php
CopyEdit
<?php
if(isset($_COOKIE[“user”])) {
echo “User is “. $_COOKIE[“user”];
} else {
echo “User cookie is not set.”;
}
?>
Cookies have limitations on size (usually 4KB) and should not store sensitive information.
Forms allow users to submit data to your PHP scripts. Data can be sent via the HTTP GET or POST methods.
Example form:
html
CopyEdit
<form method=”post” action=”process.php”>
Name: <input type=”text” name=”username”>
Email: <input type=”email” name=”email”>
<input type=”submit” value=”Submit”>
</form>
The action attribute specifies the PHP file that will process the form data.
In the process.php file, you access form data using the $_POST or $_GET superglobals , depending on the method used.
Example:
php
CopyEdit
<?php
$username = $_POST[‘username’];
$email = $_POST[’email’];
Echoo “Name: “. htmlspecialchars($username) . “<br>”;
echo “Email: ” htmlspecialchars($email);
?>
Using htmlspecialchars() prevents Cross-Site Scripting (XSS) attacks by converting special characters into HTML entities.
Always validate user input to ensure data integrity and security.
Basic validation example:
php
CopyEdit
<?php
if(empty($_POST[‘username’]) || empty($_POST[’email’])) {
echo “All fields are required.”;
} else if (!filter_var($_POST[’email’], FILTER_VALIDATE_EMAIL)) {
echo “Invalid email format.”;
} else {
echo “Form submitted successfully.”;
}
?>
Proper validation helps prevent injection attacks and ensures that the data format is correct.
To upload files, create a form with enctype=”multipart/form-data”:
html
CopyEdit
<form action=”upload.php” method=”post” enctype=”multipart/form-data”>
Select an image to upload:
<input type=”file” name=”fileToUpload”>
<input type=”submit” value=”Upload Image”>
</form>
The upload.php script processes the uploaded file:
php
CopyEdit
<?php
$target_dir = “uploads/”;
$target_file = $target_dir . basename($_FILES[“fileToUpload”][“name”]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// Check if file is an actual image
if(isset($_POST[“submit”])) {
$check = getimagesize($_FILES[“fileToUpload”][“tmp_name”]);
if($check !== false) {
echo “File is an image – “. $check[“mime”] . “.”;
$uploadOk = 1;
} else {
echo “File is not an image.”;
$uploadOk = 0;
}
}
// Check file size (limit to 500KB)
if ($_FILES[“fileToUpload”][“size”] > 500000) {
echo “Sorry, your file is too large.”;
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != “jpg” && $imageFileType != “png” &&
$imageFileType != “jpeg” && $imageFileType != “gif” ) {
echo “Sorry, only JPG, JPEG, PNG & GIF files are allowed.”;
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo “Your file was not uploaded.”;
// If everything is ok, try to upload the file
} else {
if (move_uploaded_file($_FILES[“fileToUpload”][“tmp_name”], $target_file)) {
echo “The file “. htmlspecialchars(basename($_FILES[“fileToUpload”][“name”])). ” has been uploaded.”;
} else {
echo “Sorry, there was an error uploading your file.”;
}
}
?>
Make sure the uploads directory exists inside your project folder and is writable
CRUD stands for Create, Read, Update, and Delete — the four basic functions to interact with a database.
Insert a new record into the database with SQL INSERT statements.
Example:
php
CopyEdit
<?php
$conn = new mysqli(“localhost”, “root”, “”, “testdb”);
$name = “John Doe”;
$email = “john@example.com”;
$sql = “INSERT INTO users (name, email) VALUES (‘$name’, ‘$email’)”;
if ($conn->query($sql) === TRUE) {
echo “New record created successfully”;
} else {
echo “Error: “. $conn->error;
}
$conn->close();
?>
Retrieve records using SELECT statements:
php
CopyEdit
<?php
$conn = new mysqli(“localhost”, “root”, “”, “testdb”);
$sql = “SELECT id, name, email FROM users”;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo “ID: ” $row[“id”]. ” Name: “. $row[“name”]. ” Email: ” . $row[“email”]. “<br>”;
}
} else {
echo “No records found”;
}
$conn->close();
?>
Modify existing records:
php
CopyEdit
<?php
$conn = new mysqli(“localhost”, “root”, “”, “testdb”);
$id = 1;
$newEmail = “newemail@example.com”;
$sql = “UPDATE users SET email=’$newEmail’ WHERE id=$id”;
if ($conn->query($sql) === TRUE) {
echo “Record updated successfully”;
} else {
echo “Error updating record: “. $conn->error;
}
$conn->close();
?>
Remove records from the database:
php
CopyEdit
<?php
$conn = new mysqli(“localhost”, “root”, “”, “testdb”);
$id = 1;
$sql = “DELETE FROM users WHERE id=$id”;
if ($conn->query($sql) === TRUE) {
echo “Record deleted successfully”;
} else {
echo “Error deleting record: “. $conn->error;
}
$conn->close();
?>
SQL Injection is one of the most common vulnerabilities in web applications. Use prepared statements or parameterized queries to prevent it.
Example using MySQLi prepared statements:
php
CopyEdit
<?php
$conn = new mysqli(“localhost”, “root”, “”, “testdb”);
$stmt = $conn->prepare(“SELECT * FROM users WHERE email = ?”);
$stmt->bind_param(“s”, $email);
$email = $_POST[’email’];
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row[‘name’];
}
$stmt->close();
$conn->close();
?>
Always sanitize user input before displaying it to prevent XSS attacks. Use functions like htmlspecialchars() when outputting data.
Validate file types and sizes, never trust file names or extensions alone, and store uploaded files outside the web root if possible.
Xdebug is a PHP extension that provides advanced debugging and profiling capabilities.
To enable Xdebug:
Once development is complete on your local XAMPP environment, you may want to deploy your project to a live web server.
Use the live server’s phpMyAdmin or command line tools to import your .sql file to restore the database structure and data.
Test the deployed application thoroughly for functionality, performance, and security issues.
Mastering PHP development with XAMPP enables you to build dynamic, database-driven websites efficiently on your local machine. XAMPP’s integrated environment simplifies managing Apache, PHP, and MariaDB so you can focus on coding and learning.
Understanding sessions, cookies, form handling, file uploads, and CRUD operations equips you to create fully functional web applications. Always prioritize security by validating inputs and using prepared statements.
Finally, practicing debugging and testing ensures your applications are robust and error-free before deploying to production servers.
With consistent practice and learning, you can develop professional-quality PHP applications ready for real-world use.
Popular posts
Recent Posts