Beginner php PHP 15 min read

Two Methods to Run PHP

Two Methods to Run PHP

Getting Started: Two Ways to Run Your PHP Code

Learning a new programming language can be exciting, and a great way to begin is by executing code and seeing the results immediately. This lesson introduces two primary approaches to running PHP programs: using an online coding environment and setting up a local development environment on your own computer. We’re going to explore both, allowing you to choose the method that best suits your learning style and project needs. Throughout this guide, you’re encouraged to experiment with both methods as we cover fundamental PHP concepts like displaying output, working with variables, and understanding different data types.

Online Coding with Replit

One of the simplest ways to begin coding in PHP is to leverage an online platform that handles the complexities of the underlying infrastructure. These environments eliminate the need to install and configure software, letting you focus on writing code. We's be using Replit (https://replit.com), a popular and free online service, for this initial exploration.

What is a REPL?

The name "Replit" is derived from "REPL," which stands for "Read-Evaluate-Print Loop." A REPL is a type of interactive computing environment where you input a command or expression, the system immediately processes it, displays the result, and then waits for your next input. Think of it like a command line terminal—you type a command, and the terminal executes it and returns a response.

Setting Up a Replit Project

To get started, visit the Replit website and create a free account. Once you're logged in, you’re ready to create your first PHP project.

Replit offers pre-configured templates specifically designed for PHP development. Two templates are particularly useful:

  • PHP CLI (Command Line Interface): Ideal for projects that primarily generate text output or process data files. This template is perfect for learning the basics without the overhead of a web server.
  • PHP Web Server: Designed for web development projects, allowing you to create and test PHP applications that interact with a web server.

Let's create a simple PHP CLI project to begin. From the Replit homepage, click the "Create Repl" button. A search box will appear; type "PHP" into the search box. You'll see the official Replit PHP CLI and PHP Web Server templates listed. (You might also see other templates created by users.)

Select the "PHP CLI" template and provide a name for your project. You can use the suggested random name if you prefer. Click "Create Repl" to launch your new project.

Replit will then initialize your project, which includes creating the project’s files and folders and starting a virtual machine in the cloud. This process takes a few moments. Once the project is fully loaded, you'll be presented with a three-column interface.

Executing Your First PHP Script

When you create a new PHP project in Replit, you're typically presented with a basic project setup. This includes a pre-populated file, often named main.php, that contains a simple "Hello, world!" script. This initial script serves a vital purpose in the learning process. It's a common practice when first exploring a new programming language, providing a quick way to confirm your environment is configured correctly and to familiarize yourself with the fundamentals.

The project interface in Replit usually divides the screen into three main areas. On the left, you'll find a file explorer, allowing you to navigate the project’s files and folders. The central pane offers a code editor where you'll write and modify your PHP code. Finally, the right-hand side displays the console output, providing a terminal and a shell interface for interacting with the virtual computer Replit has created. Pressing the "Run" button initiates the PHP interpreter, and any output from your script will appear in the console.

A typical PHP project is composed of one or more files. These files contain your PHP code and are distinguished by the .php extension. The main.php file in your initial project provides a starting point.

Here’s the boilerplate code you’re likely to see in main.php:

<?php
echo "Hello, world!\n";

Let's break down what this code does. The <?php at the beginning is called an opening PHP tag. It's essential; it tells the PHP interpreter that the following lines should be treated as PHP code. The echo statement is a core PHP command used to output text to the console. In this instance, it displays "Hello, world!" followed by a newline character (\n), which inserts a line break after the message. Successfully running this simple script confirms that your PHP environment is set up and functioning correctly.

Understanding How Your PHP Code Executes

When you see text displayed on the screen from your PHP code, it's the result of a series of steps. The text itself, like "Hello, world!", is represented as a string – a sequence of characters. We're going to delve deeper into strings and special characters later, but for now, it's important to know that strings are always enclosed in double quotes. The line of code that produces this output is a statement, which is a single instruction telling the computer to do something. Each PHP statement must end with a semicolon (;) – think of it as the punctuation mark that signals the end of the instruction. Without it, PHP won’t recognize the statement as complete.

