Chapters What is PHP and what can it do? What is PHP? 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:
Hello World
This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display: Hello World using the PHP echo statement. Note that the file does not need to be executable or special in any way. The server finds out that this file needs to be interpreted by PHP because you used the ".php" extension, which the server is configured to pass on to PHP. Think of this as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things. The point of the example is to show the special PHP tag format. In this example we used ENTITY?php to indicate the start of a PHP tag. Then we put the PHP statement and left PHP mode by adding the closing tag, ?ENTITY. You may jump in and out of PHP mode in an HTML file like this anywhere you want. For more details, read the manual section on the basic PHP syntax. [!NOTE] Line feeds have little meaning in HTML; however, it is still a good idea to make your HTML look nice and clean by putting line feeds in. A line feed that follows immediately after a closing ?ENTITY will be removed by PHP. This can be extremely useful when you are putting in many blocks of PHP or include files containing PHP that aren't supposed to output anything. At the same time it can be a bit confusing. You can put a space after the closing ?ENTITY to force a space and a line feed to be output, or you can put an explicit line feed in the last echo/print from within your PHP block. [!NOTE] There are many text editors and Integrated Development Environments (IDEs) that you can use to create, edit and manage PHP files. A partial list of these tools is maintained at PHP Editors List. If you wish to recommend an editor, please visit the above page and ask the page maintainer to add the editor to the list. Having an editor with syntax highlighting can be helpful. [!NOTE] Word processors such as StarOffice Writer, Microsoft Word and AbiWord are not optimal for editing PHP files. If you wish to use one for this test script, you must ensure that you save the file as plain text or PHP will not be able to read and execute the script. Now that you have successfully created a working PHP script, it is time to create the most famous PHP script! Make a call to the phpinfo function and you will see a lot of useful information about your system and setup such as available predefined variables, loaded PHP modules, and configuration settings. Take some time and review this important information. Something Useful Let us do something more useful now. We are going to check what sort of browser the visitor is using. For that, we check the user agent string the browser sends as part of the HTTP request. This information is stored in a variable. Variables always start with a dollar-sign in PHP. The variable we are interested in right now is $_SERVER['HTTP_USER_AGENT']. [!NOTE] $_SERVER is a special reserved PHP variable that contains all web server information. It is known as a superglobal. See the related manual page on superglobals for more information. To display this variable, you can simply do: A sample output of this script may be: Mozilla/5.0 (Linux) Firefox/112.0 There are many types of variables available in PHP. In the above example we printed an element from an Array variable. Arrays can be very useful. $_SERVER is just one variable that PHP automatically makes available to you. A list can be seen in the Reserved Variables section of the manual or you can get a complete list of them by looking at the output of the phpinfo function used in the example in the previous section. You can put multiple PHP statements inside a PHP tag and create little blocks of code that do more than just a single echo. For example, if you want to check for Firefox you can do this: A sample output of this script may be: You are using Firefox. Here we introduce a couple of new concepts. We have an if statement. If you are familiar with the basic syntax used by the C language, this should look logical to you. Otherwise, you should probably pick up an introductory PHP book and read the first couple of chapters, or read the Language Reference part of the manual. The second concept we introduced was the str_contains function call. str_contains is a function built into PHP which determines if a given string contains another string. In this case we are looking for 'Firefox' (so-called needle) inside $_SERVER['HTTP_USER_AGENT'] (so-called haystack). If the needle is found inside the haystack, the function returns true. Otherwise, it returns ENTITY. If it returns ENTITY, the if expression evaluates to ENTITY and the code within its {braces} is executed. Otherwise, the code is not run. Feel free to create similar examples, with if, else, and other functions such as strtoupper and strlen. Each related manual page contains examples too. If you are unsure how to use functions, you will want to read both the manual page on how to read a function definition and the section about PHP functions. We can take this a step further and show how you can jump in and out of PHP mode even in the middle of a PHP block:You are using Firefox
You are not using Firefox
A sample output of this script may be:You are using Firefox
Instead of using a PHP echo statement to output something, we jumped out of PHP mode and just sent straight HTML. The important and powerful point to note here is that the logical flow of the script remains intact. Only one of the HTML blocks will end up getting sent to the viewer depending on the result of str_contains. In other words, it depends on whether the string Firefox was found or not. Dealing with Forms One of the most powerful features of PHP is the way it handles HTML forms. The basic concept that is important to understand is that any form element will automatically be available to your PHP scripts. Please read the manual section on Variables from external sources for more information and examples on using forms with PHP. Here is an example HTML form: There is nothing special about this form. It is a straight HTML form with no special tags of any kind. When the user fills in this form and hits the submit button, the action.php page is called. In this file you would write something like this: Hi . You are years old. A sample output of this script may be: Hi Joe. You are 22 years old. Apart from the htmlspecialchars and (int) parts, it should be obvious what this does. htmlspecialchars makes sure any characters that are special in HTML are properly encoded so people can't inject HTML tags or JavaScript into your page. For the age field, since we know it is a number, we can just convert it to an int which will automatically get rid of any stray characters. You can also have PHP do this for you automatically by using the filter extension. The $_POST['name'] and $_POST['age'] variables are automatically set for you by PHP. Earlier we used the $_SERVER superglobal; above we just introduced the $_POST superglobal which contains all POST data. Notice how the method of our form is POST. If we used the method GET then our form information would live in the $_GET superglobal instead. You may also use the $_REQUEST superglobal, if you do not care about the source of your request data. It contains the merged information of GET, POST and COOKIE data. What's next? With your new knowledge you should be able to understand most of the manual. In particular you may want to explore the following features: Reading and writing files with the filesystem functions, Handling file uploads, Fetching remote pages and files with Curl, Storing and analyzing data in a database with PDO (SQLite can be used without running a database server), Persisting data across requests with Sessions There's a trove of libraries and frameworks for every occasion on the Packagist repository, all installable via the Composer package manager. For community help and advice, check out the Help page. For a variety of podcasts, presentations and other videos, check out the community PeerTube. Other community resources that will help you include "awesome lists" (curated directories of links) and "developer roadmaps" (lists of related topics). When you're stuck with no idea where to start, try breaking down your project or problem into smaller parts, allowing you to more easily see what you already know how to do and what you need to learn. The list can be as deep / detailed as you need. For example, building a blog might be broken down into the following parts: Listing and viewing pages Reading records (pages) from a database Creating pages Handle form submission Writing records (pages) to a database Admin login Reading records (users) from a database Handling passwords Persisting data (user login) across requests / pages (sessions) If there's nothing particular you want to build, you can try searching for coding exercises such as katas, challenges and "code golf". Even when not specifically aimed at PHP, most should be completable and will likely challenge your knowledge and thinking.