Category: Basic

  • Comments

    A comment in any computer program (such as a PHP program) is a certain explanatory text that is ignored by the language compiler/interpreter. Its purpose is to help the user understand the logic used in the program algorithm.

    Although placing comments in the code is not essential, it is a highly recommended practice. The comments also serve as program documentation. Comments are also useful when the code needs to be debugged and modified.

    Types of Comments in PHP

    There are two commenting formats in PHP −

    • Single-line Comments
      • Single-line Comments Using “#”
      • Single-line Comments Using “//”
    • Multi-line Comments
    • DocBlock comments (for documentation)

    PHP Single-line Comments

    They are generally used for short explanations or notes relevant to the local code. PHP uses two notations for inserting a single-line comment in a program.

    Single-line Comments Using “#”

    A line in PHP code starting with the “#” symbol is treated as a single-line comment.

    <?php
       # Single line comment starting with # symbol
       echo 'Hello World';
    ?>

    Single-line Comments Using “//”

    PHP also supports C style of single-line comments with “//” symbol. A line starting with double oblique symbol is treated as a comment.

    <?php
       // Single line comment starting with // symbol
       echo 'Hello World';
    ?>

    A comment that starts with the symbol “#” or “//” need not be closed. The effect of these symbols last till the end of the physical line.

    In other words, the PHP parser will treat the next line as a PHP statement and not as a comment even if there is no closing comment marker.

    PHP Multi-line Comments

    Multi-line comments are generally used to provide pseudocode algorithms and more detailed explanations when necessary.

    The multiline style of commenting is the same as in C. One or more lines embedded inside the “/*” and “*/” symbols are treated as a comment.

    Example of Multi-line Comment in PHP

    Here is the example of a multi-line comment.

    <?php
    
       /* This is a multiline comment example
       program to add two numbers
       Variables used - $x for first number, 
       $y for second number */
       
       $x=10;
       $y=20;
       print "Total = ". $x+$y;
    ?>

    Note that you can put even a single line inside the “/* .. */” symbols. However, if there is a “/*” symbol in the program, it must have a closing end-of comment marker “*/”. If not, an error will be displayed as follows −

    PHP Parse error:  Unterminated comment starting line 3 in /home/cg/root/65ded9eeb52fc/main.php on line 3

    PHP DocBlock comment (for documentation)

    A “DocBlock comment” is a type of code comment that usually starts with “/*” and uses asterisks () on each line to give detailed documentation about a particular code component like a function, class, or variable, which allows developers to easily understand its meaning and usage; it is commonly used with tools that generate API documentation automatically.

    Below is the example of a DocBlock comment.

    /**
     * This function adds two numbers.
     *
     * @param int $a First number
     * @param int $b Second number
     * @return int Sum of $a and $b
     */functionadd($a,$b){return$a+$b;}

    Useful Tips for Comments

    Here are some useful tips for writing better comments in PHP −

    • Always write comments for others, not yourself because always assume that another developer will read your code.
    • You should use proper english and grammar by avoiding shorthand, typos or ambiguous words. Because well written comments improve readability.
    • Do not comment the obvious if the code is self-explanatory, comments are unnecessary.
    • You can also mark areas that need improvement or debugging.
    • You should keep comments above the code block they refer to.
    • Update comments whenever the code changes.
    • Suppose if a function has a complex logic so you should explain it in detail by using the Block Comments.
    • You should always use the DocBlocks for functions and classes.
  • Hello World

    Conventionally, learners write a “Hello World” program as their first program when learning a new language or a framework. The objective is to verify if the software to be used has been installed correctly and is working as expected. To run a Hello World program in PHP, you should have installed the Apache server along with PHP module on the operating system you are using.

    PHP is a server-side programming language. The PHP code must be available in the document root of the web server. The web server document root is the root directory of the web server running on your system. The documents under this root are accessible to any system connected to the web server (provided the user has permissions). If a file is not under this root directory, then it cannot be accessed through the web server.

    Setting Up XAMPP for PHP Development

    In this tutorial, we are using XAMPP server software for writing PHP code. The default document root directory is typically “C:\xampp\htdocs\” on Windows and “/opt/lamp/htdocs/” on Linux. However, you can change the default document root by modifying the DocumentRoot setting in Apache server’s configuration file “httpd.conf”.

    Starting the Apache Server on Windows

    While on a Windows operating system, start the Apache server from the XAMPP control panel.

    PHP Hello World

    Creating and Saving the PHP Script

    First, locate the htdocs folder on your computer. This folder is where your web server (such as XAMPP) looks for PHP files. Next, add a new file to the htdocs folder. Name the file hello.php.

    Open this file with a text editor (such as Notepad, Visual Studio Code, or Sublime Text). In the file, enter the following PHP code:

    <?php
       echo "Hello World!";
    ?>

    Open a new tab in your browser and enter http://localhost/hello.php as the URL. You should see the “Hello World” message in the browser window.

    Mixing HTML and PHP in a Script

    PHP allows you to write both HTML and PHP code within the same file. This means that you can create a webpage in HTML and then add dynamic content with PHP. By combining HTML with PHP, you can create dynamic web pages that respond to user input or database content.

    <!DOCTYPE html><html><body><h1>My PHP Website</h1><?php
    
      echo "Hello World!";
    ?></body></html>

    The “Hello World” message will be rendered as a plain text. However, you can put HTML tags inside the “Hello World” string. The browser will interpret the tags accordingly.

    In the following code, the “echo” statement renders “Hello World” so that it is in <h1> heading with the text aligned at the center of the page.

    <?php
       echo "<h1 align='center'>Hello World!</h1>";
    ?>

    PHP Script from Command Prompt

    You can run your PHP script from the command prompt. Let’s assume you have the following content in your “hello.php” file.

    <?php
       echo "Hello PHP!!!!!";
    ?>

    Add the path of the PHP executable to your operating system’s path environment variable. For example, in a typical XAMPP installation on Windows, the PHP executable “php.exe” is present in “c:\xampp\php” directory. Add this directory in the PATH environment variable string.

    Now run this script as command prompt −

    C:\xampp\htdocs>php hello.php 
    

    You will get the following output −

    Hello PHP!!!!!
  • Syntax

    The syntax rules of PHP are very similar to C Language. PHP is a server side scripting language. A PHP code is stored as a text file with “.php” extension. A ‘.php’ file is essentially a web page with one or more blocks of PHP code interspersed in the HTML script.

    However, it should be opened in a browser with a HTTP protocol URL. In other words, if you double-click on the PHP file icon, it will be opened locally with the file protocol. For example, if you open the “index.php” file in the document root folder of your Apache server, it may just show the text of the PHP code. But, if you launch the Apache server and open the URL http://localhost/index.php, it displays the Apache home page.

    PHP Tags

    PHP defines two methods of using tags for escaping the PHP code from HTML. See below −

    • Canonical PHP tags
    • Short-open (SGML-style) tags

    Canonical PHP Tags

    Canonical PHP tags are commonly used to include PHP code within an HTML file. These tags start with ‘<?php’ and end with ‘?>’. This is the finest and widely used method of creating PHP code because it works on all servers and requires no further configuration. The most universally effective PHP tag style is −

    <?php
       echo "Hello World!";
    ?>

    If you use this approach, you can be positive that your tags will always be correctly interpreted.

    Short-open (SGML-style) Tags

    Short-open tags are a shorter way to write PHP code. They start with ‘<?’ and end with ‘?>’. These tags may not work on all servers unless the PHP configuration file’s short_open_tag argument is enabled. Short or short-open tags look like this −

    <?php
    	echo "Hello Everyone!";
    ?>

    Short tags are, as one might expect, the shortest option. You must do one of two things to enable PHP to recognize the tags −

    • Choose the “–enable-short-tags” configuration option when you’re building PHP.
    • Set the “short_open_tag” setting in your php.ini file to on.
    short_open_tag=on
    

    This option must be disabled to parse XML with PHP because the same syntax is used for XML tags.

    The use of ASP-style tags −

    <%...%>

    and HTML script tags −

    <script language ="PHP">...</script>

    has been discontinued.

    Escaping from HTML

    The PHP parser ignores everything outside of a pair of opening and closing tags. Thus, a PHP file can have mixed content. This allows PHP to be embedded in HTML documents −

    <p>This is a HTML statement</p><?php echo This is a PHP statement.'; ?><p>This is another HTML statement.</p>

    A little advanced example of escaping using conditions is shown below −

    <?php if ($expression == true): ?>
    
      This HTML statement will be rendered.
    <?php else: ?>
      Otherwise this HTML statement will be rendered.
    <?php endif; ?>

    PHP skips the blocks where the condition is not met, even though they are outside of the PHP open/close tags.

    For outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the text through echo or print.

    Basic Syntax of PHP

    The basic syntax of PHP is very similar to that of C and C++.

    Statements in PHP

    A statement in PHP is any expression that is followed by a semicolon (;). Any sequence of valid PHP statements that is enclosed by the PHP tags is a valid PHP program.

    Here is a typical statement in PHP, which in this case assigns a string of characters to a variable called “$greeting” −

    $greeting="Welcome to PHP!";

    A physical line in the text editor doesn’t have any significance in a PHP code. There may be multiple semicolon-terminated statements in a single line. On the other hand, a PHP statement may spill over more than one line if required.

    Expressions in PHP

    An expression is a combination of values, variables, and operators that produces a result. Tokens are the most basic building blocks of PHP. For example −

    • Numbers (3.14159)
    • Strings (“Hello”)
    • Variables ($name)
    • Constants (TRUE, FALSE)
    • Keywords (if, else, while, for, etc.)

    Braces ({}) for blocks

    Although statements cannot be combined like expressions, you can always put a sequence of statements anywhere a statement can go, by enclosing them in a set of curly braces.

    Here, both the following statements are equivalent −

    if(3==2+1)print("Good - I haven't totally lost my mind.");if(3==2+1){print("Good - I haven't totally");print("lost my mind.<br>");}

    PHP Case Sensitivity

    PHP is a case sensitive language. The names of various PHP identifiers such as variable, function, class, etc., are case sensitive. As a result, the variable “$age” is not the same as “$Age”.

    Variables are case-sensitive in PHP −

    $age=25;// Error: Undefined variable $Ageecho$Age;

    Here, $age and $Age are different variables.

    PHP and Other Web Technologies

    A “.php” file may contain HTML, CSS and JavaScript code blocks along with the PHP code. Hence, the PHP parser must differentiate between the PHP code from the other elements. When a “.php” file is opened in the web browser, the HTML engine renders the HTML/CSS/JavaScript part and escapes out of the HTML block as soon as the statements included in PHP tags are encountered. The PHP parser interpreter processes this block and returns the response to the browser.

    PHP Syntax

  • Features

    PHP (Hypertext Preprocessor) is an open-source server-side scripting language primarily used for web development. PHP can be embedded into HTML code.

    PHP is mainly used for server-side scripting, which runs scripts on the web server and then forwards the HTML they process to the web browser on the client. This makes it possible for programmers to design dynamic webpages that can manage sessions, handle forms, communicate with databases, and carry out a variety of other duties necessary for online applications.

    Features of PHP

    Over the years, PHP has incorporated numerous features. It is being consistently upgraded with new features and code revisions. In this chapter, let’s highlight some of the key features of PHP:

    PHP Features

    PHP is Simple and Easy to Learn

    The syntax of PHP compared to that of C, Java, and Perl, which makes it rather simple for developers to comprehend, particularly for those who are already familiar with other programming languages. Web apps can be developed quickly because of its generous pre-defined functions.

    PHP is Open Source

    PHP is free and open-source, meaning we can download it for free, and anyone can use it, modify it, and distribute. This encourages a sizable and vibrant developer community that uses forums, tutorials, and documentation to support and contribute to its development.

    PHP is Cross-Platform Compatible

    Numerous operating systems including Windows, Linux, macOS, and UNIX; and different databases like MongoDB, PostgreSQL, MySQL are compatible with PHP.

    PHP-based apps can operate on several environments without requiring any modifications due to this cross-platform inter-operability.

    Server-Side Scripting in PHP

    PHP is mainly used for server-side scripting, which runs scripts on the web server and then forwards the HTML they process to the web browser on the client. It helps the developers in Form Submission and Session Management with users across multiple requests.

    PHP Supports Easy Integration with Databases

    PHP offers strong database interaction support for various DBMS. It offers numerous built-in functions to achieve the database connection.

    PHP also includes database abstraction layer which integrates the communication between the application and the database. This makes it simple for developers to design database-driven web applications.

    PHP Provides Extensive Library Support

    PHP provides extensive libraries for various functionalities like image processing, encryption, PDF generation, parsing XML and JSON, handling sessions and cookies, and much more.

    Security Features in PHP

    PHP provides a plethora of built-in functions for data encryption. Developers can also leverage third-party applications for security.

    PHP employs security algorithms like Sha1 and MD5 to encrypt strings. Additionally, functions like filter_var and strip_tags contribute in maintaining a secure environment for the users. PHP also supports secure communication protocols like HTTPS.

    Efficient Memory and Session Management in PHP

    PHP is a reliable language due to its efficient memory management and session management. It avoids unnecessary memory allocation.

    PHP code runs in its own memory space which makes it faster compared to other scripting languages making it more efficient. In PHP, the database connections are also fast.

    PHP Has Active Community and Support

    Since PHP is an open-source platform, it has a vibrant community of developers who actively contribute to its development, share knowledge, provide support, and create third-party tools and frameworks.

    Due to this active community support, PHP remains up-to-date and developers can easily seek help from other community members in case they get any errors or exceptions while writing PHP codes.

  • History

    PHP started out as a small open-source project that evolved gradually as more and more people found out how useful it was. Rasmus Lerdorf released the first version of PHP way back in 1994. At that time, PHP stood for Personal Home Page, as he used it to maintain his personal homepage.

    Later on, he added database support and called it as “Personal Home Page/Forms Interpreter” or PHP/FI, which could be used to build simple, dynamic web applications.

    • PHP has gone through many versions since its first release in 1995. PHP 1.0 introduced in 8 June 1995, created by Rasmus Lerdorf. Mainly developed to track visits to his online resume. Then PHP 2.0 (1 November 1997) is the first version recognized as a standalone scripting language which included form handling, database support and built-in variables.
    • Zeev Suraski and Andi Gutmans rewrote the parser in 1997 and formed the base of PHP 3. The name of the language was also changed to the recursive acronym PHP: Hypertext Preprocessor. They are also the authors of Zend Engine, a compiler and runtime environment for the PHP. Zend Engine powered PHP 4 was released in May 2000.
    • PHP 5 was released in 2004, which included many new features such as OOP support, the PHP Data Objects (PDO), and numerous performance enhancements.
    • PHP 7, is a new major PHP version which was developed in 2015. It included new language features, most notable being, the introduction of return type declarations for functions which complement the existing parameter type declarations, and support for the scalar types (integer, float, string, and boolean) in parameter and return type declarations.

    New Features in PHP 8

    PHP 8 is the latest major version, released in November 2020. Some of the new features and notable changes include:

    Just-in-time (JIT) Compilation

    PHP 8’s JIT compiler provides substantial performance improvements mathematical-type operations than for common web-development use cases. The JIT compiler provides the future potential to move some code from C to PHP.

    Match Expressions

    The newly introduced “match” expression is more compact than a switch statement. Because match is an expression, its result can be assigned to a variable or returned from a function. The example is as follows −

    <?php
       $num = 2;
       echo match($num) {
    
      1 =&gt; "One",
      2 =&gt; "Two",
      3 =&gt; "Three",
      default =&gt; "Other",
    }; ?>

    Union types

    A union type accepts values from multiple types rather than just one. Union types are also useful in a variety of circumstances because of PHP’s dynamic type system. Union types are a collection of two or more types that can be used equally. Here is the example of union types −

    functionprintData(int|string$data){echo$data;}

    Named Arguments

    Instead of passing values in order, you can use names. Here is the example fot named arguments −

    functiongreet($name,$age){echo"Hello, $name. You are $age years old.";}greet(age:25,name:"Alia");

    Attributes (Annotations)

    It is a new way to add metadata to code. It makes code cleaner than using comments. Below is th example −

    #[CustomAttribute]classMyClass{}

    Static return type

    Functions can only return static (non-changing) values. It helps with class inheritance. Static is a special class name that, along with self and parent, is now a valid return type in the new version.

    WeakMap

    WeakMaps are a new feature in PHP 8. It behaves similarly to a regular array or dictionary, but it does not keep objects in memory that are no longer needed. Here is the basic example for this feature −

    classFooBar{privateWeakMap$cache;publicfunctiongetSomethingWithCaching(object$obj){return$this->cache[$obj]??=$this->computeSomethingExpensive($obj);}// ...}

    PHP 8 – Type Changes and Additions

    PHP 8 introduced union types, a new static return type, and a new mixed type. PHP 8 also provided Attributes, (similar to “annotations” in other programming languages) that help in adding metadata to PHP classes.

    In addition, there have been many changes and additions to the PHP standard library. PHP 8.2.9 is the latest stable version available.

    Important milestones in PHP’s release history are summarized in the following table −

    VersionDescription
    Version 1.0
    (8 June 1995)
    Officially called “Personal Home Page Tools (PHP Tools)”. This is the first use of the name “PHP”.
    Version 2.0
    (1 November 1997)
    Officially called “PHP/FI 2.0”. This is the first release that could actually be characterised as PHP, being a standalone language with many features that have endured to the present day.
    Version 3.0
    (6 June 1998)
    Development moves from one person to multiple developers.Zeev Suraski and Andi Gutmans rewritten the base for this version.
    Version 4.0
    (22 May 2000)
    Added more advanced two-stage parse/execute tag-parsing system called the Zend engine.
    Version 5.0
    (13 July 2004)
    Zend Engine II with a new object model.
    Version 5.1
    (24 November 2005)
    Performance improvements with the introduction of compiler variables in re-engineered PHP Engine.Added PHP Data Objects (PDO) as a consistent interface for accessing databases.
    Version 6.x
    Not released
    Abandoned version of PHP that planned to include native Unicode support.
    Version 7.0
    (3 December 2015)
    Zend Engine 3 ,Uniform variable syntax,Added Closure:call(),?? (null coalesce) operator,Return type declarations,Scalar type declarations,<=> “spaceship” three-way comparison operator,Anonymous classes
    Version 7.3
    (6 December 2018)
    Flexible Heredoc and Nowdoc syntax
    Version 8.0
    (26 November 2020)
    Just-In-Time (JIT) compilation,Arrays starting with a negative index,TypeError on invalid arithmetic/bitwise operators,Variable syntax tweaks,Attributes,Named arguments,Match expression,Union types, Mixed type,Static return type
    Version 8.1
    (25 November 2021)
    Enumerations (Enums),Readonly Properties,New Functions: fsync, fdatasync, array_is_list,Final class constantss,Explicit octal numeral notation,
    Version 8.2
    (8 December 2022)
    Standalone Types (null, false, true),Disjunctive Normal Form (DNF) Types,New Random Extension,Deprecation of Dynamic Properties,Performance Improvements,
    Version 8.3
    (23 November 2023)
    Typed Class Constants,json_validate() Function,Deep Cloning of readonly Properties,Dynamic Class Constant Fetch,Randomizer Additions,Override Attribute,
    Version 8.4
    (21 November 2024)
    Property Hooks,Asymmetric Visibility,Chaining new expressions without parentheses,New Array Functions like array_find(), array_find_key(), array_any(), array_all(),

  • Installation

    To develop PHP applications fully, especially those involving databases and web servers, installing PHP on your local machine is necessary.

    You can start learning the basics of programming in PHP with the help of any of the online PHP compilers freely available on the Internet. This will help in getting acquainted with the features of PHP without installing it on your computer. Later on, install a full-fledged PHP environment on your local machine.

    PHP Online Compiler / Editor

    One such online PHP compiler is provided by, enter PHP script and execute it.

    However, to be able to learn the advanced features of PHP, particularly related to the web concepts such as server variables, using backend databases, etc., you need to install the PHP environment on your local machine.

    In order to develop and run PHP Web pages, you neeed to install three vital components on your computer system.

    • Web Server − PHP will work with virtually all Web Server software, including Microsoft’s Internet Information Server (IIS), NGNIX, or Lighttpd etc. The most often used web server software is the freely available Apache Server. Download Apache for free here https://httpd.apache.org/download.cgi
    • Database − PHP will work with virtually all database software, including Oracle and Sybase but most commonly used is freely available MySQL database. Download MySQL for free here – https://www.mysql.com/downloads/
    • PHP Parser − In order to process PHP script instructions a parser must be installed to generate HTML output that can be sent to the Web Browser.

    Although it is possible to install these three components separately, and configure the installation correctly, it is a little complex process, particularly for the beginners. Instead, using any all-in-one packaged distribution that contains precompiled Apache, MySQL and PHP binaries is convenient.

    Installing PHP

    Install PHP by following the instructions below. There are various ways to configure Apache and PHP, but this is probably the easiest.

    Step 1 − Download the PHP files

    Get the most recent PHP x64 Thread Safe ZIP package from https://windows.php.net/download/.

    Step 2 − Extract the files

    Create a new php folder in the root of your C:\ drive and extract the ZIP contents there. PHP can be installed anywhere on your system, but if you do not use C:\php, you must edit the folders listed below.

    Step 3 − Configure php.ini

    PHP’s configuration file is php.ini. This is not present by default, therefore copy C:\php\php.ini-development to C:\php\php.ini. This default configuration creates a development environment that records all PHP errors and warnings. You can edit php.ini using a text editor and you may need to change lines like the ones shown below. To uncomment a value, normally you must remove the leading semicolon (;). First, enable any required extensions for the libraries you wish to use. The following extensions should be suitable for most applications, including WordPress −

    extension=curl
    extension=gd
    extension=mbstring
    extension=pdo_mysql
    

    If you want to send emails via PHP’s mail() function, insert the details of an SMTP server in the [mail function] section (your ISP’s settings should is enough) −

    [mail function];For Win32 only.; http://php.net/smtpSMTP= mail.myisp.com
    ; http://php.net/smtp-port
    smtp_port =25;For Win32 only.; http://php.net/sendmail-from
    sendmail_from = [email protected]
    

    Step 4 − Add C:\php to the PATH environment variable

    To ensure that Windows can discover the PHP executable, add it to the PATH environment variable. Click the Windows Start button, type “environment”, and then select Edit the system environment variables. Select the Advanced tab and then click the Environment Variables option. Scroll down the System variables list and select Path, then the Edit button. Select New and enter C:\php.

    Step 5 − Configure PHP as an Apache module

    Make sure Apache is not running, then open the C:\Apache24\conf\httpd.conf configuration file with a text editor. at configure PHP as an Apache module, add the following lines at the bottom of the file (change the file paths as needed, but use forward slashes rather than Windows backslashes) −

    # PHP8 module
    PHPIniDir "C:/php"
    LoadModule php_module "C:/php/php8apache2_4.dll"
    AddType application/x-httpd-php .php
    

    Optionally, change the DirectoryIndex setting to set index.php the default instead of index.html. Initial parameters are −

    <IfModule dir_module>
       DirectoryIndex index.html
    </IfModule>

    You have to change it to −

    <IfModule dir_module>
       DirectoryIndex index.php index.html
    </IfModule>

    Save httpd.conf and test your changes with the cmd command line.

    cd C:\Apache24\bin
    httpd -t
    

    Step 6 − Test a PHP file

    Create a new index.php file in Apache’s web page root folder C:\Apache24\htdocs. Include the following PHP code −

    <?php
       phpinfo();
    ?>

    XAMPP Installation

    There are many precompiled bundles available both in open-source as well as proprietary distributions. XAMPP, from Apache Friends (https://www.apachefriends.org/) is one of the most popular PHP enabled web server packages. We shall be using XAMPP in this tutorial.

    XAMPP is an easy to install Apache distribution that contains Apache, MariaDB, PHP and Perl. The letter X in the acronym indicates that it is a cross-platform software, available for use on Windows, Linux and OS X. Note that XAMPP includes MariaDB, which is a fork of MySQL, with no difference in its functionality.

    To download the respective installer for your operating system, visit https://www.apachefriends.org/download.html, and download one of the following −

    • Windows − https://sourceforge.net/projects/
    • Linux − https://sourceforge.net/projects/
    • OS X − https://sourceforge.net/projects/

    Using the installer on Windows is a completely wizard based installation. All you need to provide is an administrator access and the location of the installation directory which is “c:\xampp” by default.

    Install XAMPP on Linux

    To install XAMPP on Linux, use the following steps −

    Step 1 − Change the permissions to the installer −

    chmod 755 xampp-linux-*-installer.run
    

    Run the installer −

    sudo ./xampp-linux-*-installer.run
    

    XAMPP is now installed below the “/opt/lamp” directory.

    Step 2 − To start XAMPP simply call this command −

    sudo /opt/lampp/lampp start
    

    You should now see something like this on your screen −

    Starting XAMPP...LAMPP: Starting Apache...LAMPP: Starting MySQL...LAMPP started.
    Ready. Apache and MySQL are running.

    You can also use a graphical tool to manage your servers easily. You can start this tool with the following commands −

    cd /opt/lampp
    sudo ./manager-linux.run(or manager-linux-x64.run)

    Step 3 − To stop XAMPP simply call this command −

    sudo /opt/lampp/lampp stop
    

    You should now see something like this on your screen −

    Stopping XAMPP...LAMPP: Stopping Apache...LAMPP: Stopping MySQL...LAMPP stopped.

    Also, note that there is a graphical tool that you can use to start/stop your servers easily. You can start this tool with the following commands −

    cd /opt/lampp
    sudo ./manager-linux.run(or manager-linux-x64.run)

    If you are using OS X, follow these steps −

    • To start the installation, Open the DMG-Image, and double-click the image to start the installation process.
    • To start XAMPP simply open XAMPP Control and start Apache, MySQL and ProFTPD. The name of the XAMPP Control is “manager-osx”.
    • To stop XAMPP simply open XAMPP Control and stop the servers. The name of the XAMPP Control is “manager-osx”.
    • The XAMPP control panel is a GUI tool from which the Apache server, and MySQL can be easily started and stopped.
    PHP Installation 2

    Press the Admin button after starting the Apache module. The XAMPP homepage appears like the one shown below −

    PHP Installation 3

    PHP Parser Installation

    Before you proceed it is important to make sure that you have proper environment setup on your machine to develop your web programs using PHP. Type the following address into your browser’s address box.

    http://127.0.0.1/info.php
    

    If this displays a page showing your PHP installation related information then it means you have PHP and Webserver installed properly. Otherwise you have to follow given procedure to install PHP on your computer.

    This section will guide you to install and configure PHP over the following four platforms −

    • PHP Installation on Linux or Unix with Apache
    • PHP Installation on Mac OS X with Apache
    • PHP Installation on Windows NT/2000/XP with IIS
    • PHP Installation on Windows NT/2000/XP with Apache

    Apache Configuration

    If you are using Apache as a Web Server then this section will guide you to edit Apache Configuration Files.

    Just Check it here − PHP Configuration in Apache Server

    PHP.INI File Configuration

    The PHP configuration file, php.ini, is the final and most immediate way to affect PHP’s functionality.

    Just Check it here − PHP.INI File Configuration

    Windows IIS Configuration

    To configure IIS(Internet Information Services) on your Windows machine you can refer your IIS Reference Manual shipped along with IIS.

    You now have a complete PHP development environment on your local machine.

  • Introduction

    PHP started out as a small open source project that evolved as more and more people found out how useful it was. Rasmus Lerdorf released the first version of PHP way back in 1994. Initially, PHP was supposed to be an abbreviation for “Personal Home Page”, but it now stands for the recursive initialism “PHP: Hypertext Preprocessor”.

    Lerdorf began PHP development in 1993 by writing several Common Gateway Interface (CGI) programs in C, which he used to maintain in his personal homepage. Later on, He extended them to work with web forms and to communicate with databases. This implementation of PHP was “Personal Home Page/Forms Interpreter” or PHP/FI.

    Today, PHP is the world’s most popular server-side programming language for building web applications. Over the years, it has gone through successive revisions and versions.

    PHP Versions

    PHP was developed by Rasmus Lerdorf in 1994 as a simple set of CGI binaries written in C. He called this suite of scripts “Personal Home Page Tools”. It can be regarded as PHP version 1.0.

    • In April 1996, Rasmus introduced PHP/FI. Included built-in support for DBM, mSQL, and Postgres95 databases, cookies, user-defined function support. PHP/FI was given the version 2.0 status.
    • PHP: Hypertext Preprocessor – PHP 3.0 version came about when Zeev Suraski and Andi Gutmans rewrote the PHP parser and acquired the present-day acronym. It provided a mature interface for multiple databases, protocols and APIs, object-oriented programming support, and consistent language syntax.
    • PHP 4.0 was released in May 2000 powered by Zend Engine. It had support for many web servers, HTTP sessions, output buffering, secure ways of handling user input and several new language constructs.
    • PHP 5.0 was released in July 2004. It is mainly driven by its core, the Zend Engine 2.0 with a new object model and dozens of other new features. PHP’s development team includes dozens of developers and others working on PHP-related and supporting projects such as PEAR, PECL, and documentation.
    • PHP 7.0 was released in Dec 2015. This was originally dubbed PHP next generation (phpng). Developers reworked Zend Engine is called Zend Engine 3. Some of the important features of PHP 7 include its improved performance, reduced memory usage, Return and Scalar Type Declarations and Anonymous Classes.
    • PHP 8.0 was released on 26 November 2020. This is a major version having many significant improvements from its previous versions. One standout feature is Just-in-time compilation (JIT) that can provide substantial performance improvements. The latest version of PHP is 8.2.8, released on July 4th, 2023.

    How PHP Works?

    PHP is a server-side scripting language that creates dynamic content for websites. When a user requests a PHP page, the web server passes the request to the PHP interpreter, which executes the PHP script. The interpreter then generates HTML code, which is sent back to the web server and eventually to the user’s browser.

    Now let us see how it works −

    • A user opens their browser and wants a PHP page.
    • The web server receives the request and looks for the matching PHP file.
    • If the file is found, the web server sends it to the PHP interpreter.
    • The interpreter runs the PHP script.
    • The interpreter generates HTML code as output.
    • The web server returns HTML code to the browser.
    • The browser parses and displays HTML code.

    Why Use PHP?

    PHP is simple to learn and has a simple syntax. It is compatible with most web servers, integrates easily with databases. And it is open-source and free to use, has a large developer community and is well-suited for building dynamic web applications across multiple platforms such as Windows, Linux, and Mac. These features makes it a popular choice for web development projects, particularly because of its accessibility and cost-effectiveness.

    PHP Application Areas

    PHP is one of the most widely used language over the web. Here are some of the application areas of PHP −

    • PHP is a server-side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites. Although it is especially suited to web development, you can also build desktop standalone applications as PHP also has a command-line interface. You can use PHP-GTK extension to build GUI applications in PHP.
    • PHP is widely used for building web applications, but you are not limited to output only HTML. PHP’s ouput abilities include rich file types, such as images or PDF files, encrypting data, and sending emails. You can also output easily any text, such as JSON or XML.
    • PHP is a cross-platform language, capable of running on all major operating system platforms and with most of the web server programs such as Apache, IIS, lighttpd and nginx. PHP also supports other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM, etc.

    PHP Features

    Here are some more important features of PHP −

    • PHP performs system functions. It can create, open, read, write, and close the files.
    • PHP can handle forms. It can gather data from files, save data to a file, through email you can send data, return data to the user.
    • You add, delete, modify elements within your database through PHP.
    • Access cookies variables and set cookies.
    • Using PHP, you can restrict users to access some pages of your website.
    • It can encrypt data.

    PHP provides a large number of reusable classes and libraries are available on “PEAR” and “Composer”. PEAR (PHP Extension and Application Repository) is a distribution system for reusable PHP libraries or classes. “Composer” is a dependency management tool in PHP.

    How PHP Differs from Other Languages?

    Here is how it differs from other languages −

    FeaturePHPPythonJavaScriptJava
    TypeServer-side scriptingGeneral-purposeClient-side (mainly)General-purpose
    Use CaseWeb developmentWeb, AI, automationFrontend, Backend (Node.js)Enterprise applications
    SyntaxEasy, C-likeClean, readableDynamic, event-drivenStrict, OOP-heavy
    SpeedFast (PHP 7 & 8 improvements)Slower than PHPFaster (Node.js)Slower than PHP

  • Roadmap

    This road map will provide you all you need to know to become an expert PHP developer. It covers everything from the fundamentals (variables, data types, and control structures) to more advanced concepts like object-oriented programming (OOP), error handling, and database management.

    You should also learn about popular PHP frameworks like Laravel and CodeIgniter, which are useful for building strong online applications. This road map also covers the tools, best coding practices, and certification details that will help you gain the knowledge and confidence to write clean, efficient, and secure PHP code for any project.

    What is a Tutorial Roadmap?

    Tutorial Roadmap typically covers the journey from beginner to advanced user, including key concepts, practical applications, and best practices.

    PHP Roadmap

    This is PHP Developer Roadmap. Following this roadmap will guarantee to become a good PHP Developer. This is designed for programmers who are completely unaware of PHP concepts but have a basic understanding on computer programming.

    PHP Roadmap

    PHP Introduction

    PHP HistoryPHP FeaturesPHP InstallationPHP Syntax

    PHP Hello World

    PHP Basic Concepts

    PHP Comments

    PHP Variables

    PHP Constant

    PHP Magic Constant

    PHP Data Types

    Scaler Types

    Compound Types

    Strings

    Boolean

    Integers

     Floats

    Arrays

     Objects

    PHP Type Casting

    PHP Type Juggling

    PHP Control Structures

    Operators

    Arithmetic

    Comparison

    Logical

    Assignment

    String

    Array

    Conditional

    Spread

    Null Coals..

    Spaceship

    Working With Arrays

    Indexed Arrays

    Associative Arrays

    Multidimensional Arrays

    Array Functions

    PHP Functions

    Control Statements

    Decision Making

    Looping

    IfElse

    Switch

    For

    Foreach

    While

    DoWhile

    Break

    Continue

    Constant Arrays

    File Handling

    File Operations

    Open

    Read 

    Write 

    Download

    Copy 

    Append 

    Delete

    File Extension

    CSV File

    File Permission 

    Listing Files

    Create Directory

    OOPs in PHP

    Classes & Objects

    Constructors & Destructors

    Access Modifiers

     Public

     Private

     Protected

    PHP Inheritance

    PHP Encapsulation

    Advanced OOP Features

    Class Constants

    Interfaces

    Static Methods

    Abstract Classes

    Static Properties

    Final Keyword

    Cloning Objects

    Overloading

    Anonymous Classes

    PHP Namespaces

    PHP Object Iteration

    PHP Web Development

    Functions Basics

    Argument Handling

    Advanced Function Concepts

    Variable Scope

    Function Parameters

    Returning Values

    Call by value

    Call by Reference

    Default Arguments

    Named Arguments

    Variable Arguments

    Local Variables

    Global Variables

    Passing Functions

    Recursive Functions

    Type Hints

    Strict Typing

    Anonymous Functions

    Arrow Functions

    Variable Functions

    Traits

    Form Handling

    HTTP 

    Session Management

    Web Concepts

    Form Validation

    Form Email/URL

    Complete Form

    Sanitize Input

    GET & POST

    File Uploading

    Post-Redirect-Get

    Cookies

    Sessions

    Session Options

    Flash Messages

    File Inclusion

    Sending Emails

    Advanced PHP

    PHP AJAX

    PHP XML

    Ajax Search

    Ajax XML Parser

    Ajax Auto Complete

    Ajax RSS Feed

    Simple XML Parser

    SAX Parser

    DOM Parser

    Best Practices

    PHP Login

    Facebook Login

    Paypal Login

    MySql Login

    Database Interaction

    MySQL

    PDO Extension

    CSRF

    CSRF

    Coding Standard

    Error Handling

    Design Patterns

    PHP Frameworks

    Core PHP vs Frameworks

    Laravel

    CakePHP

    Symphony

    Useful Resources

    PHP Online Compiler

    PHP Cheatsheet

    Questions & Answers

    PHP Quick Guide

    How PHP Roadmap Can help you?

    This PHP roadmap includes essential programming concepts, hands-on coding exercises, and valuable learning resources. Calculate your learning timeline, implement strategic coding practices, and build a solid foundation in PHP development with our clear, structured approach.

    Useful PHP Projects

    If you want to become a PHP developer, working on real-world projects will help you learn faster. Here are some amazing PHP projects you can create −

    • Simple Calculator: A basic calculator that can perform addition, subtraction, multiplication and division.
    • Login & Registration System: A system in which users can sign up, log in and log out.
    • To-Do List App: It can be simple app in which users can add, delete and mark tasks as completed.
    • Blog Website: Basic blogging system in which users can create, edit and delete posts.
    • Online Quiz System: Quiz app in which users answer multiple choice questions and see their scores.
    • URL Shortener: It is a tool like Bitly which shortens long URLs into short and shareable links.
    • Chat Application: It is a real-time chat system in which users can send and receive messages.

    Gain Experience

    Work experience is an important factor in any domain because it immediately reflects the candidate’s skills and knowledge. Students can gain relevant work experience by doing internships in college or working full-time.

    PHP Certifications

    Getting a PHP certification can help you to showcase your skills and stand out on job applications. Here are some of the top PHP certifications you can achieve −

    • PHP From Scratch
    • Zend Certified PHP Engineer by Zend
    • PHP Certification by Udemy
    • Coursera PHP Certifications
    • Oracle Certified Professional
    • Certified PHP Developer

    Prepare for PHP Job Interviews

    After learning all of the skills required to become a PHP developer, the next step is to prepare for PHP job interviews. The job interviews are separated into stages to examine the candidate’s knowledge in several areas. PHP job interviews try to assess candidates’ technical and non-technical knowledge.

    Skills Required to Become a PHP Developer

    If you want to become a PHP Developer you will have to learn some important skills. Here is a list of skills that you must have −

    • Learn PHP Basics
    • Work with Databases (MySQL)
    • Learn HTML, CSS, and JavaScript
    • Understand PHP Frameworks
    • Learn Object-Oriented Programming (OOP)
    • Work with APIs
    • Learn Security Basics
    • Practice Using Version Control (Git)
    • Debugging and Problem-Solving
    • Build Real life Projects
  • PHP Tutorial

    What is PHP?

    PHP is an open-source general purpose scripting language, widely used for website development. It is developed by Rasmus Lerdorf in 1994. PHP is a a recursive acronym for ‘PHP: Hypertext Preprocessor’.

    PHP is the world’s most popular server-side programming language. Its latest version PHP 8.4.3, released on January 16th, 2025.

    PHP is a server-side scripting language that is embedded in HTML. PHP is a cross-platform language, capable of running on all major operating system platforms and with most of the web server programs such as Apache, IIS, lighttpd and nginx.

    A large number of reusable classes and libraries are available on PEAR and Composer. PEAR (PHP Extension and Application Repository) is a distribution system for reusable PHP libraries or classes. Composer is a dependency management tool in PHP.

    Why Learn PHP?

    PHP one of the most preferred languages for creating interactive websites and web applications. PHP scripts can be easily embedded into HTML. With PHP, you can build

    • Web Pages and Web-Based Applications
    • Content Management Systems, and
    • E-commerce Applications etc.

    A number of PHP based web frameworks have been developed to speed-up the web application development. The examples are WordPress, Laravel, Symfony etc.

    PHP Characteristics

    Below are the main characteristics which make PHP a very good choice for web development −

    1. PHP is Easy to Learn
    2. Open-Source & Free
    3. Cross-Platform Compatibility
    4. Server-Side Scripting
    5. Embedded in HTML
    6. Database Connectivity
    7. Object-Oriented & Procedural Support
    8. Large Standard Library
    9. Supports Various Protocols
    10. Framework Support

    Advantages of Using PHP

    PHP is a MUST for students and working professionals to become great Software Engineers, especially when they are working in Web Development Domain.

    Some of the most notable advantages of using PHP are listed below −

    • PHP is a multi-paradigm language that supports imperative, functional, object-oriented, and procedural programming methodologies.
    • PHP is a server-side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites.
    • PHP is integrated with a number of popular databases including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server.
    • PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on the Unix side. The MySQL server, once started, executes even very complex queries with huge result sets in record-setting time.
    • PHP supports a number of protocols such as POP3, IMAP, and LDAP. PHP supports distributed object architectures (COM and CORBA), which makes n-tier development possible.
    • PHP is forgiving: PHP language tries to be as forgiving as possible.
    • PHP has a familiar C-like syntax.

    There are five important characteristics of PHP that make its practical nature possible: Simplicity, Efficiency, Security, Flexibility, and Familiarity.

    Here are some of the most popular PHP frameworks −

    • Laravel: Used for building big and secure web applications.
    • CodeIgniter: Very fast and lightweight framework. Good for small projects.
    • Symfony: Used for large and complex applications.
    • CakePHP: Good for making fast and secure websites.
    • FuelPHP: Secure and flexible framework for web development.
    • YII: Best for developing modern Web Applications.
    • Phalcon: It is a PHP full-stack framework.
    • Pixie: Full-stack PHP framework and follows HMVC architecture.
    • Slim: Lightweight micro-framework used for creating RESTful APIs and services.

    Hello World Using PHP

    Just to give you a little excitement about PHP, I’m going to give you a small conventional PHP Hello World program. You can try it using the Edit & Run button.

    <?php
       echo "Hello, World!";
    ?>

    Online PHP Compiler

    Our PHP tutorial provides various examples to explain different concepts. We have provided an online compiler, where you can write, save, run, and share your programs directly from your browser without setting up any development environment. Practice PHP here: Online PHP compiler.

    Audience

    This PHP tutorial is designed for programmers who are completely unaware of PHP concepts but have a basic understanding on computer programming.

    Prerequisites

    Before proceeding with this tutorial, all that you need to have is a basic understanding of computer programming. Knowledge of HTML, CSS, JavaScript, and databases will be an added advantage.

    Download PHP

    You can download PHP’s latest version from its official websites. Here is the link to open the PHP download page:PHP Downloads & Installation

    Frequently Asked Questions about PHP

    There are some very Frequently Asked Questions(FAQ) about PHP, this section tries to answer them briefly.Do I Need Prior Programming Experience to Learn PHP?

    chevron

    Is PHP Free to Use?

    chevron

    What are the Applications of PHP?

    chevron

    How Do I Install PHP?

    chevron

    What Tools and Technologies Work Well with PHP?

    chevron

    Can PHP Be Used for Both Frontend and Backend Development?

    chevron

    Are There Security Concerns with PHP?

    chevron

    What Are the Latest Features and Updates in PHP?

    chevron

    How Long Will it Take to Master PHP?

    chevron

    What Resources Do I Need to Learn PHP?

    chevron