Advanced PHP Techniques and Features

colonteeSoftware and s/w Development

Nov 4, 2013 (3 years and 8 months ago)

68 views

Advanced PHP Techniques and Features


Stephen M. Corcoran

Department of Computer Science

University of Wisconsin
-
Platteville

corcorans@uwplatt.edu



Abstract


Since 1994 PHP has been widely known and has changed for the better good of web
development. Development with PHP is endless in a sense that a developer can create small or
large scale web applications as well as GUI applications. Since PHP is an open sour
ce language,
the support for developing PHP; is for the developers, by the developers. Using a server
-
side
scripting language from a business standpoint is beneficial in terms of support, cost,
extensibility, functionality and learnability. With the number

of packages, classes and libraries
present to use with PHP, PHP itself in a sense is endless. No matter the length of time a
developer spends creating web applications, he or she still learns new things daily.



Introduction


PHP has changed rapidly and

matured greatly since the beginning; being an open source
language allows others to better the language as fit.

“Over the past five years PHP adoption
within the enterprise has accelerated, and it is now going mainstream within IT”
[4]
.
With the
large ext
ensibility and support that PHP has to offer many large corporations/businesses are
tending to move towards building their applications with PHP.
“With the financial crises that
started in 2007 we are seeing the same trends as we did with dot
-
com bust. Com
panies are
looking to do more with less as that is the only way for them to continue to be competitive and
grow”
[4].

The adaptability, cross platform support, the documentation and support, and
reducing in learning has increased the popularity of PHP for

companies that want to build large
scale applications fast and efficiently.



History


PHP was originally created in 1994 by Rasmus Lerdorf which
was

a bunch of CGI scripts
written in C. The original name for PHP was PHP/FI, later called phptools, which
allowed web
developers to embed code inside HTML tags. The original meaning to PHP was Personal Home
Page Tools which Rasmus used to maintain his own personal website with. Within the first year
of PHP, which was still not available to public developers; P
HP was rewritten to encapsulate
more functionality such as database interaction and other useful tools to create dynamic web
applications. In late 1995, PHP tools was released to the public as open source and encouraged
developers to look and fix bugs that

they saw fit.


In early 1997 two Israeli students, Andi Gutmans and Zeev Suraski, used PHP to drive a
shopping cart application for a school project. With the complexity of an application like this,
Gutmans and Suraski stumbled upon numerous bugs within P
HP itself which led them to
exploration of the code to find the underlying issues. These two developers are big contributors
to PHP and how it has evolved over time. Gutmans and Suraski are still working together to
better the PHP source code, writing tut
orials, and attending PHP development conferences to
help better developers. With the support offered by the two, this has helped PHP achieve its
presence and notability in development.


Since the change to the PHP source code by Gutmans and Suraski, other

developers have taken
the same initiative to change and add features as seen needed. In 1999 The Zend engine was
released as the first framework for PHP. Since then, regular updates and releases have occurred
to ensure that any security flaws are fixed an
d more functionality is added to PHP.



Weak Types and Type casting


PHP is a loosely typed language to where you can declare variables without types and mix and
match variable types with each other. In

PHP when declaring variables a type is not required nor
allowed. When declaring a variable, it is as simple as
$my_variable = ‘Hello’
; to specifically
make
$my_variable

a string you would either need to do
$my_variable = (string)‘Hello’

or
$my_variable =
strval(‘Hello’)
. Working with classes and the advanced object
-
oriented patterns
in PHP it may be easier for some to specify
types to ensure strange things don’t

happen to the
data being passed or returned from a function or class. Another way to specify ty
pes for variables
it to use the settype function which would look as follows,
settype($my_variable, “string”)

or
any other type that you would want
$my_variable

to be.
If a developer does not want to use the
settype function for the application that he or
she is working on, then they have the option to use
the gettype() function which would return what type a specific variable is. Since PHP is a weakly
typed language like ruby and python, issue can occur when developing large scale applications
that do not
have the proper error and type checking in place.



Frameworks


