0% found this document useful (0 votes)
53 views

WT M3 PHP Basic

This document discusses server-side web development using PHP. It describes how server-side scripts are executed on a web server to dynamically generate content, unlike client-side scripts which are executed in the browser. It compares different server-side technologies like PHP, ASP.NET, JSP, and explains how they generate HTML, CSS and JavaScript to send to the requesting browser. It also discusses how the Apache web server handles requests and interacts with PHP as an installed module to process requests and return dynamic content to clients.

Uploaded by

Janhvi Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

WT M3 PHP Basic

This document discusses server-side web development using PHP. It describes how server-side scripts are executed on a web server to dynamically generate content, unlike client-side scripts which are executed in the browser. It compares different server-side technologies like PHP, ASP.NET, JSP, and explains how they generate HTML, CSS and JavaScript to send to the requesting browser. It also discusses how the Apache web server handles requests and interacts with PHP as an installed module to process requests and return dynamic content to clients.

Uploaded by

Janhvi Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

PHP: Hypertext Preprocessor

What Is Server-Side Development?


• The basic hosting of your files is achieved through a web server.
• Server-side development involves the use of a programming
technology like PHP or ASP.NET to create scripts that dynamically
generate content.
• It is important to remember that when developing server-side
scripts, you are writing software, just like a C or Java programmer
would do, with the major distinction that your software runs on a
web server and uses the HTTP request-response loop for most
interactions with the clients.
Comparing Client and Server Scripts
• The fundamental difference between client and server scripts is
that in a client-side script the code is executed on the client
browser, whereas in a server-side script, it is executed on the web
server.
• Client-side JavaScript code is downloaded to the client and is
executed there. The server sends the JavaScript (that the user
could look at), but you have no guarantee that the script will even
execute.
• Server-side source code remains hidden from the client as it is
processed on the server. The clients never get to see the code, just
the HTML output from the script.
• Figure 8.1 illustrates how client and server scripts differ.
• The location of the script also impacts what resources it can access.
Server scripts cannot manipulate the HTML or DOM of a page in
the client browser as is possible with client scripts. Conversely, a
server script can access resources on the web server whereas the
client cannot.
• Understanding where the scripts reside and what they can access is
essential to writing quality web applications.
Server-Side Script Resources
• A server-side script can access any resources made available to it
by the server. These resources can be categorized as data storage
resources, web services, and software applications, as can be seen
in Figure 8.2.
• The most commonly used resource is data storage, in the form of a
connection to a database management system. A database
management system (DBMS) is a software system for storing,
retrieving, and organizing large amounts of data.
• The next suites of resources are web services, offered by third-
party providers. Web services use the HTTP protocol to return XML
or other data formats and are used to extend the functionality of a
website.
Comparing Server-Side Technologies
• There are several different server-side technologies for creating
web applications. The most common include:
• ASP (Active Server Pages). This was Microsoft’s first server-side
technology (also called ASP Classic). Like PHP, ASP code (using the
VBScript programming language) can be embedded within the
HTML; though it supported classes and some object-oriented
features, most developers did not make use of these features.
• ASP programming code is interpreted at run time, hence it can be
slow in comparison to other technologies.
• ASP.NET. This replaced Microsoft’s older ASP technology. ASP.NET is part of
Microsoft’s .NET Framework and can use any .NET programming language
(though C# is the most commonly used).
• ASP.NET uses an explicitly object-oriented approach that typically takes longer
to learn than ASP or PHP, and is often used in larger corporate web application
systems.
• It also uses special markup called web server controls that encapsulate common
web functionality such as database-driven lists, form validation, and user
registration wizards.
• A recent extension called ASP.NET MVC makes use of the Model-View-Controller
design pattern. ASP. NET pages are compiled into an intermediary file format
called MSIL that is analogous to Java’s byte-code. ASP.NET then uses a JIT (Just-
In-Time) compiler to compile the MSIL into machine executable code so its
performance can be excellent.
• JSP (Java Server Pages). JSP uses Java as its programming language
and like ASP.NET it uses an explicit object-oriented approach and is
used in large enterprise web systems and is integrated into the
J2EE environment.
• JSP uses the Java Runtime Engine, it also uses a JIT compiler for fast
execution time and is cross-platform. While JSP’s usage in the web
as a whole is small, it has a substantial market share in the intranet
environment, as well as with very large and busy sites.
• Node.js. This is a more recent server environment that uses
JavaScript on the server side, thus allowing developers already
familiar with JavaScript to use just a single language for both
client-side and server-side development.
• Unlike the other development technologies listed here, node.js is
also its own web server software, thus eliminating the need for
Apache, IIS, or some other web server software.
• Perl. Until the development and popularization of ASP, PHP, and
JSP, Perl was the language typically used for early server-side web
development. As a language, it excels in the manipulation of text.
It was commonly used in conjunction with the Common Gateway
Interface (CGI), an early standard API for communication between
applications and web server software.
• PHP. Like ASP, PHP is a dynamically typed language that can be
embedded directly within the HTML, though it now supports
most common object oriented features, such as classes and
inheritance.
• By default, PHP pages are compiled into an intermediary
representation called opcodes that are analogous to Java’s byte-
code or the .NET Framework’s MSIL.
• Originally, PHP stood for personal home pages, although it now is
a recursive acronym that means PHP: Hypertext Processor.
• Python. This terse, object-oriented programming language has
many uses, including being used to create web applications. It is
also used in a variety of web development frameworks such as
Django and Pyramid.
• Ruby on Rails. This is a web development framework that uses
the Ruby programming language. Like ASP.NET and JSP, Ruby on
Rails emphasizes the use of common software development
approaches, in particular the MVC design pattern.
• It integrates features such as templates and engines that aim to
reduce the amount of development work required in the
creation of a new site.
• All of these technologies share one thing in common: using
programming logic, they generate HTML and possibly CSS and
JavaScript on the server and send it back to the requesting
browser, as shown in Figure 8.3.
• Of these server-side technologies, ASP.NET and PHP appear to
have the largest market share.
• ASP.NET tends to be more commonly used for enterprise
applications and within intranets. Due to the massive user
base of WordPress, PHP is the most commonly used web
development technology.
Web Server’s Responsibilities
• In the client-server model the server is responsible for answering
all client requests. No matter how static or simple the website is,
there must be a web server somewhere configured to answer
requests for that domain.
• Once a web server is configured and the IP address associated
through a DNS server, it can then start listening for and answering
HTTP requests.
• In the very simplest case the server is hosting static HTML files,
and in response to a request sends the content of the file back to
the requester.
• A web server has many responsibilities beyond responding to
requests for HTML files. These includes,
• Handling HTTP connections.
• Responding to requests for static and dynamic resources,
managing permissions and access for certain resources,
encrypting and compressing data, managing multiple domains
and URLs, managing database connections, cookies, and state,
and uploading and managing files.
• The LAMP software stack is used, which refers to the Linux
operating system, the Apache web server, the MySQL DBMS, and
the PHP scripting language.
• The Apache web server is an essential part of the web
development pipeline, one should have some insight into how it
works and how it interacts with PHP.
• Apache and Linux
• The Apache web server as the intermediary that interprets HTTP
requests that arrive through a network port and decides how to
handle the request, which often requires working in conjunction
with PHP; both Apache and PHP make use of configuration files
that determine exactly how requests are handled, as shown in
Figure 8.5.
• Apache runs as a daemon on the server. A daemon is an
executing instance of a program (also called a process) that runs
in the background, waiting for a specific event that will activate
it.
• As a background process, the Apache daemon (also known by its
OS name, httpd) waits for incoming HTTP requests.
• When a request arrives, Apache then uses modules to determine
how to respond to the request.
• In Apache, a module is a compiled extension (usually written in
the C programming language) to Apache that helps it handle
requests.
• For this reason, these modules are also sometimes referred to as
handlers. Figure 8.6 illustrates that when a request comes into
Apache, each module is given an opportunity to handle some
aspect of the request.
• Some modules handle authorization, others handle URL rewriting,
while others handle specific extensions.
• Apache and PHP
• As can be seen in Figure 8.6, PHP is usually installed as an Apache
module (though it can alternately be installed as a CGI binary). The
PHP module mod_php5 is sometimes referred to as the SAPI
(Server Application Programming Interface) layer since it handles
the interaction between the PHP environment and the web server
environment.
• Apache runs in two possible modes: multi-process (also called
preforked) or multi-threaded (also called worker), which are
shown in Figure 8.7.
• PHP Internals
• PHP itself is written in the C programming language and is
composed of three main modules:
• PHP core. The Core module defines the main features of the PHP
environment, including essential functions for variable handling,
arrays, strings, classes, math, and other core features.
• Extension layer. This module defines functions for interacting
with services outside of PHP. This includes libraries for MySQL
(and other databases), FTP, SOAP web services, and XML
processing, among others.
• Zend Engine. This module handles the reading in of a requested
PHP file, compiling it, and executing it.
• Figure 8.8 illustrates how the Zend Engine operates behind the
scenes when a PHP page is requested.
• The Zend Engine is a virtual machine (VM) analogous to the Java
Virtual Machine or the Common Language Runtime in the .NET
Framework.
• A VM is a software program that simulates a physical computer;
while a VM can operate on multiple platforms, it has the
disadvantage of executing slower than a native binary application.
Quick Tour of PHP
PHP Tags
• The most important fact about PHP is that the programming code
can be embedded directly within an HTML file.
• PHP file will usually have the extension .php.
• programming code must be contained within an opening <?php
tag and a matching closing ?> tag in order to differentiate it from
the HTML.
• The programming code within the <?php and the ?> tags is
interpreted and executed, while any code outside the tags is
echoed directly out to the client.
PHP Comments
• Programmers are supposed to write documentation to provide
other developers (and themselves) guidance on certain parts of a
program.
• In PHP any writing that is a comment is ignored when the script is
interpreted, but visible to developers who need to write and
maintain the software. The types of comment styles in PHP are:
• Single-line comments. Lines that begin with a # are comment lines
and will not be executed.
• Multiline (block) comments. Each PHP script and each function
within it are ideal places to include a large comment block.
• These comments begin with a /* and encompass everything that is
encountered until a closing */ tag is found. These tags cannot be
nested.
• End-of-line comments. // is encountered in code, everything up to
the end of the line is considered a comment.
• These comments are preferable to the block comments because
they do not interfere with one another, but are unable to span
multiple lines of code.
Variables, Data Types, and Constants
• Variables in PHP are dynamically typed, which means that
programmer do not have to declare the data type of a variable.
• To declare a variable you must preface the variable name with the
dollar ($) symbol.
$count =0;
• In PHP, the name of a variable is case-sensitive and variable names
can also contain the underscore character.
• Rules for Variable declaration
• Variables in PHP starts with a dollar($) sign, followed by the name of
the variable.
• The variable name must begin with a letter or the underscore
character.
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• A variable name should not contain space.
• Writing to Output
• To output something that will be seen by the browser, you can use
the echo() function.
echo ("hello");
• There is also an equivalent shortcut version that does not require the
parentheses.
echo "hello";
• Strings can easily be appended together using the concatenate
operator, which is the period (.) symbol. Consider the following code:
$username = "Ricardo";
echo "Hello". $username;
• This code will output Hello Ricardo to the browser.
Program Control
Functions
• A function in PHP contains a small bit of code that accomplishes one
thing. These functions can be made to behave differently based on
the values of their parameters.
• Functions can exist all on their own, and can be called from anywhere
that needs to make use of them, as long as they are in scope.
• In PHP there are two types of function: user-defined functions and
built-in functions.
• A user-defined function is one that the programmer define.
• A built-in function is one of the functions that come with the PHP
environment.
Arrays
• In general, an array is a data structure that allows the programmer to
collect a number of related elements together in a single variable.
• In PHP, an array is actually an ordered map, which associates each
value in the array with a key.
• A PHP array is not only like other languages’ arrays, but it is also like
their vector, hash table, dictionary, and list collections.
• Array keys in most programming languages are limited to integers,
start at 0, and go up by 1. In PHP, keys must be either integers or
strings and need not be sequential.
• Array values are not restricted to integers and strings. They can be
any object, type, or primitive supported in PHP.
• Defining and Accessing an Array
• The following declares an empty array named days:
$days = array();
• To define the contents of an array as strings for the days of the week:
$days = array("Mon","Tue","Wed","Thu","Fri");
$days = ["Mon","Tue","Wed","Thu","Fri"]; // alternate syntax
• The code below echoes the value of our $days array for the key=1, which
results in output of Tue.
echo "Value at index 1 is ". $days[1]; // index starts at zero
• You could also define the array elements individually using this same
square bracket notation:
$days = array();
$days[0] = "Mon";
$days[1] = "Tue";
$days[2] = "Wed";
// also alternate approach
$daysB = array();
$daysB[] = "Mon";
$daysB[] = "Tue";
$daysB[] = "Wed";
• In PHP, you are also able to explicitly define the keys in addition to the
values. This allows you to use keys other than the classic 0, 1, 2, . . . ,
n to define the indexes of an array.
• Multidimensional Arrays
• PHP also supports multidimensional arrays. Below example, illustrates
the creation of two different multidimensional arrays (each one
contains two dimensions).
• Adding and Deleting Elements
• In PHP, arrays are dynamic, that is, they can grow or shrink in size. An
element can be added to an array simply by using a key/index that
hasn’t been used, as shown below:
$days[5] = "Sat";
• As an alternative to specifying the index, a new element can be added
to the end of any array using the following technique:
$days[ ] = "Sun";
• The advantage to this approach is that we don’t have to worry about
skipping an index key.
• PHP is more than happy to let you “skip” an index, as shown in the
following example.
$days = array("Mon","Tue","Wed","Thu","Fri");
$days[7] = "Sat";
print_r($days);
• What will be the output of the print_r()? It will show that our array
now contains the following:
Array ([0] => Mon [1] => Tue [2] => Wed [3] => Thu [4] => Fri [7] => Sat)
• You can also create “gaps” by explicitly deleting array elements using
the unset() function, as shown in Listing 9.4.
Array Sorting
• PHP has built-in functions. There are many built-in sort functions,
which sort by key or by value. To sort the $days array by its values you
would simply use:
sort($days);
• As the values are all strings, the resulting array would be:
Array ([0] => Fri [1] => Mon [2] => Sat [3] => Sun [4] => Thu [5] => Tue
[6] => Wed)
asort($days); //alternative
• The resulting array in this case is:
Array ([4] => Fri [0] => Mon [5] => Sat [6] => Sun [3] => Thu
[1] => Tue [2] => Wed)
Superglobal Arrays
• PHP uses special predefined associative arrays called superglobal
variables that allow the programmer to easily access HTTP headers,
query string parameters, and other commonly needed information
(see Table 9.1).
• They are called superglobal because these arrays are always in scope
and always exist, ready for the programmer to access or modify them
without having to use the global keyword.
$_GET and $_POST Superglobal Arrays
• The $_GET and $_POST arrays are the most important superglobal
variables in PHP since they allow the programmer to access data sent
by the client in a query string.
• An HTML form (or an HTML link) allows a client to send data to the
server. That data is formatted such that each value is associated with
a name defined in the form.
• If the form was submitted using an HTTP GET request, then the
resulting URL will contain the data in the query string.
• PHP will populate the superglobal $_GET array using the contents of
this query string in the URL. Figure 9.5 illustrates the relationship
between an HTML form, the GET request, and the values in the $_GET
array.
• If the form was sent using HTTP POST, then the values would not be
visible in the URL, but will be sent through HTTP POST request body.
• From the PHP programmer’s perspective, almost nothing changes
from a GET data post except that those values and keys are now
stored in the $_POST array.
• This mechanism greatly simplifies accessing the data posted by the
user, since you need not parse the query string or the POST request
headers.
• Figure 9.6 illustrates how data from a HTML form using POST
populates the $_POST array in PHP.
• Accessing Form Array Data
• If the user selects more than one day and submits the form, the
$_GET['day'] value in the superglobal array will only contain the last
value from the list that was selected.
• To overcome this limitation, you have to change the name attribute
for each checkbox from day to day[].
Monday <input type="checkbox" name="day[]" value="Monday" />
Tuesday <input type="checkbox" name="day[]" value="Tuesday" />
...
• After making this change in the HTML, the corresponding variable
$_GET['day'] will now have a value that is of type array.
$_SERVER Array
• The $_SERVER associative array contains a variety of information. It
contains some of the information contained within HTTP request
headers sent by the client.
• It also contains many configuration options for PHP itself, as shown in
Figure 9.11.
• To use the $_SERVER array, you simply refer to the relevant case-
sensitive key name:
echo $_SERVER["SERVER_NAME"] . "<br/>";
echo $_SERVER["SERVER_SOFTWARE"] . "<br/>";
echo $_SERVER["REMOTE_ADDR"] . "<br/>";
• Server Information Keys
• SERVER_NAME is a key in the $_SERVER array that contains the name
of the site that was requested. If you are running multiple hosts on
the same code base, this can be a useful piece of information.
• SERVER_ADDR is a complementary key telling us the IP of the server.
• SCRIPT_NAME key identifies the actual script being executed.
• Request Header Information Keys
• REQUEST_METHOD key returns the request method that was used to
access the page: that is, GET, HEAD, POST, PUT.
• REMOTE_ADDR key returns the IP address of the requestor.
• One of the most commonly used request headers is the user-agent
header, which contains the operating system and browser that the
client is using. This header value can be accessed using the key
HTTP_USER_AGENT.
• $_FILES Array
• The $_FILES associative array contains items that have been uploaded
to the current script.
• The <input type="file"> element is used to create the user interface
for uploading a file from the client to the server.
• The user interface is only one part of the uploading process. A server
script must process the upload file(s) in some way; the $_FILES array
helps in this process.
• HTML Required for File Uploads
• To allow users to upload files, there are some specific things you must
do:
• First, you must ensure that the HTML form uses the HTTP POST
method, since transmitting a file through the URL is not possible.
• Second, you must add the enctype="multipart/form-data" attribute
to the HTML form that is performing the upload so that the HTTP
request can submit multiple pieces of data (namely, the HTTP post
body, and the HTTP file attachment itself).
• Finally you must include an input type of file in your form. A simple
form demonstrating a very straightforward file upload to the server is
shown in Listing 9.12.
• Handling the File Upload in PHP
• The corresponding PHP file responsible for handling the upload (as
specified in the HTML form’s action attribute) will utilize the
superglobal $_FILES array.
• This array will contain a key=value pair for each file uploaded in the
post. The key for each element will be the name attribute from the
HTML form, while the value will be an array containing information
about the file as well as the file itself.
• The keys in that array are the name, type, tmp_name, error, and size.
• Figure 9.12 illustrates the process of uploading a file to the server and
how the corresponding upload information is contained in the
$_FILES array.
The values for each of the keys are,
• name is a string containing the full file name used on the client
machine, including any file extension. It does not include the file path
on the client’s machine.
• type defines the MIME type of the file. This value is provided by the
client browser and is therefore not a reliable field.
• tmp_name is the full path to the location on your server where the
file is being temporarily stored. The file will cease to exist upon
termination of the script, so it should be copied to another location if
storage is required.
• error is an integer that encodes many possible errors and is set to
UPLOAD_ERR_OK (integer value 0) if the file was uploaded
successfully.
• size is an integer representing the size in bytes of the uploaded file.
• Checking for Errors
• For every uploaded file, there is an error value associated with it in
the $_FILES array.
• The error values are specified using constant values, which resolve to
integers.
• The value for a successful upload is UPLOAD_ERR_OK, and should be
looked for before proceeding any further.
• The full list of errors is provided in Table 9.2 and shows that there are
many causes for bad file uploads.
• File Size Restrictions
• There are three main mechanisms for maintaining uploaded file size
restrictions: via HTML in the input form, via JavaScript in the input
form, and via PHP coding.
• The first of these mechanisms is to add a hidden input field before
any other input fields in your HTML form with a name of
MAX_FILE_SIZE. This technique allows your php.ini maximum file size
to be large, while letting some forms override that large limit with a
smaller one.
• Moving the File
• Reading/Writing Files
• There are two basic techniques for read/writing files in PHP:
• Stream access. In this technique, our code will read just a small
portion of the file at a time. While this does require more careful
programming, it is the most memory-efficient approach when reading
very large files.
• All-In-Memory access. In this technique, we can read the entire file
into memory (i.e., into a PHP variable). While not appropriate for
large files, it does make processing of the file extremely easy.
• Stream Access
• The function fopen() takes a file location or URL and access mode as
parameters. The returned value is a stream resource, which you can
then read sequentially.
• Some of the common modes are “r” for read, “rw” for read and write,
and “c,” which creates a new file for writing.
• Once the file is opened, you can read from it in several ways. To read
a single line, use the fgets() function, which will return false if there is
no more data, and if it reads a line it will advance the stream forward
to the next one so you can use the === check to see if you have
reached the end of the file.
• Finally, when finished processing the file you must close it using
fclose(). Listing 9.19 illustrates a script using fopen(), fgets(), and
fclose() to read a file and echo it out.
• To write data to a file, you can employ the fwrite() function in much
the same way as fgets(), passing the file handle and the string to
write.
• In-Memory File Access

You might also like