PHP (Hypertext Preprocessor)

What is PHP?

PHP is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML. It is a server-side scripting language designed primarily for web development but also used as a general-purpose programming language. Originally created by Rasmus Lerdorf in 1994, the PHP reference implementation is now produced by The PHP Development Team. PHP originally stood for Personal Home Page, but it now stands for the recursive acronym PHP: Hypertext Preprocessor.

PHP runs on different operating systems, like Windows, UNIX, Linux and supports different databases like MySQL, Microsoft Access, and Oracle. PHP can not only collect form data, but it can also create, read, write, delete, and close files on the server.

What can PHP do?

There are three main areas where PHP scripts are used.

Server-side scripting This is the most traditional and main target field for PHP. You need three things to make this work: the PHP parser (CGI or server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming.
Command line scripting You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks.
Writing desktop applications PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such programs

Getting Started with PHP

Hello Php

Introductory Sample:


		<!DOCTYPE HTML>
			<html>
				<head>
					<title>Example</title>
				</head>
				<body>

				<?php
					echo "Hi, I'm a PHP script!";
				?>

				</body>
			</html>
		

Instead of lots of commands to output HTML (as seen in C or Perl), PHP pages contain HTML with embedded code that does "something" (in this case, output "Hi, I'm a PHP script!").

Installation

Super Global Variables

Session Handling in PHP

To demontrate the Session Handling in Php here is a simple Log in(login.php) and profile(profile.php) system.

To access profile.php, user must log in first and log-in name will be used until log out or browser close (session terminate when browser closed).

To handle session, you must first start it and store some value to any session variable. You can create any amount of session variable you wish. To validate whether Session is active or not, we use isset() function and finally to destroy it we use unset() function.

Redirection in Php

PHP Code Syntax for Redirection:


		<?php
		/* Redirect browser */
		header("Location: http://theos.in/");
 
		/* Make sure that code below does not get executed when we redirect. */
		exit;
		?>
			

PHP Redirect with HTTP Status Code:


function movePage($num,$url){
	static $http = array (
       100 => "HTTP/1.1 100 Continue",
       101 => "HTTP/1.1 101 Switching Protocols",
       200 => "HTTP/1.1 200 OK",
       201 => "HTTP/1.1 201 Created",
       202 => "HTTP/1.1 202 Accepted",
       203 => "HTTP/1.1 203 Non-Authoritative Information",
       204 => "HTTP/1.1 204 No Content",
       205 => "HTTP/1.1 205 Reset Content",
       206 => "HTTP/1.1 206 Partial Content",
       300 => "HTTP/1.1 300 Multiple Choices",
       301 => "HTTP/1.1 301 Moved Permanently",
       302 => "HTTP/1.1 302 Found",
       303 => "HTTP/1.1 303 See Other",
       304 => "HTTP/1.1 304 Not Modified",
       305 => "HTTP/1.1 305 Use Proxy",
       307 => "HTTP/1.1 307 Temporary Redirect",
       400 => "HTTP/1.1 400 Bad Request",
       401 => "HTTP/1.1 401 Unauthorized",
       402 => "HTTP/1.1 402 Payment Required",
       403 => "HTTP/1.1 403 Forbidden",
       404 => "HTTP/1.1 404 Not Found",
       405 => "HTTP/1.1 405 Method Not Allowed",
       406 => "HTTP/1.1 406 Not Acceptable",
       407 => "HTTP/1.1 407 Proxy Authentication Required",
       408 => "HTTP/1.1 408 Request Time-out",
       409 => "HTTP/1.1 409 Conflict",
       410 => "HTTP/1.1 410 Gone",
       411 => "HTTP/1.1 411 Length Required",
       412 => "HTTP/1.1 412 Precondition Failed",
       413 => "HTTP/1.1 413 Request Entity Too Large",
       414 => "HTTP/1.1 414 Request-URI Too Large",
       415 => "HTTP/1.1 415 Unsupported Media Type",
       416 => "HTTP/1.1 416 Requested range not satisfiable",
       417 => "HTTP/1.1 417 Expectation Failed",
       500 => "HTTP/1.1 500 Internal Server Error",
       501 => "HTTP/1.1 501 Not Implemented",
       502 => "HTTP/1.1 502 Bad Gateway",
       503 => "HTTP/1.1 503 Service Unavailable",
       504 => "HTTP/1.1 504 Gateway Time-out"
   );
   header($http[$num]);
   header ("Location: $url");
}
}
			

Setting Header PHP


	<?php
		// Date in the past
			header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
			header("Cache-Control: no-cache");
			header("Pragma: no-cache");
	
	?>
	

