AVATTAVA

Technology is Power

PHP 8.0 Intro

Coding MasterClass PHP 8 Introduction

PHP 8.0 Introduction

In this PHP 8.0 introduction, we need to explain immediately what is a web page, which is an hypertext document on the World Wide Web “with its own address”. Web pages are delivered by a web server to the users and displayed in a web browser to act as a “retrieval unit” for the information stored in that same web server. A website consists of several web pages linked together under a common domain name, as per yoursite.com

What is PHP or Hypertext PreProcessor?

PHP is a general-purpose scripting language that is especially suited to web development. Fast, flexible and pragmatic, PHP is an open-source, server-side programming language that can be used to create websites, applications and customer relationship management systems. Widely embedded into HTML and helps to simplify HTML code.

How to code in PHP ?

  • 1. PHP Parser
  • The parser takes PHP code and analyses it, outputting a respective syntax tree that puts the source into an easier to read format for machines to understand.
  • 2. Web Server
  • The server is the program that will execute your PHP files to form webpages
  • 3. Web Browser
  • The browser will allow you to view the PHP page through the server, in the same way as with any other content on the web.

How do developers use PHP ? 

PHP is used to create most things that a software developer needs. However, there are 3 main areas in which it thrives:

  1. Server-side Scripts
    Server-side scripts are PHP main strength. If you are just learning to code and want to explore server-side scripting, PHP is a great language to learn. To get cracking with PHP server-side scripting you’ll need to have a PHP parser, web server and web browser.
  2. Command-line Scripts 
    Command-line scripting is ideal for scripts made using Cron (Linux) or Task Scheduler (Windows). Also great for simple text processing.
  3. Desktop Applications
    PHP is probably not the best language to create desktop applications but for the advanced web developer, it provides you with many more options than its competitors.

PHP is excellent at collecting forms data, encrypting users data and sending and receiving cookies. PHP is compatible with all major operating systems, so you can code no matter what technology you are using.

How is PHP used in HTML5?

PHP is often used to build dynamic webpages. A dynamic webpage is one where each visitor to the website gets a personalized page that may look different than how the website looks to another visitor. In order to create this dynamic behavior, PHP was designed to work closely with HTML. PHP can be used directly inline with an HTML document. This is in contrast to static webpages which provide the same content to each visitor.

PHP or Pre Hypertext Processor

PHP is nicknamed “Personal Home Page”, but if we compare it with JavaScript, where the code is executed on the browser (client side), the PHP code is executed within the server (server side) and the result is integrated on the HTML page that is sent to the browser. The browser is not aware of the modifications that occurred in the server.

PHP allows to build dynamic web pages where the content can be partially or entirely created at the time of calling the web page using the information provided by a contact form or extracted from a database. PHP is quite powerful and flexible enough to be able to generate a very simple text (in English), CSS code with some nice visual effects, HTML code and or JavaScript code, all bundled together on a HTML page and sent to the browser through a .php file on the server.

 PHP 8 Introduction to HTML5 to make Dynamic websites vs Static websites

<!DOCTYPE> declaration in HTML5

HTML documents must start with a <!DOCTYPE> declaration, which is not an HTML tag, but rather is an “information” to the browser about what document type to expect. In HTML5, the declaration is <!DOCTYPE html>

In order to indicate to the server that a certain HTML page contains PHP code, it is enough to give a .php extension to the file.

Below, with example.php you can see a very simple webpage in PHP 8.0.2 where the xmlns attribute specifies the xml namespace for a document. Please note that example.php is an HTML webpage containing PHP code to execute.

Note: The xmlns attribute is required in XHTML, invalid in HTML 4.01 and optional in HTML5.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang"fr">
   <head>
     <meta charset="utf-8" />
     <title>Page PHP</title>
  </head>
  <body>
    <?php
    echo '<p>Bounjour Sarah Jones</p>';
    ?>
  </body>
</html>

Note: The HTML validator at https://w3.org does not complain when the xmlns attribute is missing in an XHTML document. This is because the namespace “xmlns=http://www.w3.org/1999/xhtml” is default and will be added to the <html> tag even if you do not include it.

Within the same web page, you can add little blocks of PHP code to try out the final result, which is the rendering of an HTML web page. Below, the PHP code shows a static text on the web page, thanks to the function echo. Most probably, on a .php file of any WordPress website, that same text will be dynamically created according to users’ input.