Symfony, Zend, Yii and CakePHP are the popular frameworks for PHP developers which uses
an MVC (Model, View, Control) architecture. Using frameworks such as the ones listed are great
for small

or large scale applications to help better the system, reduce the maintenance cost and
increase the lifecycle of an application. However, learning the MVC architecture can take time
and cost money for developers to learn and completely understand the syst
em. Despite the steep
learning curve of an MVC architecture, using a framework can be beneficial for any company.


The popular frameworks listed above are available free of charge and have support for 64 or 32
bit architectures with cross platform compati
bility. Each framework has the similar MVC layout
but have largely different in terms of
creating;

developing and maintaining large scale
applications. Management applications built upon a framework can be difficult at first for
developers new to the MVC a
rchitecture and a framework. By being able to fully understand a
framework and the advantages that they provide, the developing of an application will be greatly
reduced.



Packages and Libraries


PHP has numerous libraries that are available to the devel
opers such as curl, sockets, SQLite,
FTP, Apache, and SMTP. The most popular and used package is curl which has a lot of
important features and functionality for web application developers. For PHP developers the
most common libraries that are used are Apa
che for the web server setup, SMTP for an email
system, MySQL or SQLite for database connections, and FTP to allow file uploads and
downloads. Depending on
Linux

environment setup, some of the libraries of PHP setup may be
included by default and some woul
d have to be installed separately before usage.



Curl



Curl stands for client urls which is a command line tool which allows PHP to connect and work
with web sites, ftp files and execute shell commands. Curl was created by Daniel Stenberg,
which allows P
HP to connect and actively communicate with different web servers and protocols
of all types. Using this package allows for http and https connections, form uploads, username
and password authentication, and web certifications.




Pear



Pear is a package
for PHP which stands for PHP extension and repository which allows other
developers to use other packages to better their application. Pear is an open source software
which allows other developers to create useful packages or libraries that may help others

in
developing applications. Some of the popular packages that pear has to offer is web form
creation and form validation, xml parsers, and email engines. Using a package such as this one,
allows web applications to be developed quicker and more efficient
than before. To fully
understand the
capabilities

and the
available

packages within pear that can be used; visit
pear.php.net or get yourself a copy of
Foundation of PEAR Rapid PHP Development
.



Object
-
Oriented PHP


PHP is an object
-
oriented language that

can be procedural as well. PHP uses and has the same
class types as other programming languages. Abstract and interface are the typical types, with the
option to extend or implement other classes. The difference that PHP has compared to other
languages is

how declaring variables accessed at which scope, the type hitting within classes and
the ability to fully clone objects. Even though languages use the this object to access class
variables or functions such as this.variable or
this
-
> variable
, PHP does
$
this
-
> variable

despite the convention on variable declaration is
$variable = “hello
”. Below will demonstrate
how these different features are used at different levels within classes
.



Declaring variables


When declaring class variables or global variables, there are numerous ways to do so. Declaring
variables on the global scope can happen in two different ways; using the define feature or the
keyword global. The few examples below will show the different b
etween the three different
ways to declare a variable. See appendix A for the usage of global variables, appendix B for
usage of constant variables and appendix C for the usage of define when
declaring variables
.



Object Cloning


PHP allows object clonin
g which is in a sense object copying or also known as a shallow copy.
PHP5 introduced a new keyword called clone which will clone an object called object1 to a new
object called object2. When using the clone keyword, object2 will receive the the value and
properties that are associated with object1. Even though cloning an object can be useful,
sometimes you don’t want the second object to have the same properties as the first one. When
releasing the new clone functionality, PHP also has a function __clone,
in which when the
original clone function is called any property changes within __clone will take in effect for the
new object. Having the __clone function can allow property change and/or value change that you
want to take place. Using __clone will allow
you to change where the property in the new object
will be referenced to. Below is an example of how object cloning using a class will work in
which all the properties that object1
possess

object2 will now have but will also be referenced by
object2. See a
ppendix D for a full example of cloning using the __clone method.



User
-
level overloading



