Introduction

PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

Instead of lots of commands to output HTML (as seen in C or Perl), PHP pages contain HTML with embedded code that does something (in this case, output Hi, I'm a PHP script!). The PHP code is enclosed in special start and end processing instructions that allow jumping in and out of PHP mode.

What distinguishes PHP from something like client-side JavaScript is that the code is executed on the server, generating HTML which is then sent to the client. The client would receive the results of running that script, but would not know what the underlying code was. A web server can even be configured to process all HTML files with PHP, and then there's no way that users can tell that PHP is being used.

The best part about using PHP is that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid to read the long list of PHP's features. With PHP, almost anyone can get up and running and be writing simple scripts in no time at all. Although PHP's development is focused on server-side scripting, much more can be done with it. Read on, and see more in the What can PHP do? section, or go right to the introductory tutorial to jump straight to learning about web programming.

PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

Nice, but what does that mean? An example:

Example #1 An introductory example

            
              <!DOCTYPE html>
              <html>
                 <head>
                    <title>Example</title>
                  </head>
                 <body>
                <?php
                      echo "Hi, I'm a PHP script!";
                  ?>
                 </body>
              </html>
              
          

Instead of lots of commands to output HTML (as seen in C or Perl), PHP pages contain HTML with embedded code that does something (in this case, output Hi, I'm a PHP script!). The PHP code is enclosed in

special start and end processing instructions that allow jumping in and out of PHP mode

What distinguishes PHP from something like client-side JavaScript is that the code is executed on the server, generating HTML which is then sent to the client. The client would receive the results of running that script, but would not know what the underlying code was. A web server can even be configured to process all HTML files with PHP, and then there's no way that users can tell that PHP is being used.

The best part about using PHP is that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid to read the long list of PHP's features. With PHP, almost anyone can get up and running and be writing simple scripts in no time at all.

Although PHP's development is focused on server-side scripting, much more can be done with it. Read on, and see more in the What can PHP do? section, or go right to the introductory tutorial to jump straight to learning about web programming.

What can PHP do

Anything. PHP is mainly focused on server-side scripting, so it can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more.

There are two main areas where PHP scripts are used.

  • Server-side scripting. This is the most widely used and main target field for PHP. Three things are needed to make this work: the PHP parser (CGI or server module), a web server, and a web browser. All these can run on a local machine in order to just experiment with PHP programming. See the installation instructions section for more information.
  • Command line scripting. A PHP script can be run without any server or browser, only the PHP parser is needed to use it this way. This type of usage is ideal for scripts regularly executed using cron (on Unix or macOS) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks. See the section about Command line usage of PHP for more information.

PHP can be used on all major operating systems, including Linux, many Unix variants (including HP-UX, Solaris and OpenBSD), Microsoft Windows, macOS, RISC OS, and probably others. PHP also has support for most of the web servers today. This includes Apache, IIS, and many others. And this includes any web server that can utilize the FastCGI PHP binary, like lighttpd and nginx. PHP works as either a module, or as a CGI processor.

So with PHP, developers have the freedom of choosing an operating system and a web server. Furthermore, they also have the choice of using procedural programming or object-oriented programming (OOP), or a mixture of them both. PHP is not limited to outputting HTML.

PHP's abilities include outputting rich file types, such as images or PDF files, encrypting data, and sending emails. It can also output easily any text, such as JSON or XML. PHP can autogenerate these files, and save them in the file system, instead of printing it out, forming a server-side cache for dynamic content. One of the strongest and most significant features in PHP is its support for a wide range of databases. Writing a database-enabled web page is incredibly simple using one of the database specific extensions (e.g., for mysql), or using an abstraction layer like PDO, or connect to any database supporting the Open Database Connection standard via the ODBC extension. Other databases may utilize cURL or sockets, like CouchDB.

Basic Syntax

When PHP processes a file, it recognizes the opening and closing tags, <?php and ?>, to define the boundaries of PHP code execution. Content outside these tags is ignored by the PHP parser, allowing PHP to seamlessly embed in various document types. A whitespace character (space, tab, or newline) must follow

  1. <?php echo 'if you want to serve PHP code in XHTML or XML documents, use these tags'; ?>
  2. You can use the short echo tag to <?= 'print this string' ?>. It's equivalent to <?php echo 'print this string' ?>.
  3. <? echo 'this code is within short tags, but will only work '. 'if short_open_tag is enabled'; ?>

Output of the above example in PHP 8.4.4:

  1. if you want to serve PHP code in XHTML or XML documents, use these tags

  2. You can use the short echo tag to print this string. It's equivalent to print this string.

  3. this code is within short tags, but will only work if short_open_tag is enabled

Short tags (example three) are available by default but can be disabled either via the short_open_tag php.ini configuration file directive, or are disabled by default if PHP is built with the --disable-short-tags configuration

If a file ends with PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.

Example #2 PHP Code Only File

          
           <?php
echo "Hello world\n";

// ... more code

echo "Last statement\n";

// the script ends here with no PHP closing tag
          ?>
          
        

Types

Every single expression in PHP has one of the following built-in types depending on its value:

  • null

  • bool

  • int

  • float (floating-point number)

  • string

  • array

  • object

  • callable

  • resource

PHP is a dynamically typed language, which means that by default there is no need to specify the type of a variable, as this will be determined at runtime. However, it is possible to statically type some aspect of the language via the use of type declarations. Different types that are supported by PHP's type system can be found at the type system page.

Example #1 Different Types

          
            <?php
          $a_bool = true;   // a bool
          $a_str  = "foo";  // a string
          $a_str2 = 'foo';  // a string
          $an_int = 12;     // an int
          
          echo get_debug_type($a_bool), "\n";
          echo get_debug_type($a_str), "\n";
          
          // If this is an integer, increment it by four
          if (is_int($an_int)) {
              $an_int += 4;
          }
          var_dump($an_int);
          
          // If $a_bool is a string, print it out
          if (is_string($a_bool)) {
              echo "String: $a_bool";
          }
          ?>
          Run code
          Output of the above example in PHP 8:
          
          bool
          string
          int(16)
          
        

Variables

Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive. A valid variable name starts with a letter (A-Z, a-z, or the bytes from 128 through 255) or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$

Note: PHP doesn't support Unicode variable names, however, some character encodings (such as UTF-8) encode characters in such a way that all bytes of a multi-byte character fall within the allowed range, thus making it a valid variable name.

By default, variables are always assigned by value. That is to say, when an expression is assigned to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. For more information on this kind of assignment, see the chapter on Expressions.

PHP also offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa.

To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs 'My name is Bob' twice:

One important thing to note is that only variables may be assigned by reference.

            
              <php
$foo = 25;
$bar = &$foo;      // This is a valid assignment.
$bar = &(24 * 7);  // Invalid; references an unnamed expression.

function test()
{
   return 25;
}

$bar = &test();    // Invalid because test() doesn't return a variable by reference.
?>
            
          

It is not necessary to declare variables in PHP, however, it is a very good practice. Accessing an undefined variable will result in an E_WARNING (prior to PHP 8.0.0, E_NOTICE). An undefined variable has a default value of null. The isset() language construct can be used to detect if a variable has already been initialized. Example #4 Default value of an uninitialized variable

<php // Unset AND unreferenced (no use context) variable. var_dump($unset_var); ?>

PHP allows array autovivification (automatic creation of new arrays) from an undefined variable. Appending an element to an undefined variable will create a new array and will not generate a warning. Example #5 Autovivification of an array from an undefined variable

<?php $unset_array[] = 'value'; // Does not generate a warning. ?>

A variable can be destroyed by using the unset() language construct.

Constants

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren't actually constants). Constants are case-sensitive. By convention, constant identifiers are always uppercase. Note: Prior to PHP 8.0.0, constants defined using the define() function may be case-insensitive. The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$ It is possible to define() constants with reserved or even invalid names, whose value can only be retrieved with the constant() function. However, doing so is not recommended. Tip See also the Userland Naming Guide.

Expressions

Expressions are the most important building blocks of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value". The most basic forms of expressions are constants and variables. When you type $a = 5, you're assigning 5 into $a. 5, obviously, has the value 5, or in other words 5 is an expression with the value of 5 (in this case, 5 is an integer constant). After this assignment, you'd expect $a's value to be 5 as well, so if you wrote $b = $a, you'd expect it to behave just as if you wrote $b = 5. In other words, $a is an expression with the value of 5 as well. If everything works right, this is exactly what will happen.

Operators

An operator is something that takes one or more values (or expressions, in programming jargon) and yields another value (so that the construction itself becomes an expression). Operators can be grouped according to the number of values they take. Unary operators take only one value, for example ! (the logical not operator) or ++ (the increment operator). Binary operators take two values, such as the familiar arithmetical operators + (plus) and - (minus), and the majority of PHP operators fall into this category. Finally, there is a single ternary operator, ? :, which takes three values; this is usually referred to simply as "the ternary operator" (although it could perhaps more properly be called the conditional operator). A full list of PHP operators follows in the section Operator Precedence. The section also explains operator precedence and associativity, which govern exactly how expressions containing several different operators are evaluated.

Control Structures

Any PHP script is built out of a series of statements. A statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well. The various statement types are described in this chapter. (PHP 4, PHP 5, PHP 7, PHP 8) The if construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an if structure that is similar to that of C: The following example would display a is bigger than b if $a is bigger than $b: If statements can be nested infinitely within other if statements, which provides you with complete flexibility for conditional execution of the various parts of your program. Despite the indentation (which does not matter for PHP), the else is associated with the if ($b), so the example does not produce any output. While relying on this behavior is valid, it is recommended to avoid it by using curly braces to resolve potential ambiguities. (PHP 4, PHP 5, PHP 7, PHP 8)

Alternative syntax for control structures

PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively. <?php if ($a == 5): ?> A is equal to 5 <?php endif; ?> In the above example, the HTML block "A is equal to 5" is nested within an if statement written in the alternative syntax. The HTML block would be displayed only if $a is equal to 5. The alternative syntax applies to else and elseif as well. The following is an if structure with elseif and else in the alternative format: Whereas this is valid, as the trailing newline after the switch statement is considered part of the closing ?> and hence nothing is output between the switch and case:

Classes and Objects

PHP includes a complete object model. Some of its features are: visibility, abstract and final classes and methods, additional magic methods, interfaces, and cloning. PHP treats objects in the same way as references or handles, meaning that each variable contains an object reference rather than a copy of the entire object. See Objects and References. Basic class definitions begin with the keyword class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class. The class name can be any valid label, provided it is not a PHP reserved word. As of PHP 8.4.0, using a single underscore _ as a class name is deprecated. A valid class name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$. A class may contain its own constants, variables (called "properties"), and functions (called "methods"). Run code The pseudo-variable $this is available when a method is called from within an object context. $this is the value of the calling object

Security

PHP is a powerful language and the interpreter, whether included in a web server as a module or executed as a separate CGI binary, is able to access files, execute commands and open network connections on the server. These properties make anything run on a web server insecure by default. PHP is designed specifically to be a more secure language for writing CGI programs than Perl or C, and with correct selection of compile-time and runtime configuration options, and proper coding practices, it can give you exactly the combination of freedom and security you need. As there are many different ways of utilizing PHP, there are many configuration options controlling its behaviour. A large selection of options guarantees you can use PHP for a lot of purposes, but it also means there are combinations of these options and server configurations that result in an insecure setup. The configuration flexibility of PHP is equally rivalled by the code flexibility. PHP can be used to build complete server applications, with all the power of a shell user, or it can be used for simple server-side includes with little risk in a tightly controlled environment. How you build that environment, and how secure it is, is largely up to the PHP developer. This chapter starts with some general security advice, explains the different configuration option combinations and the situations they can be safely used, and describes different considerations in coding for different levels of security.

Handling file uploads

This feature lets people upload both text and binary files. With PHP's authentication and file manipulation functions, you have full control over who is allowed to upload and what is to be done with the file once it has been uploaded. PHP is capable of receiving file uploads from any RFC-1867 compliant browser. File upload progress bar can be implemented using Session Upload Progress.