<?php
$txt = "PHP 8.0";
echo "I love $txt";
?>

2.0 Base Structure

HTML is a markup language and PHP is a server-side scripting language, meaning that you will write the coding in different files, often. However, you will face scenarios where you will be have to connect a PHP file to HTML.

We will discuss the base structure of an HTML webpage containing PHP. You will discover that PHP and HTML interact a lot since PHP can generate HTML and HTML can pass information to PHP, but for that to happen, PHP will have to retrieve variables from external sources. When a form is submitted to a PHP script, the information from that form is automatically made available to the script, as in a very simple HTML form:

<form action="example.php" method="post">
    Name:  <input type="text" name="username" /><br />
    Email: <input type="text" name="email" /><br />
    <input type="submit" name="submit" value="Submit me!" />
</form>

2.1 How to connect PHP and HTML ?  

To connect PHP and HTML code, the best way is to construct a link between them since putting both scripts in the same file will make modifying the code difficult. This method offers the following advantages.

  • Simple to maintain and manage multiple scripts by making modifications in one place.
  • Allowing multiple pages on a website to share common functions and variables reduces redundancy.
  • Easy code editing and debugging.

You can also connect PHP and HTML by changing the file extension.

2.2 Tags syntax in PHP

PHP accepts two kinds of syntax for its Tags: <?php … ?>

                      <?  … ?>  

But the second one, without the letters php (in red), needs to be authorised within the php.ini configuration file by selecting the directive SHORT_OPEN_TAG to be ON. When the script only contains PHP code, the closing tag ?> can be omitted.

2.3 Function “echo” in PHP

Is echo a PHP function or a language construct? The function echo is the workhorse of every PHP webpage, as it allows to display one or more text strings on the HTML page.

The function echo also accepts two kinds of syntax: echo (‘text string’);

                          echo ‘text’ , ‘text’ , ‘text’;

The first syntax only accepts one parameter, while the second syntax accepts several input parameters, as you will be able to see on the following example:

<!DOCTYPE html>
<html xmlns="http://w3.org/1999/xhtml" lang="fr">
<head>
    <meta charset="utf-8" />
    <title>Beautiful PHP Webpage</title>
    </head>
    <body>
    <p>
        <?php
        echo ('Bonjour Olivier');
        ?>
        <br/>
        <?php
        echo 'Bonjour' , 'Valeria' , '?!';
        ?>
    </p>
    </body>
</html>

Note: There is no automatic line jump as a result of the PHP code execution and that means it will be necessary to insert an HTML tag </br> that displays a line jump on the final HTML webpage.

The nl2br() function contains these newline characters \n or \r\n which create the newline. Apart from nl2br() function, an HTML break line tag <br/> is used to break the string. The <br/> tag should be enclosed in double quotes, “<br/>”

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

2.4 Instructions Separator

All instructions must end with a semicolon. In case of omission an error is generated.

Note: The sole exception concerns the instruction that precedes the ending tag, for which the semicolon can be omitted. The closing tag of a block of PHP code automatically implies a semicolon.

<?='Hello Valeria!'?>

Yes, the closing tag of a block of PHP code automatically implies a semicolon, but the closing tag for the block will include the immediately trailing new line if one is present.

<?php echo "Some text"; ?>
New line of PHP, perhaps?
<?= "Show a new line, now!" ?>

Output

Some textNew line of PHP, perhaps?

Show a new line, now!

Note: Omitting the closing tag of a PHP block at the end of a file is helpful when using PHP functions include or require, in that way, unwanted white space will not occur at the end of files and you will still be able to add headers to the response later. Very handy if you use output buffering, and would not like to see added unwanted white space at the end of the parts generated by the included files.

Note: Output buffering is a way to tell PHP to hold some data before it is sent to the browser, so that you can retrieve the data and put it in a variable, manipulate it and send it to the browser.

Below, you can see a few examples of entering and exiting the PHP parser:

<?php
    echo 'Alex Jones';
?>

<?php echo 'Alex Jones' ?>

<?php echo 'We omitted the last closing tag';

PHP Parser

PHP Parser is a library that takes a source code written in PHP, passes it through a lexical analyzer and creates its respective syntax tree (data structure). Very useful for static code analysis, to check our own code for syntactic errors and certain quality criteria.

