Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Thursday, May 7, 2020

Embedding PHP in HTML

PHP is an HTML-embedded server-side scripting language. When building a complex page, at some point you will be faced with the need to combine PHP and HTML to achieve your needed results. At the first point, this can seem complicated, since PHP and HTML are two separate languages, but this is not the case. PHP is designed to interact with HTML and PHP scripts can be included in an HTML page without a problem.

In an HTML page, PHP code is enclosed within special PHP tags. When a visitor opens the page, the server processes the PHP code and then sends the output (not the PHP code itself) to the visitor's browser. Actually, it is quite simple to integrate HTML and PHP. A PHP script can be treated as an HTML page, with bits of PHP inserted here and there. Anything in a PHP script that is not contained within <?php ?> tags is ignored by the PHP compiler and passed directly to the web browser. If you look at the example below you can see what a full PHP script might look like:

Recommended usage:

<html>
<head>
</head>
<body class="page_bg">
Hello, today is <?php echo date('l, F jS, Y'); ?>.
</body>
</html>


The code above is simply HTML, with just a bit of PHP that prints out today's date using the built-in date function. As mentioned above, all of the plain HTML in the code above will be ignored by the PHP compiler and passed through to the web browser untouched.

 More advanced techniques:

<html>
<head></head>
<body>
<ul>
<?php for($i=1;$i<=5;$i++){ ?>
<li>Menu Item <?php echo $i?></li>
<?php } ?>
</ul>
</body>
</html>

and the result is:

· Menu Item 1
· Menu Item 2
· Menu Item 3
· Menu Item 4
· Menu Item 5

 

PHP in HTML using short_open_tag

If you want to shorten your code as much as possible, you can go for the short_tags option. This will save you from typing <?php at the beginning of the code, shortening it to just <?.

PHP in HTML using short_tags:

<html>
<head></head>
<body class="page_bg">
Hello, today is <?=date('l, F jS, Y'); ?>.
</body>
</html>

Have in mind that if you want to build a website compatible with as many platforms as possible, you should not rely on short_tags.

HTML in PHP using echo

A possible way to integrate HTML tags in a PHP file is via the echo command:

Possible yet not recommended usage:

<?php
echo "<html>";
echo "<head></head>";
echo "<body class=\"page_bg\">";
echo "Hello, today is ";
echo date('l, F jS, Y'); //other php code here echo "</body>";
echo "</html>";
?>

This will, however, affect the HTML Code Coloring option in most HTML/PHP editors, which allows for an easy understanding of the role of HTML tags. You should escape each double quote within the HTML code with a backslash.


Comments in PHP

The word comment itself expresses its meaning as commenting out something. If we comment on anything in the PHP program file, it will not be compiled with the code. The compiler or the interpreter will simply ignore this.

There are two types of comments you can add:

1.     Single line comment used for quick notes about complex code or to temporarily disable a line of PHP code. You need to add // or # before the code.

Example-1 :

<?php
echo "This is my first PHP Program";
// this is the first program
?>

 

Example-2 :

<?php
# $i=10;
# $j=20;
# echo $i + $j;
echo "Hello World!";
# this is PHP comment
?>

 

2.     Multi-line comment used to comment out large blocks of code or writing multiple line comments. You need to add /* before and */ after the code.

Example:

<?php
    /* The following line of code
       will output the "Hello World!" message */
    echo "Hello World!";
?>

Introduction to PHP

PHP is a server-side scripting language. That is used to develop Static websites or Dynamic websites or Web applications. PHP stands for Hypertext Pre-processor, that earlier stood for Personal Home Pages.

  • PHP scripts can only be interpreted on a server that has PHP installed.
  • The client computers accessing the PHP scripts require a web browser only.
  • A PHP file contains PHP tags and ends with the extension ".php".

What is Scripting Language?

  • A script is a set of programming instructions that is interpreted at runtime.
  • A scripting language is a language that interprets scripts at runtime. Scripts are usually embedded into other software environments.
  • The purpose of the scripts is usually to enhance the performance or perform routine tasks for an application.
  • Server-side scripts are interpreted on the server while client side scripts are interpreted by the client application.
  • PHP is a server-side script that is interpreted on the server while JavaScript is an example of a client-side script that is interpreted by the client browser. Both PHP and JavaScript can be embedded into HTML pages.

Programming Language Vs Scripting Language

Programming language

Scripting language

Has all the features needed to develop complete applications.

Mostly used for routine tasks

The code has to be compiled before it can be executed

The code is usually executed without compiling

Does not need to be embedded into other languages

Is usually embedded into other software environments.

What does PHP stand for?

PHP means - Personal Home Page, but it now stands for the recursive backronym PHP: Hypertext Preprocessor.

PHP code may be embedded into HTML code, or it can be used in combination with various web template systems, web content management system and web frameworks.

Php Syntax