The Role of the PHP Engine

When you click the "Run" button in Replit, what actually happens? PHP is a scripted language. This means that instead of being translated into machine code beforehand (like languages such as C++ or Swift), the code is interpreted and executed on the fly. A program called an interpreter handles this process; in PHP's case, it's known as the PHP engine. The PHP engine reads your .php file and translates its contents into instructions the computer can understand and carry out.

This contrasts with compiled languages. In those, a separate compilation step occurs before execution, transforming the source code into an executable file. Scripted languages like PHP, Python, and JavaScript offer a different approach to program execution.

Running PHP from the Command Line

The "Run" button in Replit provides a simple way to execute PHP code, but it's not the only option. You can also invoke the PHP engine directly from the command line. This is a very useful skill, especially when working outside of a development environment like Replit.

To try this out, switch to the "Shell" tab in your Replit project. This opens a command-line interface. At the $ prompt, type the following and press Enter:

php main.php

You should see "Hello, world!" printed to the terminal.

This command instructs the PHP engine to process and execute the main.php file. This method works not only in Replit but also on your own computer, allowing you to run PHP scripts independently of any web-based development environment. We'll be exploring the flow of control, which determines the order in which statements are executed, as we cover conditionals and loops in future lessons.

Setting Up a Basic Web Project with PHP

Since PHP is most often used to build web applications, let's create a simple web project using Replit's built-in PHP Web Server template. To do this, return to your Replit dashboard and create a new project. When prompted, search for and select the "PHP Web Server" template. This will set up a basic environment ready for PHP web development.

You'll notice a single file, named index.php, already present in the project's file structure. This index.php file holds a special significance in web development. It functions as the default page displayed when a user visits the root URL (the homepage) of a website. We'll delve into the intricacies of how this works later when we cover web programming fundamentals. For now, understand it's the starting point for your web application.

The contents of index.php are displayed in the editor pane. You'll also find Console and Shell tabs on the right side of the Replit interface. A Webview tab will appear here once you run the web server, allowing you to view the rendered web page.

Let's examine the code within index.php:

<html>
<head>
<title>PHP Test</title>
</head>
<body>
  <?php echo '<p>Hello World</p>'; ?>
</body>
</html>

The majority of the file is written in HTML, which provides the structure and layout for a standard web page. You’re likely familiar with HTML tags like <html>, <head>, <title>, and <body>. The opening and closing <html> tags mark the beginning and end of the entire HTML document. As we explore further, you'll see that PHP scripts often blend dynamic PHP code with static content like HTML.

The key line here is the PHP code: <?php echo '<p>Hello World</p>'; ?>. This line uses the echo statement to output the text "Hello World" within HTML paragraph (<p>) tags. The <?php and ?> tags delineate the PHP code block, telling the server to interpret this section as PHP. When the web server runs, this PHP code will be executed, and the resulting HTML will be sent to the user’s browser.

Running PHP: Two Approaches

While online environments like Replit are convenient for initial exploration, understanding how to execute PHP code is crucial. There are primarily two ways to run PHP scripts: using a web server environment and setting up a local development environment.

Running with a Web Server (Replit Example)

When you utilize Replit to execute your PHP code, the platform automatically launches a web server. This server hosts your index.php file and activates the PHP engine necessary to process the code within. Instead of seeing the output directly in the console, you're now presented with a simple webpage displaying "Hello World" in the Webview panel.

A unique characteristic of Replit’s web server is that it publishes temporary webpages accessible through a URL ending in .replit.dev. You can access this webpage directly by clicking the address bar in the Webview panel. A pop-up will reveal the unique URL. Copying and pasting this URL into a standard web browser (like Chrome, Firefox, or Safari) will render the "Hello World" message as a standalone webpage, completely separate from the Replit interface itself. This demonstrates your first, albeit simple, PHP-powered website being published online.

Note: As you progress to more complex projects later in this guide, you might encounter situations where additional configuration is needed within Replit. Detailed instructions for these configurations can be found in Appendix C.