Including and Requiring Files

Include

The include (or require) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement. Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website.


    <html>
        <body>
            <div class="menu">
            <?php include 'menu.php';?>
            </div>
                <h1>Welcome to my home page!</h1>
        </body>
    </html>
    

Require


    <html>
        <body>
            <h1>Welcome to my home page!</h1>
            <?php require 'noFileExists.php';
            echo "I have a $color $car.";
            ?>
        </body>
    </html>
    

Database Connectivity

In Php database conectivity is fairly easy and straight forward. As compared to other programming language such as Java, the lines of code of the database connectivity in Php is fairly shorter. There are two ways to connect in a database either use the database function-specific access or use the PDO (PHP Data Objects) which is database agnostic. I'll illustrate using PDO since it is database agnostic - meaning it can be use in any database

Database Connection via mysqli


	<?php
	  $con = mysqli_connect("localhost","root","password","webtek-database-finals");
	 if (mysqli_connect_errno())
	    {
	    echo "Failed to connect to MySQL: " . mysqli_connect_error();
	    }
         ?>
	

Database Connection via PDO


    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "webtek-database-finals";

    try {
    // Instatstiate connection
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        // Bind the parameters
    $stmt = $conn->prepare("INSERT INTO registration (firstname, lastname, username)
    VALUES (:firstname, :lastname, :username)");
    $stmt->bindParam(':firstname', $firstname);
    $stmt->bindParam(':lastname', $lastname);
    $stmt->bindParam(':username', username);

    // insert a row
    $firstname = "Chris";
    $lastname = "Espiritu";
    $username = "cee";
    $stmt->execute();

    // insert another row
    $firstname = "Maureen";
    $lastname = "Calpito";
    $username = "mcalpito";
    $stmt->execute();

    // insert another row
    $firstname = "Chris";
    $lastname = "Santos";
    $username = "crissantos";
    $stmt->execute();

    echo "New records created successfully";
    }
    catch(PDOException $e)
    {
    echo "Error: " . $e->getMessage();
    }
    $conn = null;
    ?>
    

There are many ways to connect to any database in Php, arguably the best way is to use PDO since it does not depend on vendor-specific implementation

Frameworks

Laravel Laravel is a free, open-source PHP web framework intended for the development of web applications following the model–view–controller (MVC) architectural pattern. Some of the features of Laravel are a modular packaging system with a dedicated dependency manager, different ways for accessing relational databases, utilities that aid in application deployment and maintenance, and its orientation toward syntactic sugar.
CodeIgniter CodeIgniter is an open-source software rapid development web framework, for use in building dynamic web sites with PHP. It is a powerful PHP framework with a very small footprint, built for developers who need a simple and elegant toolkit to create full-featured web applications.
Symfony Symfony is a PHP web application framework and a set of reusable PHP components/libraries. Symfony is an internationally recognized, stable development environment.

Reference

  • (n.d.). Retrieved May 20, 2017, from https://www.w3schools.com/php/func_http_header.asp
  • (n.d.). Retrieved May 20, 2017, from https://www.w3schools.com/php/func_mysqli_connect.asp
  • Buckler, C. (2015, December 02). How to Install PHP on Windows — SitePoint. Retrieved May 20, 2017, from https://www.sitepoint.com/how-to-install-php-on-windows/
  • PHP. (2017, May 17). Retrieved May 20, 2017, from https://en.wikipedia.org/wiki/PHP
  • How to Start PHP Programming: Basic PHP Scripts. (2017, February 16). Retrieved May 20, 2017, from https://www.cloudways.com/blog/how-to-start-php-programming/
  • (n.d.). Retrieved May 20, 2017, from https://mothereff.in/html-entities
  • HTML. (n.d.). Retrieved May 20, 2017, from https://www.w3schools.com/
  • Shaikh, S. (. (2014, August 13). Session handling in php. Retrieved May 20, 2017, from https://codeforgeek.com/2014/08/session-handling-php/
  • laravel. (2017, May 13). Retrieved May 20, 2017, from https://en.wikipedia.org/wiki/Laravel
  • CodeIgniter Rocks. (n.d.). Retrieved May 20, 2017, from https://www.codeigniter.com/
  • CodeIgniter. (2017, May 03). Retrieved May 20, 2017, from https://en.wikipedia.org/wiki/CodeIgniter
  • Symfony. (2017, May 06). Retrieved May 20, 2017, from https://en.wikipedia.org/wiki/Symfony
  • S. (n.d.). Symfony explained to a Developer. Retrieved May 20, 2017, from http://symfony.com/explained-to-a-developer