A PHP file can also contain tags such as HTML and client side scripts such as JavaScript.

  • HTML is an added advantage when learning PHP Language. You can even learn PHP without knowing HTML but it’s recommended you at least know the basics of HTML.
  • Database management systems DBMS for database powered applications.
  • For more advanced topics such as interactive applications and web services, you will need JavaScript and XML.

The flowchart diagram shown below illustrates the basic architecture of a PHP web application and how the server handles the requests.

Why use PHP?

You have obviously heard of a number of programming languages out there; you may be wondering why we would want to use PHP as our poison for the web programming. Below are some of the compelling reasons.

  • PHP is open source and free.
  • Short learning curve compared to other languages such as JSP, ASP etc.
  • Large community document
  • Most web hosting servers support PHP by default unlike other languages such as ASP that need IIS. This makes PHP a cost effective choice.
  • PHP is regular updated to keep abreast with the latest technology trends.
  • Other benefit that you get with PHP is that it’s a server side scripting language; this means you only need to install it on the server and client computers requesting for resources from the server do not need to have PHP installed; only a web browser would be enough.
  • PHP has in built support for working hand in hand with MySQL; this doesn’t mean you can’t use PHP with other database management systems. You can still use PHP with
    • Postgres
    • Oracle
    • MS SQL Server
    • ODBC etc.
  • PHP is cross platform; this means you can deploy your application on a number of different operating systems such as windows, Linux, Mac OS etc.

What is PHP used for & Market share

In terms of market share, there are over 20 million websites and application on the internet developed using PHP scripting language.

This may be attributed to the points raised above;

The diagram below shows some of the popular sites that use PHP


PHP File Extensions

File extension and Tags In order for the server to identify our PHP files and scripts, we must save the file with the “.php” extension. Older PHP file extensions include

  • .phtml
  • .php3
  • .php4
  • .php5
  • .phps

The PHP tags themselves are not case-sensitive, but it is strongly recommended that we use lower case letter. The code below illustrates the above point.

<?php … ?>

We will be referring to the PHP lines of code as statements. PHP statements end with a semi colon (;). If you only have one statement, you can omit the semi colon. If you have more than one statement, then you must end each line with a semi colon. For the sake of consistency, it is recommended that you always end your statement(s) with a semi colon.  PHP scripts are executed on the server. The output is returned in form of HTML.

How to run PHP?

Manual installation of a Web server and PHP requires in-depth configuration knowledge but the XAMPP suite of Web development tools, created by Apache Friends, makes it easy to run PHP. Installing XAMPP on Windows only requires running an installer package without the need to upload everything to an online Web server. This PHP Tutorial gives you an idea of XAMPP and how it is used for executing the PHP programs.

What is XAMPP?

It is a free and open-source cross-platform webserver solution stack package developed by Apache Friends that consists of the Apache HTTP Server, MariaDB & MySQL database, and interpreters for scripts are written in the PHP and Perl programming languages. XAMPP stands for Cross-Platform (X), Apache (A), MariaDB & MySQL (M), PHP (P) and Perl (P). It is a simple, lightweight Apache distribution that makes it extremely easy for developers to create a local web server for testing and deployment purposes.

PHP using WAMP Server

If you’re working on a project for the production environment and have a PC running the Windows OS then you should opt for WAMP server because it was built with security in mind. You can use this method to run PHP scripts you may have obtained from somewhere and need to run with little or no knowledge of PHP. You can execute your scripts through a web server where the output is a web browser.

Let’s have a look at the steps involved in using WAMP Server:

  1. Install the Server Software
  2. Set up the Server
  3. Save PHP Scripts
  4. Run PHP Scripts
  5. Troubleshoot

Now let’s move ahead with our PHP Tutorial and find out the suitable IDE for PHP.

PHP IDE

In order to remain competitive and productive, writing good code in minimum time is an essential skill that every software developer must possess. As the number and style of writing code increases and new programming languages emerge frequently, it is important that the software developers must opt for the right IDE to achieve the objectives.

An Integrated Development Environment or IDE is a self-contained package that allow you to write, compile, execute and debug code in the same place. So let’s have a look at some of the best IDE’s for PHP:

  • PHPStorm
  • Netbeans
  • Aptana Studio
  • Eclipse
  • Visual Code Editor
  • ZendStudio

PHP Hello world

The program shown below is a basic PHP application that outputs the words “Hello World!” When viewed in a web browser.

<?php

echo "Hello world";

?>

Output:

Hello world


 

Wednesday, April 1, 2020

PHP Error and Exception

PHP Error Handling

Error handling is the process of catching errors raised by your program and then taking appropriate action. If you would handle errors properly then it may lead to many unforeseen consequences. It’s very simple in PHP to handle errors. PHP offers a number of ways to handle errors.
 We are going to look at three (3) commonly used methods;

  1. Die statements– the die function combines the echo and exit function in one. It is very useful when we want to output a message and stop the script execution when an error occurs.
  2. Custom error handlers – these are user-defined functions that are called whenever an error occurs.
  3. PHP error reporting – the error message depending on your PHP error reporting settings. This method is very useful in a development environment when you have no idea what caused the error. The information displayed can help you debug your application.