Local PHP Development Environment

Online code editors provide ease of access, but they can be limited by slower performance (especially on free tiers) and a dependence on a stable internet connection. Many developers prefer a local development environment—running PHP directly on their own computers.

The first step in setting up a local environment is installing PHP. If you haven't already, consult Appendix A for instructions tailored to your specific operating system to install the latest version of PHP.

Once PHP is installed, you're ready to choose an Integrated Development Environment (IDE). An IDE is more than just a text editor; it’s a powerful tool equipped with features designed to streamline the development process. These features often include an integrated terminal, advanced search and replace capabilities, code completion, error detection, and even automated code generation for common programming tasks. Choosing an IDE that suits your workflow will greatly improve your productivity.

Setting Up Your Development Environment with PhpStorm

This section will guide you through setting up a local development environment using PhpStorm, a widely-used Integrated Development Environment (IDE) from JetBrains. While a fully paid license is available, PhpStorm offers a free 30-day trial, and many individuals – including students, educators, bootcamp participants, and contributors to open-source initiatives – are eligible for a permanent free license. You can download PhpStorm and find licensing details at [https://www.jetbrains.com/phpstorm/](https://www.jetbrains.com/phpstorm/). Follow the provided installation instructions to get it up and running on your system.

If PhpStorm doesn't appeal to you, don’t worry! Several other free IDEs, such as Visual Studio Code, Eclipse, and Apache NetBeans, provide plugins to support PHP development.

Creating Your First "Hello, world!" Project

Let’s begin by creating a basic "Hello, world!" project within PhpStorm. This mirrors the simplicity of a default PHP CLI template often found in online environments like Replit. To start, launch PhpStorm and select "New Project." From the available options, choose "PHP Empty Project." You’ll then be prompted to select a location to store your project files and to give it a name. It’s a good practice to include a forward slash (/) before the project name in the location path – for example, /my-php-project. Click "Create" to finalize the project setup.

PhpStorm will now generate a new folder, named according to your chosen project name, in the designated location. This folder acts as the central repository for all project files. As your projects grow in complexity, you’re likely to organize them further using subfolders to manage data, program logic, configuration settings, and other related assets. Once the folder is created, PhpStorm will open the project view, which provides the core editing interface.

The PhpStorm interface is typically divided into three main panels:

  • Project Contents Panel (Top-Left): This area displays the file and folder structure of your project, allowing you to navigate and manage your project’s assets.
  • Code/File Editing Panel (Top-Right): This is where you’re going to spend most of your time, as it's the area where you write and edit your PHP code and other project files.
  • Command Line Terminal (Bottom): To access a command-line terminal, click the "Terminal" button (often represented by a >_ symbol) located in the left-hand column of the PhpStorm window. This terminal provides a powerful way to interact with your project and system.

Running Your PHP Script: The Terminal Approach

Now that you've created a new PHP file, it's time to execute it and see the results. One common method is to use the terminal, also known as the command line. Your development environment likely has a terminal window that automatically opens and is focused on your project’s directory.

Let's create a simple program to get started. We'll use the classic "Hello, world!" example. Within your project, create a new file named hello.php. PhpStorm (or your chosen IDE) will automatically add the .php extension. The editor should automatically populate the file with the opening PHP tag: <?php.

Here's the code you're going to enter into hello.php:

<?php
print "Hello, world!\n";

This line instructs PHP to display the text "Hello, world!" followed by a newline character. The newline character (\n) ensures that the output appears on its own line in the terminal.

print vs. echo: Displaying Output

You may have noticed the use of print in this example. PHP also offers echo as an alternative way to output text. While there are subtle technical differences, for introductory programming, you can largely consider them interchangeable. The choice often boils down to personal preference. Some developers prefer print because the word better reflects the action of displaying something. Others may use echo due to its prevalence in older PHP code.

A key distinction is that, unlike functions in many other languages, print and echo in PHP aren't technically functions. This means you don't need to enclose the text you want to display within parentheses, although it's perfectly acceptable to do so.

Executing Your Script from the Terminal

To run your hello.php script, navigate to the terminal panel within your development environment. Then, type the following command and press Enter:

php hello.php

This command tells the PHP interpreter to process and execute the hello.php file. You should then see the output:

Hello, world!

displayed in the terminal window. Congratulations, you've just executed your first PHP script!

Running PHP Scripts: Alternative Methods and Local Web Servers

Beyond the debugging tools, PhpStorm (and most other IDEs) offers another straightforward way to execute your PHP code. Simply locate the green "Run" button—often situated near the debugging icon—at the top of the application window. Clicking this button will typically run the currently open file. If a dropdown menu appears presenting choices between PHP and JavaScript execution, be sure to select the PHP option.

When you run a script this way, a dedicated "Run" panel will appear at the bottom of your screen. This panel displays critical information, including the specific PHP engine being utilized and the complete path to the script being processed. This is particularly valuable if you have multiple PHP versions installed on your system, allowing you to easily verify compatibility. The panel will also show the script’s output, and a final exit code – a value of 0 signifies that the script executed successfully.

Utilizing PHP's Built-in Web Server

PHP installations include a convenient, integrated web server specifically designed for local development and testing. To quickly confirm that this web server is functioning correctly and to gather information about your PHP environment, use the phpinfo() function. This function generates a comprehensive HTML report detailing numerous aspects of your PHP configuration. Running a script containing phpinfo() is a standard initial step when setting up any PHP-based web project, whether on your local machine or a remote server.

Let's put this into practice. Create a new project folder named web_project_1 within your IDE. Inside this folder, create a new file named index.php. The name index.php is significant because web servers often serve this file by default when no specific file is requested. Populate this file with the following code:

<?php
phpinfo();
?>

This code snippet, starting with the opening PHP tag <?php, calls the phpinfo() function and displays its output. You can now view this detailed report as a formatted webpage. Within PhpStorm, select "View" then "Open in Browser" and choose "Built-in Preview". Alternatively, a small icon within the editing panel can also launch the web preview.

Running Your PHP Code: Two Simple Approaches

When you create a PHP file, you need a way to execute it and see the results. Fortunately, there are a couple of straightforward methods for doing so, particularly useful during development. Let's explore these approaches.

Using PhpStorm's Built-in Web Server

PhpStorm, a popular integrated development environment (IDE), provides a convenient built-in web server for testing your PHP projects. When you utilize this feature, PhpStorm automatically launches a miniature web server and displays the output of your index.php file within a sample browser window directly inside the IDE. This is a quick and easy way to see how your code behaves without needing to configure anything externally.

It's highly recommended to explore the displayed web page. This page often contains valuable information about your PHP environment, including the version of the PHP interpreter, the location of the crucial php.ini configuration file, a list of enabled database extensions (if any), and acknowledgements to the key developers behind PHP.

Using the Command-Line PHP Web Server

Alternatively, you can run PHP's built-in web server directly from your terminal or command prompt. This is an option regardless of your IDE and is often the only option if you aren't using PhpStorm or a similar IDE with a built-in server.

To start the server, open your IDE's terminal (or your system's command line) and type the following command:

php -S localhost:8000

Let's break down what this command does. php invokes the PHP interpreter. The -S flag tells PHP to start its built-in web server. localhost:8000 specifies the address and port the server will listen on. localhost refers to your own computer, and 8000 is the port number. Think of port numbers as specific channels for communication; each application that needs to send or receive data requires a unique port. For local development, ports like 8000 or 8080 are common choices, while production servers typically use port 80. I personally prefer using port 8000 for local development.

Once the server is running, open your preferred web browser (like Chrome or Firefox) and enter localhost:8000 into the address bar. You should then see the output from your PHP script.

To stop the server, simply return to the terminal window where you launched it and press Ctrl+C. This will gracefully terminate the web server process.

That concludes our look at two simple ways to execute and test your PHP code. Experiment with both methods to find the one that best suits your workflow.