Author: saqibkhan

  • 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.

    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”.

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

    PHP Hello World

    Browse to the “htdocs” directory. Save the following script as “hello.php” in it.

    Open Compiler

    <?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.

    A PHP script may contain a mix of HTML and PHP code.

    Open Compiler

    <!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.

    Open Compiler

    <?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.

    Open Compiler

    <?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 must 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. However, if you launch the Apache server and open the URL http://localhost/index.php, it displays the Apache home page.

    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

    PHP defines two methods of using tags for escaping the PHP code from HTML. Canonical PHP tags and Short-open (SGML-style) tags.

    Canonical PHP Tags

    The most universally effective PHP tag style is −

    <?php
       One or more PHP statements
    ?>

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

    Short-open (SGML-style) Tags

    Short or short-open tags look like this −

    <?php
    	One or more PHP statements
    ?>

    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.

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    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 are expressions terminated by semicolons

    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 are combinations of tokens

    The smallest building blocks of PHP are the indivisible tokens such as numbers (3.14159), strings (“two”), variables ($two), constants (TRUE), and the special words that make up the syntax of PHP itself like “if”, “else”, “while”, “for”, and so forth.

    Braces make 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.");}

    PHP is case sensitive

    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”. Similarly, a function called “myfunction()” is different from another function called “MyFunction()”.

  • 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.

    • 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.

    The “match: Expression

    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.

    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
  • OOP Concepts

    OOP is an abbreviation that stands for Object-oriented programming paradigm. It is defined as a programming model that uses the concept of objects which refers to real-world entities with state and behavior. This chapter helps you become an expert in using object-oriented programming support in Python language.

    Python is a programming language that supports object-oriented programming. This makes it simple to create and use classes and objects. If you do not have any prior experience with object-oriented programming, you are at the right place. Let’s start by discussing a small introduction of Object-Oriented Programming (OOP) to help you.

    Procedural Oriented Approach

    Early programming languages developed in 50s and 60s are recognized as procedural (or procedure oriented) languages.

    A computer program describes procedure of performing certain task by writing a series of instructions in a logical order. Logic of a more complex program is broken down into smaller but independent and reusable blocks of statements called functions.

    Every function is written in such a way that it can interface with other functions in the program. Data belonging to a function can be easily shared with other in the form of arguments, and called function can return its result back to calling function.

    Prominent problems related to procedural approach are as follows −

    • Its top-down approach makes the program difficult to maintain.
    • It uses a lot of global data items, which is undesired. Too many global data items would increase memory overhead.
    • It gives more importance to process and doesn’t consider data of same importance and takes it for granted, thereby it moves freely through the program.
    • Movement of data across functions is unrestricted. In real-life scenario where there is unambiguous association of a function with data it is expected to process.

    Python – OOP Concepts

    In the real world, we deal with and process objects, such as student, employee, invoice, car, etc. Objects are not only data and not only functions, but combination of both. Each real-world object has attributes and behavior associated with it.

    oop_concepts

    Attributes

    • Name, class, subjects, marks, etc., of student
    • Name, designation, department, salary, etc., of employee
    • Invoice number, customer, product code and name, price and quantity, etc., in an invoice
    • Registration number, owner, company, brand, horsepower, speed, etc., of car

    Each attribute will have a value associated with it. Attribute is equivalent to data.

    Behavior

    Processing attributes associated with an object.

    • Compute percentage of student’s marks
    • Calculate incentives payable to employee
    • Apply GST to invoice value
    • Measure speed of car

    Behavior is equivalent to function. In real life, attributes and behavior are not independent of each other, rather they co-exist.

    The most important feature of object-oriented approach is defining attributes and their functionality as a single unit called class. It serves as a blueprint for all objects having similar attributes and behavior.

    In OOP, class defines what are the attributes its object has, and how is its behavior. Object, on the other hand, is an instance of the class.

    Principles of OOPs Concepts

    Object-oriented programming paradigm is characterized by the following principles −

    • Class
    • Object
    • Encapsulation
    • Inheritance
    • Polymorphism
    principles_of_oop

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    Class & Object

    A class is an user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation.

    An object refers to an instance of a certain class. For example, an object named obj that belongs to a class Circle is an instance of that class. A unique instance of a data structure that is defined by its class. An object comprises both data members (class variables and instance variables) and methods.

    Example

    The below example illustrates how to create a class and its object in Python.

    Open Compiler

    # defining classclassSmartphone:# constructor    def__init__(self, device, brand):
    
      self.device = device
      self.brand = brand
    # method of the classdefdescription(self):returnf"{self.device} of {self.brand} supports Android 14"# creating object of the class phoneObj = Smartphone("Smartphone","Samsung")print(phoneObj.description())

    On executing the above code, it will display the following output −

    Smartphone of Samsung supports Android 14
    

    Encapsulation

    Data members of class are available for processing to functions defined within the class only. Functions of class on the other hand are accessible from outside class context. So object data is hidden from environment that is external to class. Class function (also called method) encapsulates object data so that unwarranted access to it is prevented.

    Example

    In this example, we are using the concept of encapsulation to set the price of desktop.

    Open Compiler

    classDesktop:def__init__(self):
    
      self.__max_price =25000defsell(self):returnf"Selling Price: {self.__max_price}"defset_max_price(self, price):if price &gt; self.__max_price:
         self.__max_price = price
    # Object desktopObj = Desktop()print(desktopObj.sell())# modifying the price directly desktopObj.__max_price =35000print(desktopObj.sell())# modifying the price using setter function desktopObj.set_max_price(35000)print(desktopObj.sell())

    When the above code is executed, it produces the following result −

    Selling Price: 25000
    Selling Price: 25000
    Selling Price: 35000
    

    Inheritance

    A software modelling approach of OOP enables extending capability of an existing class to build new class instead of building from scratch. In OOP terminology, existing class is called base or parent class, while new class is called child or sub class.

    Child class inherits data definitions and methods from parent class. This facilitates reuse of features already available. Child class can add few more definitions or redefine a base class function.

    Syntax

    Derived classes are declared much like their parent class; however, a list of base classes to inherit from is given after the class name −

    classSubClassName(ParentClass1[, ParentClass2,...]):'Optional class documentation string'
       class_suite
    

    Example

    The following example demonstrates the concept of Inheritance in Python −

    Open Compiler

    #!/usr/bin/python# define parent classclassParent:        
       parentAttr =100def__init__(self):print("Calling parent constructor")defparentMethod(self):print("Calling parent method")defsetAttr(self, attr):
    
      Parent.parentAttr = attr
    defgetAttr(self):print("Parent attribute :", Parent.parentAttr)# define child classclassChild(Parent):def__init__(self):print("Calling child constructor")defchildMethod(self):print("Calling child method")# instance of child c = Child()# child calls its method c.childMethod()# calls parent's method c.parentMethod()# again call parent's method c.setAttr(200)# again call parent's method c.getAttr()

    When the above code is executed, it produces the following result −

    Calling child constructor
    Calling child method
    Calling parent method
    Parent attribute : 200
    

    Similar way, you can drive a class from multiple parent classes as follows −

    classA:# define your class A.....classB:# define your class B.....classC(A, B):# subclass of A and B.....

    You can use issubclass() or isinstance() functions to check a relationships of two classes and instances.

    • The issubclass(sub, sup) boolean function returns true if the given subclass sub is indeed a subclass of the superclass sup.
    • The isinstance(obj, Class) boolean function returns true if obj is an instance of class Class or is an instance of a subclass of Class

    Polymorphism

    Polymorphism is a Greek word meaning having multiple forms. In OOP, polymorphism occurs when each sub class provides its own implementation of an abstract method in base class.

    You can always override your parent class methods. One reason for overriding parent’s methods is because you may want special or different functionality in your subclass.

    Example

    In this example, we are overriding the parent’s method.

    Open Compiler

    # define parent classclassParent:defmyMethod(self):print("Calling parent method")# define child classclassChild(Parent):defmyMethod(self):print("Calling child method")# instance of child
    c = Child()# child calls overridden method          
    c.myMethod()

    When the above code is executed, it produces the following result −

    Calling child method
    

    Base Overloading Methods in Python

    Following table lists some generic functionality that you can override in your own classes −

    Sr.No.Method, Description & Sample Call
    1__init__ ( self [,args…] )Constructor (with any optional arguments)Sample Call : obj = className(args)
    2__del__( self )Destructor, deletes an objectSample Call : del obj
    3__repr__( self )Evaluable string representationSample Call : repr(obj)
    4__str__( self )Printable string representationSample Call : str(obj)
    5__cmp__ ( self, x )Object comparisonSample Call : cmp(obj, x)

    Overloading Operators in Python

    Suppose you have created a Vector class to represent two-dimensional vectors, what happens when you use the plus operator to add them? Most likely Python will yell at you.

    You could, however, define the __add__ method in your class to perform vector addition and then the plus operator would behave as per expectation −

    Example

    Open Compiler

    classVector:def__init__(self, a, b):
    
      self.a = a
      self.b = b
    def__str__(self):return'Vector (%d, %d)'%(self.a, self.b)def__add__(self,other):return Vector(self.a + other.a, self.b + other.b) v1 = Vector(2,10) v2 = Vector(5,-2)print(v1 + v2)

    When the above code is executed, it produces the following result −

    Vector(7,8)
  • Installation

    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.

    One such online PHP compiler is provided by Tutorialpoint’s “Coding Ground for Developers”. Visit https://www.tutorialspoint.com/codingground.htm, enter PHP script and execute it.

    PHP Installation

    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.

    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.

    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.

    PHP.INI File Configuration

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

    Windows IIS Configuration

    To configure IIS 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.

    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.

    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.

  • Python OS.Path Methods

    The os.path is another Python module, which also provides a big range of useful methods to manipulate files and directories. Most of the useful methods are listed here −

    Sr.No.Methods with Description
    1os.path.abspath(path)Returns a normalized absolutized version of the pathname path.
    2os.path.basename(path)Returns the base name of pathname path.
    3os.path.commonprefix(list)Returns the longest path prefix (taken character-by-character) that is a prefix of all paths in list.
    4os.path.dirname(path)Returns the directory name of pathname path.
    5os.path.exists(path)Returns True if path refers to an existing path. Returns False for broken symbolic links.
    6os.path.lexists(path)Returns True if path refers to an existing path. Returns True for broken symbolic links.
    7os.path.expanduser(path)On Unix and Windows, returns the argument with an initial component of ~ or ~user replaced by that user’s home directory.
    8os.path.expandvars(path)Returns the argument with environment variables expanded.
    9os.path.getatime(path)Returns the time of last access of path.
    10os.path.getmtime(path)Returns the time of last modification of path.
    11os.path.getctime(path)Returns the system’s ctime, which on some systems (like Unix) is the time of the last change, and, on others (like Windows), is the creation time for path.
    12os.path.getsize(path)Returns the size, in bytes, of path.
    13os.path.isabs(path)Returns True if path is an absolute pathname.
    14os.path.isfile(path)Returns True if path is an existing regular file.
    15os.path.isdir(path)Returns True if path is an existing directory.
    16os.path.islink(path)Returns True if path refers to a directory entry that is a symbolic link.
    17os.path.ismount(path)Returns True if pathname path is a mount point: a point in a file system where a different file system has been mounted.
    18os.path.join(path1[, path2[, …]])Joins one or more path components intelligently.
    19os.path.normcase(path)Normalizes the case of a pathname.
    20os.path.normpath(path)Normalizes a pathname.
    21os.path.realpath(path)Returns the canonical path of the specified filename, eliminating any symbolic links encountered in the path
    22os.path.relpath(path[, start])Returns a relative filepath to path either from the current directory or from an optional start point.
    23os.path.samefile(path1, path2)Returns True if both pathname arguments refer to the same file or directory
    24os.path.sameopenfile(fp1, fp2)Returns True if the file descriptors fp1 and fp2 refer to the same file.
    25os.path.samestat(stat1, stat2)Returns True if the stat tuples stat1 and stat2 refer to the same file.
    26os.path.split(path)Splits the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that.
    27os.path.splitdrive(path)Splits the pathname path into a pair (drive, tail) where drive is either a drive specification or the empty string.
    28os.path.splitext(path)Splits the pathname path into a pair (root, ext) such that root + ext == path, and ext is empty or begins with a period and contains at most one period.
    29os.path.walk(path, visit, arg)Calls the function visit with arguments (arg, dirname, names) for each directory in the directory tree rooted at path (including path itself, if it is a directory).
  • Python OS File/Directory Methods

    The OS module of Python provides a wide range of useful methods to manage files and directories. These are the built-in methods that help in interacting with operating systems. Most of the useful methods are listed here −

    Sr.No.Methods & Description
    1os.access(path, mode)Use the real uid/gid to test for access to path.
    2os.chdir(path)Change the current working directory to path
    3os.chflags(path, flags)Set the flags of path to the numeric flags.
    4os.chmod(path, mode)Change the mode of path to the numeric mode.
    5os.chown(path, uid, gid)Change the owner and group id of path to the numeric uid and gid.
    6os.chroot(path)Change the root directory of the current process to path.
    7os.close(fd)Close file descriptor fd.
    8os.closerange(fd_low, fd_high)Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring errors.
    9os.dup(fd)Return a duplicate of file descriptor fd.
    10os.dup2(fd, fd2)Duplicate file descriptor fd to fd2, closing the latter first if necessary.
    11os.fchdir(fd)Change the current working directory to the directory represented by the file descriptor fd.
    12os.fchmod(fd, mode)Change the mode of the file given by fd to the numeric mode.
    13os.fchown(fd, uid, gid)Change the owner and group id of the file given by fd to the numeric uid and gid.
    14os.fdatasync(fd)Force write of file with filedescriptor fd to disk.
    15os.fdopen(fd[, mode[, bufsize]])Return an open file object connected to the file descriptor fd.
    16os.fpathconf(fd, name)Return system configuration information relevant to an open file. name specifies the configuration value to retrieve.
    17os.fstat(fd)Return status for file descriptor fd, like stat().
    18os.fstatvfs(fd)Return information about the filesystem containing the file associated with file descriptor fd, like statvfs().
    19os.fsync(fd)Force write of file with filedescriptor fd to disk.
    20os.ftruncate(fd, length)Truncate the file corresponding to file descriptor fd, so that it is at most length bytes in size.
    21os.getcwd()Return a string representing the current working directory.
    22os.getcwdu()Return a Unicode object representing the current working directory.
    23os.isatty(fd)Return True if the file descriptor fd is open and connected to a tty(-like) device, else False.
    24os.lchflags(path, flags)Set the flags of path to the numeric flags, like chflags(), but do not follow symbolic links.
    25os.lchmod(path, mode)Change the mode of path to the numeric mode.
    26os.lchown(path, uid, gid)Change the owner and group id of path to the numeric uid and gid. This function will not follow symbolic links.
    27os.link(src, dst)Create a hard link pointing to src named dst.
    28os.listdir(path)Return a list containing the names of the entries in the directory given by path.
    29os.lseek(fd, pos, how)Set the current position of file descriptor fd to position pos, modified by how.
    30os.lstat(path)Like stat(), but do not follow symbolic links.
    31os.major(device)Extract the device major number from a raw device number.
    32os.makedev(major, minor)Compose a raw device number from the major and minor device numbers.
    33os.makedirs(path[, mode])Recursive directory creation function.
    34os.minor(device)Extract the device minor number from a raw device number.
    35os.mkdir(path[, mode])Create a directory named path with numeric mode mode.
    36os.mkfifo(path[, mode])Create a FIFO (a named pipe) named path with numeric mode mode. The default mode is 0666 (octal).
    37os.mknod(filename[, mode=0600, device])Create a filesystem node (file, device special file or named pipe) named filename.
    38os.open(file, flags[, mode])Open the file file and set various flags according to flags and possibly its mode according to mode.
    39os.openpty()Open a new pseudo-terminal pair. Return a pair of file descriptors (master, slave) for the pty and the tty, respectively.
    40os.pathconf(path, name)Return system configuration information relevant to a named file.
    41os.pipe()Create a pipe. Return a pair of file descriptors (r, w) usable for reading and writing, respectively.
    42os.popen(command[, mode[, bufsize]])Open a pipe to or from command.
    43os.read(fd, n)Read at most n bytes from file descriptor fd. Return a string containing the bytes read. If the end of the file referred to by fd has been reached, an empty string is returned.
    44os.readlink(path)Return a string representing the path to which the symbolic link points.
    45os.remove(path)Remove the file path.
    46os.removedirs(path)Remove directories recursively.
    47os.rename(src, dst)Rename the file or directory src to dst.
    48os.renames(old, new)Recursive directory or file renaming function.
    49os.rmdir(path)Remove the directory path
    50os.stat(path)Perform a stat system call on the given path.
    51os.stat_float_times([newvalue])Determine whether stat_result represents time stamps as float objects.
    52os.statvfs(path)Perform a statvfs system call on the given path.
    53os.symlink(src, dst)Create a symbolic link pointing to src named dst.
    54os.tcgetpgrp(fd)Return the process group associated with the terminal given by fd (an open file descriptor as returned by open()).
    55os.tcsetpgrp(fd, pg)Set the process group associated with the terminal given by fd (an open file descriptor as returned by open()) to pg.
    56os.tempnam([dir[, prefix]])Return a unique path name that is reasonable for creating a temporary file.
    57os.tmpfile()Return a new file object opened in update mode (w+b).
    58os.tmpnam()Return a unique path name that is reasonable for creating a temporary file.
    59os.ttyname(fd)Return a string which specifies the terminal device associated with file descriptor fd. If fd is not associated with a terminal device, an exception is raised.
    60os.unlink(path)Remove the file path.
    61os.utime(path, times)Set the access and modified times of the file specified by path.
    62os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])Generate the file names in a directory tree by walking the tree either top-down or bottom-up.
    63os.write(fd, str)Write the string str to file descriptor fd. Return the number of bytes actually written.
  • File Methods

    A file object is created using open() function. The file class defines the following methods with which different file IO operations can be done. The methods can be used with any file like object such as byte stream or network stream.

    Sr.No.Methods & Description
    1file.close()Close the file. A closed file cannot be read or written any more.
    2file.flush()Flush the internal buffer, like stdio’s fflush. This may be a no-op on some file-like objects.
    3file.fileno()Returns the integer file descriptor that is used by the underlying implementation to request I/O operations from the operating system.
    4file.isatty()Returns True if the file is connected to a tty(-like) device, else False.
    5file.next()Returns the next line from the file each time it is being called.
    6file.read([size])Reads at most size bytes from the file (less if the read hits EOF before obtaining size bytes).
    7file.readline([size])Reads one entire line from the file. A trailing newline character is kept in the string.
    8file.readlines([sizehint])Reads until EOF using readline() and return a list containing the lines. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read.
    9file.seek(offset[, whence])Sets the file’s current position
    10file.tell()Returns the file’s current position
    11file.truncate([size])Truncates the file’s size. If the optional size argument is present, the file is truncated to (at most) that size.
    12file.write(str)Writes a string to the file. There is no return value.
    13file.writelines(sequence)Writes a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings.