A PHP script is a set of instructions written in the PHP programming language. These instructions are executed by a PHP interpreter, typically on a web server, to generate dynamic web content. PHP scripts are often embedded within HTML markup, allowing developers to create dynamic web pages that respond to user interactions or data changes.
PHP scripts are written in plain text files. The file name for a PHP script typically ends with the “.php” extension. This convention helps web servers recognize files that contain PHP code and ensure that they are processed appropriately by the PHP interpreter. For example, you might have files named “index.php”, “script.php”, or “contact.php”, depending on the functionality and purpose of the script.
Before we start, make sure to enable the usage of short open tags. Enabling short open tags in PHP allows developers to use the <?
and <? ?>
tags as shorthand for <?php
?>
.
Getting started with the first PHP script
To create your first PHP script, create a text file named index.php. PHP scripts are typically written in plain text files with the “.php” extension. To create your first PHP script, you can use an arbitrary text editor or Integrated Development Environment (IDE). A recommended free IDE for PHP development is Visual Studio Code. Visual Studio Code as a free option for PHP development offers a wide range of interesting PHP extensions to enhance the development experience by providing features such as syntax highlighting, code completion, debugging support, and more.
Create script
Create a PHP file (e.g. index.php), insert the provided code, and run the script.
index.php
<?php
// This is a PHP script
echo "Hello world!";
?>
This script uses the echo
statement to output the text “Hello, world!” to the web browser. When you open this script in a web browser, you’ll see the text displayed on the page. The line starting with //
is a comment. It serves as a brief description of the script’s purpose or functionality.
Run script
To execute the script, ensure that your PHP environment is installed, configured, and running. Open your web browser and enter the following text into the address bar.
http://localhost/index.php
You can also run your PHP script from the command line interface (CLI). Open the terminal or command prompt. Go to the directory where your PHP script is located. Run the PHP script with the following command:
php index.php
Using short open tags
With short open tags enabled in PHP, you can write the code using <?
as the opening tag, like this:
<?
// This is a PHP script
echo "Hello world!";
?>
You can also omit the closing ?>
tag, like this:
<?
// This is a PHP script
echo "Hello world!";
Conclusion
This was a quick introduction to get you started with PHP programming.