In computer technology, a parser is a program that is often part of a compiler. A parser receives input in the form of sequential source program instructions, interactive online commands, markup tags or some other defined interface. Parsers break the input they get into parts such as the nouns (objects), verbs (methods), and their attributes or options. These are then managed by other software components in a compiler. A parser may also check to ensure that all the necessary input has been provided.

Parsing happens during the analysis stage of compilation, when code is taken from the preprocessor (PHP = Hypertext Preprocessor), broken into smaller pieces and analyzed so that other software can understand it. The parser does this by building a data structure out of the small pieces of input. A person writes code in a human-readable language like C++ or Java and saves it as a series of files. The parser takes those files as input and breaks them down so they can be translated on the target platform.

The 3 stages of a PHP Parser

  • Stage 1. Lexical Analysis
  • A lexical analyzer or scanner takes code from the preprocessor and breaks it into smaller pieces, then it groups the input code into sequences of characters called lexemes, each of which corresponds to a token. Tokens are units of grammar in the programming language that the compiler is able to understand. Scanners also remove white space characters, comments and errors from the input.
  • Stage 2. Syntactic Analysis
  • This parsing stage checks the syntactical structure of the input, using a data structure called a parse tree. A syntax analyzer uses tokens to construct a parse tree that combines the predefined grammar of the programming language with the tokens of the input string. The syntactic analyzer reports a syntax error if the syntax is incorrect.
  • Stage 3. Semantic Analysis
  • Semantic analysis verifies the parse tree against a symbol table and determines whether it is semantically consistent or not. This process is also known as context sensitive analysis and it includes data type checking, label checking and flow control checking.

If the code provided is float a = 30.2; float b = a*20 then the analyzer will treat 20 as 20.0 before performing the operation.

2.5 Coding Comments

As with any other programming language, PHP comments helps to organize your PHP project’s code structure for better understanding and debugging purposes adding explanation and clarification to other PHP programmers looking at your code.

Do you want your PHP code to look like this?

$class = new whateverClass();
$here = $class->doThis()->doThat();
$there = $here->alsoDoThat($someVar);

Or do you prefer it to look like this?

// Initialize the Class
$class = new someClass();

// Get $class to doThis() and doThat()
$here = $class->doThis()->doThat();

// Then get $here to alsoDoThat() with $someVar
$there = $here->alsoDoThat($someVar);

PHP allows 2 syntaxes for comments:

  • // or # to insert a comment on “a dedicated line” or following a code instruction.
  • /* … */ to insert a comment that spreads over several lines (without any code).
  <?php
    // Comment on a single line.
    # Comment on a single line, a variant of the first example.

    /* Comment divided per
    two lines of a PHP file */

    /* Comment spread through
     * several lines of a PHP
     *  file that we are coding.
     */
    echo 'Hello '; // Comment following a line of code.
    echo 'Marina'; # Another comment following a line of code.
   ?> 

Output

Hello Marina

2.6 How to mix PHP and HTML ?

There is no specific rule to mix PHP and HTML, but an approach commonly used by developers consists in employing PHP only to generate the dynamic part of the webpage, the rest is written in HTML inside the PHP file. This approach makes the code less “heavy” and provides an applying logic.

There are several ways to mix PHP and HTML that rest nonetheless on 2 principles:

  1. The webpage can have 2 or more inclusions of PHP code.
  2. PHP generates “text” being integrated in the HTML webpage sent to the browser.
    • All “text” possible to be understood by the browser can be generated by PHP code (simple text, CSS, HTML, JavaScript).
Coding HTML and PHP

The following examples use PHP variables and functions (to recover the Date & Time):

<?php
  /* Declaration of variables to be used later on...
   * This section of PHP code does not generate any output on the HTML
   * webpage, since it does call the function ECHO.
   */
  $name = 'Simon';  // Username!
  $page_title = 'University Editions';
  $today = date("d/m/Y");
  $hour = date("H:i:s");
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
  <head>
    <meta charset="utf-8" />
    <title>
      <?php /* Title Display on Screen */ echo $page_title; ?>
    </title>
  </head>
  <body>
    <p>
      <?php
      /* Display of Username. Name tags in bold <b>
       * and "break line" <br /> are include within 
       * the ECHO instruction.
       */
        echo "Hello <b>$name</b>! <br />";
        // Display of Date & Hour
        echo "Today is $today and the time is $hour";
      ?>
    </p>
  </body>
</html>













<<<

Design a site like this with WordPress.com
Get started