A developer can overload a method within PHP by simply using the __ notation. The most
common overloaded functions are __get(), __set(), __call(), __construct() a
nd __destruct().
Using the __construct and __destruct are for creating and destroying objects created from
instantiating a class. The __call() function is called by default if it exist within a class which
allows different functions to be called depending

on the parameters passed. The __call() function
has two parameters. The first is the function and the second is the value. Using the __get() and
__set() functions will allow a developer to get and set values of a variable that is either protected
or priva
te within a class.



Advanced Techniques and Classes




PHP CLI (Command Line Interface)



CLI allows a developer to run PHP code or files outside of the web browser. CLI
formally

was a
separate
install

for PHP 4 however, more recently PHP now has cli inc
luded with the PHP install
package for all platforms. The biggest difference between PHP on the web and cli is that cli does
not use nor create html, the .php extension on a file is not needed and the PHP script has to have
#!/usr/bin/php as the very first

line of the file. Using the #!/usr/bin/php can also be included to
any PHP file used on the web without any issues. After the script is complete that will be used
via cli, the user will need to type PHP filename to execute the PHP script. Along with typi
ng
PHP filename there can be a number of argument passed as well, such as
-
c which tells cli to
look for php.ini files,
-
n which says to ignore .ini file, and
-
d which is to set values for an .ini
file. Also using the cli you can pass arguments to the scri
pt being called. Inside the PHP script
you would use $_SERVER[‘argc’] to get the count of the number of arguments passed and
$_SERVER[‘argv’] which stores the parameters passed in, in an array. Please refer to appendix
E for an example on using php cli.



SSH2


The ssh2 class is built upon an existing library for PHP called libssh2 which is not a default
install for PHP. Using the libssh and ssh2 class for PHP will allow developers to remote access
to different machines. The type of access that is allowed u
sing both of these tools are shell,
tunneling, file transfer and remote exec. The example code below is a custom ssh class which
connects to a remote server which requires a username, password and server address. After,
a
separate

function which requires a

Unix/Linux command to be executed and finally a function
that returns the results from the input stream. To see a full example of the sshs usage
,

please refer
to appendix F for a full custom class that demonstrates how to interact with the sshs class.



Mail


Using the PHP mail function would require a server to be setup to support SMTP which is an
advanced install and configuration. Having a mail function can be useful to companies who have
large scale applications that generate reports and want the sent

or stored elsewhere. To write a
script that sends mail with basic content is very simple. However, when you start adding advance
content such as file attachments and/or html content, things can get complicated and confusing.
Below is an example of sending

basic content to another users/developers email. Sending content
as file attachments such as csv files or any similar content would be easier to use packages from
pear or any predefined libraries to reduce development time and ensure correctness. Please r
efer
to appendix G for an example and usage of the mail function.



Sessions and Cookies


Sessions and cookies in PHP are used just like they are in other
application;

they are to stored
data and ensure that the person accessing a specific secure page is w
ho they say they are. Using
sessions and cookies are a simple way to ensure security when logging in and out
of the

applications of any type (whether it is secure data or not). To learn these features in PHP are
fairly simple, but can be made very complex
if the developer does not understand how to use
them properly.




Sessions



The general idea of sessions is the assign a user or visitor to a specific page a unique identifier
which references stored information on the server about the individual. Prior to PHP 4 creating
session handling was purely up to the developer which lead
to poor implementation of sessions
and security issues. With the number of security issues, the _SESSION array was created in PHP
4, which is an array that stores session information in files on the server. When using a session
the session_start() function

needs to be called on any page that is going to use or set a session
variable. To set a session variable you would do $_SESSION[‘variable_name’] = “something”.
With the ‘variable_name being any name you want to use such as id or name. To destroy a
session

once a user is completed, the session_destroy() function should be called.



Cookies