Error Handling Examples

Example-1:
Using die() function: While writing your PHP program you should check all possible error conditions before going ahead and take appropriate action when required. Try the following example without having test.txt file and with this file.

<?php
   if(!file_exists("/tmp/test.txt")) {
      die("File not found");
   }else {
      $file = fopen("/tmp/test.txt","r");
      print "Opend file sucessfully";
   }
   // Test of the code here.
?>

This way you can write efficient code. Using the above technique you can stop your program whenever it errors out and displays a more meaningful and user-friendly message.

Example-2:

<?php   
  $denominator = 0;   
  echo 2 / $denominator;   
?> 

Assuming you saved the file simple_error.php, open the URL 
http://localhost/ simple_error.php
You will get the following results


As you can see from the above results, it makes our application look unprofessional and can be annoying to the user.
We will modify the above code and write an error handler for the application

<?php  
 $denominator = 0;  
 if ($denominator != 0) {  
   echo 2 / $denominator;  
 } else {  
   echo "cannot divide by zero (0)";  
 }  
 ?>

Assuming you saved the above code as error_handling.php, open the URL  http://localhost/error_handling.php


Note: it’s a good security practice displaying a message like the one shown above instead of showing the message like “File not found”.

PHP Exception Handling

An exception is an unexpected program result that can be handled by the program itself. Exception Handling in PHP is almost similar to exception handling in all programming languages.
PHP provides the following specialized keywords for this purpose.
·       try: It represents a block of code in which exception can arise.
·       catch: It represents a block of code that will be executed when a particular exception has been thrown.
·     throw: It is used to throw an exception. It is also used to list the exceptions that a function throws, but doesn’t handle itself.
·     finally: It is used in place of catch block or after catch block basically, it is put for cleanup activity in PHP code.

Why Exception Handling in PHP?
Following are the main advantages of exception handling over error handling
·     Separation of error handling code from normal code: In traditional error handling code there is always if-else block to handle errors. These conditions and code to handle errors got mixed so that becomes unreadable. With try Catch block code becomes readable.
·     Grouping of error types: In PHP both basic types and objects can be thrown as an exception. It can create a hierarchy of exception objects, group exceptions in namespaces or classes, categorize them according to types.

Exception handling in PHP: Following code explains the flow of normal try-catch block in PHP:

<?php
// PHP Program to illustrate normal
// try-catch block code

function demo($var) {
    echo " Before try block";
    try {
        echo "\n Inside try block";
             
        // If var is zero then only if will be executed
        if($var == 0)
        {
                 
            // If var is zero then only exception is thrown

            throw new Exception('Number is zero.');
                 
            // This line will never be executed
            echo "\n After throw (It will never be executed)";
        }
    }
         
    // Catch block will be executed only 
    // When Exception has been thrown by try block

    catch(Exception $e) {
            echo "\n Exception Caught", $e->getMessage();
        }
         
        // This line will be executed whether
        // Exception has been thrown or not 
        echo "\n After catch (will be always executed)";
}
 
// Exception will not be raised

demo(5);
 
// Exception will be raised here

demo(0);
?>

Output:

 Before try block
 Inside try block
 After catch (will be always executed)
 Before try block
 Inside try block
 Exception CaughtNumber is zero.

 After catch (will be always executed)



Defining Custom Exceptions

You can even define your own custom exception handlers to treat different types of exceptions in a different way. It allows you to use a separate catch block for each exception type.

You can define a custom exception by extending the Exception class, because Exception is the base class for all exceptions. The custom exception class inherits all the properties and methods from PHP's Exception class. You can also add your custom methods to the custom exception class. Let's check out the following example:
Example:

<?php
// Extending the Exception class
class EmptyEmailException extends Exception {}
class InvalidEmailException extends Exception {}

$email = "someuser@example..com";

try{
    // Throw exception if email is empty
    if($email == ""){
        throw new EmptyEmailException("<p>Please enter your E-mail address!</p>");
    }   
    // Throw exception if email is not valid
    if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {          
        throw new InvalidEmailException("<p><b>$email</b> is not a valid E-mail address!</p>");
    }   
    // Display success message if email is valid
    echo "<p>SUCCESS: Email validation successful.</p>";
} catch(EmptyEmailException $e){
    echo $e->getMessage();
} catch(InvalidEmailException $e){
    echo $e->getMessage();
}
?>
In the above example we've derived two new exception classes: EmptyEmailException, and InvalidEmailException from the Exception base class. Multiple catch blocks are used to display different error messages, depending on the type of exception generated.
Since these custom exception classes inherit the properties and methods from the Exception class, so we can use the Exception class methods like getMessage(), getLine(), getFile(), etc. to retrieve error information from the exception object.
Output: