This draft deletes the entire topic.
Examples
-
PHP can be used to add content to HTML files. While HTML is processed directly by a web browser, PHP scripts are executed by a web server and the resulting HTML is sent to the browser. The following HTML markup contains a PHP statement that will add
Hello World!
to the output:<!DOCTYPE html> <html> <head> <title>PHP!</title> </head> <body> <p><?php echo "Hello world!"; ?></p> </body> </html>
When this is saved as a PHP script and executed by a web server, the following HTML will be sent to the user's browser:
<!DOCTYPE html> <html> <head> <title>PHP!</title> </head> <body> <p>Hello world!</p> </body> </html>
echo
also has a shortcut syntax, which lets you immediately print a value. Prior to PHP 5.4.0, this short syntax only works with the short_open_tag configuration setting enabled. For example,<p><?= "Hello world!" ?></p>
is same as the below line:
<p><?php echo "Hello world!"; ?></p>
In real-world applications, this shorthand syntax should only be used in templates, with properly escaped values to prevent Cross-Site-Scripting attacks.
See also: Strings and PSR-1, which describes best practices, including the proper use of short tags (
<?= ... ?>
). -
Two popular widely used language constructs to print output in PHP are
echo
andprint
.<?php echo "Hello, World!\n"; print "Hello, World!\n";
Both statements perform the same function, even though there are minor differences:
echo
has avoid
return, whilstprint
returns a type ofint
with a value of1
echo
can take multiple arguments (without parentheses only), whilstprint
only takes one argumentecho
is theoretically faster thanprint
because it has no return value, resulting in less overhead (see the answer Reference: Comparing PHP's print and echo for more information). The performance difference is negligible, however, and will have no noticeable difference on application speed.
Because
echo
andprint
are language constructs, not functions, they do not require parentheses around their arguments. For cosmetic consistency with other functions, the parentheses can be included.echo
can accept multiple arguments, separated by commas, but only if no parentheses are used.Standard C-style
printf
and related functions are available as well, as in the following example:<?php printf("%s\n", "Hello, World!");
Save this code to a file,
hello_world.php
, and run it through the PHP interpreter:> php hello_world.php Hello, World!
See outputting a variable for a comprehensive introduction of outputting variables in PHP.
-
-
In some cases, when working with a web server, overriding the web server's default content type may be required. There may be cases where you need to send data as
plain text
,JSON
, orXML
, for example.The
header()
function can send a raw HTTP header.
We'll add theContent-Type
header to notify the browser of the content we are sending.The following will send a
text/plain
header (to output plain text):<?php header("Content-Type: text/plain"); echo "Hello World"; ?>
You can render a
JSON
response by sending theapplication/json
content type:<?php header("Content-Type: application/json"); // Create a PHP data array. $data = ["response" => "Hello World"]; // json_encode will convert it to a valid JSON string. echo json_encode($data); #> {"response":"Hello World"} ?>
The
header()
function must be called before PHP produces any output, or the web server will have already sent headers for the response. This code will produce a warning:<?php // Error: We cannot send any output before the headers echo "Hello"; // All headers must be sent before ANY PHP output header("Content-Type: text/plain"); echo "World"; ?>
will give you a typical warning:
Warning: Cannot modify header information - headers already sent by (output started at /dir/example.php:2) in /dir/example.php on line 3
Note that when using
header()
, its output needs to be the first byte that's sent from the server. For this reason it's important to not have empty lines or spaces in the beginning of the file before the PHP opening tag<?php
. For the same reason, it is considered best practice (see PSR-2) to omit the PHP closing tag?>
from files that contain only PHP and from blocks of PHP code at the very end of a file.View the output buffering section to learn how to 'catch' your content into a variable to output later, for example, after outputting headers.
-
PHP can also be run from command line directly using the CLI (Command Line Interface).
CLI is basically the same as PHP from web servers, except some differences in terms of standard input and output.
Triggering
The PHP CLI allows four ways to run PHP code:
- Standard input. Run the
php
command without any arguments, but pipe PHP code into it:echo '<?php echo "Hello world!";' | php
- Filename as argument. Run the
php
command with the name of a PHP source file as the first argument:php hello_world.php
- Code as argument. Use the
-r
option in thephp
command, followed by the code to run. The<?php
open tags are not required, as everything in the argument is considered as PHP code:php -r 'echo "Hello world!";'
- Interactive shell. Use the
-a
option in thephp
command to launch an interactive shell. Then, type (or paste) PHP code and hit return:$ php -a Interactive mode enabled php > echo "Hello world!"; Hello world!
Output
All functions or controls that produce HTML output in web server PHP can be used to produce output in the stdout stream (file descriptor 1), and all actions that produce output in error logs in web server PHP will produce output in the stderr stream (file descriptor 2).
Example.php
Shell command line<?php echo "Stdout 1\n"; trigger_error("Stderr 2\n"); print_r("Stdout 3\n"); fwrite(STDERR, "Stderr 4\n"); throw new RuntimeException("Stderr 5\n"); ?> Stdout 6
$ php Example.php 2>stderr.log >stdout.log;\ > echo STDOUT; cat stdout.log; echo;\ > echo STDERR; cat stderr.log\ STDOUT Stdout 1 Stdout 3 STDERR Stderr 4 PHP Notice: Stderr 2 in /Example.php on line 3 PHP Fatal error: Uncaught RuntimeException: Stderr 5 in /Example.php:6 Stack trace: #0 {main} thrown in /Example.php on line 6
Input
- Standard input. Run the
-
Just like most other C-style languages, each statement must be terminated with a semicolon. Also, a closing tag and/or semicolon may be used to terminate the last line of code of the PHP block. That is, if the last line of PHP code is ended with a semicolon, the closing tag is optional if there is no code following that final line of code, refer to examples (A) and (B). If the last line of code has a closing tag, it does not need to be preceded by a semicolon, refer to examples (C) and (D).
Example (A):
<?php echo "No error"; // no closing tag is needed as long as there is no code below
Example (B):
<?php echo "This will cause an error"; // this needs a closing tag <html> <body> </body> </html>
Example (C):
<?php echo "I hope this helps! :D"; echo "No error" ?>
Example (D):
<?php echo "Having both semicolon and a closing tag also works!"; ?>
-
PHP 5.4+ comes with a built-in development server. It can be used to run applications without having to install a production HTTP server such as nginx or Apache. The built-in server is only designed to be used for development and testing purposes.
It can be started by using the
-S
flag:php -S <host/ip>:<port>
To test it, create an
index.php
file containing<?php echo "Hello World from built-in PHP server";
and run the command
php -S localhost:8080
from the command line (do not includehttp://
).This will start a web server listening on port 8080 using the current directory that you are in as the document root.
Open the browser and navigate to
http://localhost:8080
. You should see your 'Hello World' page.To override the default document root i.e. the current directory, you can do this.
php -S <host/ip>:<port> -t <directory>
e.g. if you have a
public/
directory in your project you can serve your project from that directory by doingphp -S localhost:8080 -t public/
.Every time a request is made from the development server, a log entry like the one below is written to the command line.
[Mon Aug 15 18:20:19 2016] ::1:52455 [200]: /
-
There are three kinds of tags to denote PHP blocks in a file. The PHP parser is looking for the opening and closing tags to get the code to interpret.
Standard Tags
These tags are the most used and highly recommended to embed PHP code in a file. These tags are always available.
<?php echo "Hello World"; ?>
Echo Tags
These tags are available in all PHP versions and since PHP 5.4 are always enabled. You don't have to enable Short Tags in order to make the Echo Tags enabled.
<?php $hello="Hello World"; ?> <?= $hello; ?> //is the same as either of <? echo $hello; ?> <?php echo $hello; ?>
Short Tags
You can disable or enable these tags with the option
short_open_tag
. If you want to use XML text on your file you have to disable the Short Tags.<? echo "Hello World"; ?>
Short tags are discouraged in the official documentation, and in some distributions the
short_open_tag
option is off by default (for example, if you install PHP via apt in Debian,short_open_tag
is off until you change it inphp.ini
.)
Remarks
PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source programming language. It is especially suited for web development. The unique thing about PHP is that it serves both beginners as well as experienced developers. It has low barrier to entry so it is easy to get started with, and at the same time, it provides advanced features offered in other programming languages.
Open-Source
It's an open-source project. Feel free to get involved.
Language Specification
PHP has a language specification.
Supported Versions
Currently, there are two supported versions: 5.6 and 7.0.
Each release branch of PHP is fully supported for two years from its initial stable release. After this two year period of active support, each branch is then supported for an additional year for critical security issues only. Releases during this period are made on an as-needed basis: there may be multiple point releases, or none, depending on the number of reports.
Unsupported Versions
Once the three years of support are completed, the branch reaches its end of life and is no longer supported.
A table of end of life branches is available.
Issue Tracker
Bugs and other issues are tracked at https://bugs.php.net/.
Mailing Lists
Discussions about PHP development and usage are held on the PHP mailing lists.
Official Documentation
Please help maintaining or translating the official PHP documentation.
You might use the editor at edit.php.net. Check out our guide for contributors.
Versions
Version | Supported Until | Release Date |
---|---|---|
7.1 | 2019-12-01 | 2016-12-01 |
7.0 | 2018-12-03 | 2015-12-03 |
5.6 | 2018-12-31 | 2014-08-28 |
5.5 | 2016-07-21 | 2013-06-20 |
5.4 | 2015-09-03 | 2012-03-01 |
5.3 | 2014-08-14 | 2009-06-30 |
5.2 | 2011-01-06 | 2006-11-02 |
5.1 | 2006-08-24 | 2005-11-24 |
5.0 | 2005-09-05 | 2004-07-13 |
4.4 | 2008-08-07 | 2005-07-11 |
4.3 | 2005-03-31 | 2002-12-27 |
4.2 | 2002-09-06 | 2002-04-22 |
4.1 | 2002-03-12 | 2001-12-10 |
4.0 | 2001-06-23 | 2000-05-22 |
3.0 | 2000-10-20 | 1998-06-06 |
2.0 | 1997-11-01 | |
1.0 | 1995-06-08 |
In italic: Presumably supported until.
Topic Outline
- HTML output from web server
- Hello, World!
- Non-HTML output from web server
- PHP CLI
- Instruction Separation
- PHP built-in server
- PHP Tags
Versions
Sign up or log in
Save edit as a guest
Join Stack Overflow
Using Google
Using Facebook
Using Email and Password
We recognize you from another Stack Exchange Network site!
Join and Save Draft