Using cookies is good practice to uses side
-
by
-
side with sessions to ensure the user is completely
secure when logging into a system. Cookies are used to store small str
ings of data from the
server on the client side of an application. The most common pieces of information stored within
a cookie is a name, value and and expiration time, which is most commonly used for login pages
to either require credentials to be entere
d upon the next visit or not. Using cookies alone is not a
way to ensure individuals are logging in as themselves due to the fact that they can be altered or
disabled by a user. When creating a cookie the setcookie() function will be called which has the
f
ollowing syntax setcookie(name, value, expire, path, domain) where path and domain are
optional. The name parameter is usually a username for a login page, the value would be the
users actual name and then the duration of the cookie. When deleting a cookie

you would use the
same syntax as creating cookie except, the time would be a time that has already passed.



Database Connections and PDO


PHP has support for database connection to some of the most popular database such as Oracle,
MySQL, SQLite, MongoDB
and MS SQL. Each connection has a specific class for how to
define connections, execute queries, and get the results returned from the database. All of
these

classes are very similar except in the calling and naming convention of the functions and how
para
meters can be passed. Using the basic classes alone may not be enough for what a developer
wants in his or her application, using a consistent connection or PDO may be the best for an
application with database connections. Using PDO (
PHP Data

Objects) will

help ensure that
there is always a consistent connection to the given database you are working with. Each
database connection class also supports a PDO connection and usage. The ideal way to handle
database connections (whether it being using the base cla
ss of the connection or the PDO way) is
to create a custom class to the way you want errors, results and connections to be handled.



Future


The next major release for PHP is PHP 6 which has a few new features; enhanced array
indexing, full
Unicode

support, enhance performance issues, and break to labels. The release
date and full implementation of PHP 6 in unknown at this time due to the struggle with fully
implementing
Unicode

support. Enhancing array indexing and performance will go hand in hand
to help speed up an application and to use less memory of the server. Adding break to labels will
give developers the options to break to labels which is essentially a goto statement or in
assembly jumping to a label. I feel that adding a feature such as a

break to label option is going
backwards in
development;

however, the implementation of this feature may change and have
a
restriction which has

yet to be determined.



Conclusion


Over the years PHP has become a widely used
language

in the development in
dustry to support
large scale web applications. As the community and development with PHP continues to expand,
the language will continue to grow and support functionality and may implement features that
other languages have or have not achieved yet. This
paper covered the advanced features and
techniques that can be used when creating websites or web applications using PHP. To learn
more about the basics before trying to tackle the features discussed please visit
www.php.
net

for
the full documentation of all current PHP functions and learning the basics.

After learning the
basics for PHP this paper and presentation would be a very helpful tool to start leaning advanced
features and extend your application farther and bette
r than you though was possible.



References


[1] The PHP Group (2012, MARCH 15). PHP: Hypertext PreProcessor.
PHP
. March, 16, 2013,
from
http://www.php.net


[2] Quin, L. (2011). World Wide Web Consortium (W3C).
W3C
. March 15, 2013, from
http://www.w3.org



[3] The PHP Group(n.d.). PHP Extension and Application Repository.
PEAR
. March 16, 2013
from
http://pear.php.net


[4] Coggeshall, J. & To
cker, M. (2009).
Zend Enterprise PHP Patterns
. New York, NY: Apress.


[5] Good, N. A. & Kent, A. (2006).
Foundations of PEAR: Rapid PHP Development
. New York,
NY: Apress


[6] Shafik, D., O’Phinney, M. W., Turmelle, L., Fuecks, H., Balbo, B. (2007).
The PHP

Anthology
. Australia: sitepoint.


[7] Ullman, L. (2007).
PHP 5 Advanced
. Berkeley, CA: Peachpit Press.


[8] Welling, L. & Thomson, L. (2009).
PHP and MySQL Web Development
. Boston, MA:
Addison
-
Wesley.


[9] Atkinson, L. (2004).
Core PHP Programming
.

Upper Saddle River, NJ: Pearson Education
Inc.



Appendix


[A]
-

Global variable usage





[B]
-

Constant variable usage





[C]
-

Define variable usage





[D]
-

Object cloning





[E]
-

CLI Example


Example script to print parameters



shell

command




[F]
-

SSH example



[G]
-

Mail example