SlideShare a Scribd company logo
Learn to build with php
This manual is the intellectual property of MakeUseOf. It must only be published in its original form. Using
parts or republishing altered parts of this guide is prohibited without permission from MakeUseOf.com
Think youโ€™ve got what it takes to write a manual for MakeUseOf.com? Weโ€™re always willing to hear a pitch!
Send your ideas to justinpot@makeuseof.com.
share:
by Matthew Hughes
http://www.matthewhughes.co.uk/
Published March 2014
LEARN TO BUILD WITH PHP
3HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
Table Of Contents
1.ย Introduction  5
1.1ย The History Of PHP 6
1.2ย What Are We Going To Cover? 6
1.3ย All About LAMP 6
1.4ย Setting Up Your Development Environment 7
Windows 7
Linux 7
OS X 8
Android 8
1.5ย Choosing The Right Text Editor 8
1.6ย Prerequisites 9
2.ย Hello World!  10
2.1ย Does PHP Have To Be Surrounded By HTML? 11
2.3ย Basic Language Concepts 11
Variables 11
If Statements 11
While Statements 12
For Loops 12
Functions 12
2.4ย Moving On 13
3.ย Forms  14
3.1ย How Forms Work In HTML 14
3.2ย Creating Our First Form 14
3.3ย Handling This Input With PHP 15
4.ย Databases  17
4.1ย MySQL Datatypes 18
Varchar(x) 18
Integer 18
Other MySQL Datatypes 18
4.2ย Creating Our Database 18
4.3ย The Wrong Way To Query The Database 19
LEARN TO BUILD WITH PHP
4HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
4.4ย Meet MeekroDB 20
5.ย Getting Content From The Database  22
5.1ย Selecting And Presenting Results 22
5.2ย Styling 23
6.ย Logins And Authentication  24
6.1ย The Users Table 24
6.2ย PHP Sessions 24
6.3ย Registering Users 26
6.4ย Logging In 26
6.5ย Logging Out 27
7.ย Conclusion And Further Reading  28
LEARN TO BUILD WITH PHP
5HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
1.ย Introduction
What was your favorite subject at school?
If youโ€™re anything like me, I bet you loved the arts. The humanities. You know, the subjects derided by some as being
vacuous and nebulous in nature, but regardless you loved studying them because youย loved being creative.
I bet you never thought of your IT classes in the same way you thought of English Language or art; as a purely cre-
ative endeavor.
Thatโ€™s a pity. Learning to program is a bit like doing a creative language class. You have an idea, and you can execute
that however you like. Itโ€™s pure creativity, but instead of baring your soul on paper, you are commanding a computer
to do your bidding. If you can dream it, and if you can describe it in a way your computer understands, then you can
make it.
The way we talk to computers is through abstractions called programming languages. There are a whole bunch of
these out there, each with their own advantages, disadvantages and truly bizarre idiosyncrasies. Theyโ€™re imperfect by
nature, but people use them to create incredible and wonderful things.
One of these languages is called PHP.
You may have heard of it before. This is the language that Facebook, WordPress and Wikipedia use to serve billions
of requests, daily. It is the de-facto language used for teaching people to program for the web. Itโ€™s beautifully simple,
but brilliantly powerful.
And in this guide, Iโ€™m going to teach you how you can use it to build your own websites.
Do you have a killer startup idea you donโ€™t quite know how to execute? Do you want to learn the language used to
extend WordPress? Are you just curious about web programming? Do you just want to learn the skills needed to stay
relevant in the modern, tech-oriented knowledge economy?
Whatever your motivation, this book aims to teach you the basics of the PHP programming language. But first, letโ€™s
have a bit of a history lesson.
LEARN TO BUILD WITH PHP
6HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
1.1ย The History Of PHP
In the infancy of the Internet, things were a bitโ€ฆ Well? Flat.
Sites werenโ€™t particularly interactive, and those who visited these sites were faced with a relatively one-directional
experience. Adding even the simplest aspects of user engagement was incredibly difficult, left in the domain of the
computer scientists and the expert programmers.
And then Rasmus Lerdorf came around. This Canadian-Greenlandic coder created the PHP programming language,
which allowed people to easily add the simplest facets of interaction to their web pages. It was new, it was brave, and
it took off almost immediately.
Rasmus Lerdorf couldnโ€™t have predicted the impact his idea would have upon the world.
A community began to form, with programmers and companies willingly providing time and money to fuel the develop-
ment of the language. Slowly but surely, PHP began posing a serious challenge to Sun (now Oracle) and Microsoft,
who were hoping to gain traction in the web-development market with their Java and ASP platforms. The rise of the
PHP programming language could only be described as startlingly rapid.
That was 20 years ago. An age, in the computer world. Since then, the PHP programming language has become the
preferred way for millions of programmers, who use PHP in their jobs, to get involved in open source and to bring their
ideas to life. Itโ€™s a staple of the digital world.
You can become one of those millions. This book will show you how.
1.2ย What Are We Going To Cover?
This is a pretty short book, but weโ€™re going to cover a lot. In just a few pages, weโ€™re going to create a simple clone of
Twitter.
Whilst itโ€™s not going to have the same feature-set and polish of the popular micro-blogging site, but we will be able to
post 140 character messages with an account we will log into.
1.3ย All About LAMP
By now, we should know that PHP is an incredible language for creating interactive web pages. But we havenโ€™t talked
about how we turn that code into a real-life product. So, letโ€™s do that.
For the most part, PHP code runs within a web server. A web server is responsible for sending web pages to anyone
who navigates to a specific domain name or IP address.
The most common choice of web server is the ludicrously popular Apache web server. This open source, cross-plat-
form software project powers the majority of the Internet, with 45% of all websites serving pages from the Apache web
server. However, itโ€™s helpful to note that there are other web servers available, including LightTTPD and Microsoftโ€™s
IIS.
This forms the second letter in the LAMP acronym, which stands for Linux, Apache, Mysql and PHP. We know what
PHP is. I just explained to you what Apache is. You might have heard of Linux at some point. But what is the โ€˜Mโ€™ in
Lamp? MySQL.
Letโ€™s talk about MySQL. Iโ€™d put money on your website having to store information that your web application has gath-
ered. Whatโ€™s more, I bet youโ€™d want to store that information somewhere that is structured, safe and organized. Yep,
youโ€™re going to have to use a database, and for most purposes MySQL is a pretty solid choice. Weโ€™re going to talk
about this later on.
Finally, letโ€™s briefly touch on Linux. Most PHP websites are served from systems running the popular, open-source
Linux operating system. However, you donโ€™t have to use Linux as your development environment if you donโ€™t want to.
Everything in this book can be used on OS X, Windows and Android
An operating system, Apache, MySQL and an installation of the PHP programming language are the four constituent
parts of the most common PHP configurations. But how do we get our hands on them?
LEARN TO BUILD WITH PHP
7HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
1.4ย Setting Up Your Development Environment
Unlike some programming languages, setting up a PHP development environment is easy. Indeed, there are a num-
ber of packages which do all the hard-work for you, and save you the hassle of installing each component (PHP,
MySQL and Apache) individually.
Windows
The easiest way to set up a PHP development environment in Windows is with XAMPP by Apache Friends. This pack-
age includes MySQL, a copy of the PHP programming language and the Apache web server, as well as an administra-
tive control panel, and plugins for SSL (the protocol used to encrypt traffic on a network) as well as sending Email.
XAMPPย is free, and can be found on the Apache friends site. Itโ€™s important to stress that there are two versions of
XAMPP available. One has a version number of 1.8.2 and runs a slightly older version of the PHP programming lan-
guage, and the other has a version number of 1.8.3 and runs a current version of PHP. Whilst I would strongly recom-
mend that you download the latest version, the contents of this guidebook should work with both.
Linux
Linux is a bit tricky. There are a number of operating systems that exist under the โ€˜Linuxโ€™ umbrella, although they each
handle the installation of software packages in different ways.
If youโ€™re using Ubuntu and any distribution which uses the Ubuntu repositories, you can run:
sudo apt-get install lamp-server^
This will install a LAMP server, with all the components required for following this article. This process is explained in
greater depth in this article, where I show youย how to install a LAMP serverย as part of installing the WordPress blog-
ging platform.
These instructions will not work on distributions that use YUM or RPM for their package management, with the instruc-
tions for setting up a LAMP server differing significantly. I would recommend you to have a look at the documentation
that came with your operating system.
However, there is another option. Remember XAMPP? Well, it just so happens that it comes with support for Linux,
and can be downloadedย here. However, where possible, I would strongly recommend that you install your LAMP
server through your package manager.
LEARN TO BUILD WITH PHP
8HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
There are a few reasons for this. Firstly, it would be slightly better integrated with your operating system and can be
easily updated. Furthermore, installing PHP via the command line is good practice should you everย deploy your ap-
plication to a VPS server.
OS X
I use OS X as my main development platform. I like the flexibility it provides me, and setting up a PHP development
environment in OS X is insanely easy.
Iโ€™m quite partial toย MAMP. This comes in two products, with one being free and the other costing $59 USD (or โ‚ฌ39).
However, the free version is more than adequate for the purposes of this guide book.
Getting MAMP is a matter of grabbing a ZIP file from the website, double-clicking a pkg file and pressing โ€˜continueโ€™ as
often as necessary.
As before, itโ€™s entirely possible for you to create a PHP development environment using XAMPP, which is also ported
to OS X. Itโ€™s entirely up to you.
Android
Android? I mean, Android is great for sending tweets and killing time on Angry Birds. But software development? Nah.
right?
Wrong. If youโ€™ve bought an Android cell phone in the past year or so, odds are quite good that itโ€™s running a CPU
thatโ€™s just as powerful as any VPS youโ€™ll get for under $10. And that means that itโ€™s good enough to run PHP, Apache
and MySQL.
There are a lot of Android LAMP servers on the market, but I really like Palapa Server. It runs nicely on an aging
Nexus 7 tablet, and Iโ€™ve even managed to shoehorn Android onto it without any real difficulties. Itโ€™s not the ideal devel-
opment environment, but itโ€™s possible.
1.5ย Choosing The Right Text Editor
Youโ€™re probably familiar with what word processors are. Odds are good that youโ€™ve used Microsoft Word, Open Office
or Google Docs to write letters, school assignments or business documents.
But you might not know that itโ€™s not possible to use a regular word processor to develop software and websites. Why
is that? Mainly because when you write a document, you leave all sorts of extraneous markup and formatting in the
LEARN TO BUILD WITH PHP
9HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
file. The end product isnโ€™t just the words you write, but also the alignment of each word and its styling.
As a result, when writing code, we use text editors. What are they? Simply put, these allow you to write files which are
saved in purest plaintext. No formatting. Just characters.
When writing code, I tend to use Sublime Text 2. It comes with an indefinite free trial (although, it does occasionally
nag you to upgrade), and heaps of features, which makes writing software with it a joy.
In particular, it comes built in with syntax highlighting for PHP, Javascript and HTML, which makes it really easy to
read the code you produce. You can download Sublime Text 2 here, and it is available for Linux, Windows and OS X.
If youโ€™re not convinced, you can read more aboutย Sublime Text 2.
If youโ€™re on Android, youโ€™ll find that your choices are quite limited. Iโ€™m fond on VimTouch, which is available for free on
the Google Play store. Vim has a pretty steep learning curve, but itโ€™s well worth a try. Read more about why itโ€™sย worth
giving Vim text editor a chance.
1.6ย Prerequisites
Weโ€™re going to jump straight in to learning PHP. Whilst I plan to gently introduce you to this amazing programming
language, there are some things Iโ€™m expecting you to understand beforehand.
Specifically, Iโ€™m going to expect that you understand how a website is structured with HTML. If you donโ€™t know your
p tags from your span tags, thatโ€™s not a problem. MakeUseOf has aย XHTML bookย which will bring you up to
speed. Read through that and once youโ€™re feeling confident, read on.
Feeling adventurous? Why not learn about the latest version of HTML with ourย HTML5 e-book? Whilst itโ€™s not essen-
tial, it might help you later on.
LEARN TO BUILD WITH PHP
10HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
2.ย Hello World!
Time for a whistle-stop tour of PHP. And where better to start than the traditional โ€˜Hello World!โ€™ program.
But first, weโ€™re going to need to know where to store our PHP files. We store them in a place called the โ€˜Document
Rootโ€™, which sounds complicated, but it really isnโ€™t. All that means is whatever is stored in this folder will be available to
anyone who visits the computerโ€™s IP address with their web browser.
The location of your document root varies on how your PHP environment is set up. If you are using MAMP on OS
X, you can find it in /Applications/MAMP/htdocs. If youโ€™ve installed your LAMP server on Linux using your distribu-
tionโ€™s package manager, your Document Root directory will most likely be /var/www. On XAMPP, your root directory is
located in C:/xampp/htdocs/.
Once youโ€™ve navigated to the Document Root folder, create a file called โ€˜index.phpโ€™ and add the following lines.
!doctype html
html lang=โ€enโ€
head
meta charset=โ€UTF-8โ€
titleMicroblogging Site/title
/head
body
/body
/html
Nothingโ€™s going on here, but we do have the skeleton of a web page. This homepage will be found at โ€˜localhostโ€™.
Sometimes itโ€™s followed with a port number, which usually is โ€™80โ€™, โ€˜8888โ€™ or โ€˜8080โ€™. Although, depending on the PHP
development package you use, can vary. If youโ€™re unsure, refer to the documentation.
Now, letโ€™s write our first lines of PHP! In between body and /body, write
?php echo(โ€œHello World!โ€); ?
So, letโ€™s break this down.
All PHP code has to be between a โ€˜?phpโ€™ and โ€˜?โ€™. If it isnโ€™t then the web server will not execute it. Then, we have
โ€˜echoโ€™. As Iโ€™m sure youโ€™ve guessed, this function prints content to the browser. Finally, we have the content we want
to print out. This is surrounded in parentheses and speech marks. Itโ€™s worth noting that parentheses are (for the most
part) optional, when it comes to calling a function.
As we have finished the โ€˜echoโ€™ statement, we finish it with a semicolon. If this is missing, your code will not work.
LEARN TO BUILD WITH PHP
11HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
If it works, you should see โ€˜Hello Worldโ€™ in your browser.
2.1ย Does PHP Have To Be Surrounded By HTML?
No.
If weโ€™re performing an action that should be displayed immediately within the web browser, we can have it nested
within the HTML document. This is called inline PHP, and thatโ€™s what we used to print โ€˜Hello Worldโ€™ to the screen.
However, for anything more complex, we should always aim to put it in its own PHP document. As with the previous
example, the file should end with a โ€˜.phpโ€™ extension and all code should start and end with โ€˜?phpโ€™ and โ€˜?โ€™.
2.3ย Basic Language Concepts
Before we go on, letโ€™s look at some language concepts in PHP. Whilst this isnโ€™t an exhaustive list, it does include the
essentials required to be productive as a PHP programmer. Once weโ€™ve gone through these, weโ€™re going to look at
using some of these concepts within the context of forms.
Variables
Variables are a concept found in virtually all programming languages. They are used to store a value, which can be
retrieved, used and changed later on.
You might be familiar with a language that requires you to specify the value of a variable. These include C#, C, C++
and Java, and usually look a bit like this.
int x = 10;
You also might be familiar with Javascript, where variables are declared with the โ€˜varโ€™ keyword.
var x = 10;
In PHP, however, variables are declared with a dollar symbol.
$x = 10;
PHP variables cannot start with a number or a special character other than an underscore. Furthermore, they cannot
be called โ€˜thisโ€™, as this is a reserved keyword.
If Statements
If statements are useful. They allow you to execute code contingent upon a specific condition being met. Consider the
following code.
$x = 5;
if ($x == 4) {
echo(โ€œHello Worldโ€);
} elseif ($x == 3) {
echo(โ€œHello Daveโ€);
} else {
echo(โ€œHello Brianโ€);
}
LEARN TO BUILD WITH PHP
12HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
So, the first condition being examined is if $x equals four (note the double equals symbols). Since it isnโ€™t, the PHP
interpreter will look at the next conditional statement, which is if $x equals 3. If it doesnโ€™t, it will move on to the final
statement, which will echo out โ€˜Hello Brianโ€™ if none of the conditions have been met.
You can check if a variable is empty (also known as โ€˜nullโ€™, or a โ€˜null valueโ€™) by preceding it with a ! in the โ€˜ifโ€™ statement.
For example:
if (!$x){
echo(โ€œx is emptyโ€);
}
While Statements
While statements execute code repeatedly whilst a condition is being met. Consider the following code.
$x = 10;
while ($x  1) {
echo($x);
$x = $x - 1;
}
This code looks at the value of $x, and if it is greater than one, it will echo the value of $x and then remove one from it.
It will do this, until the condition of โ€˜$x  1โ€™ is no longer met. That is to say, that it equals 1 or less.
For Loops
For loops are, as a concept in programming, often quite intimidating to beginners. They shouldnโ€™t be, though. Whilst
theyโ€™re ostensibly quite complex, theyโ€™re really easy to understand when broken down. Letโ€™s write a simple for loop
that counts from one to ten.
for($i = 0; $i  10; $i++){
echo($i);
}
Whatโ€™s happening here? Well, first we create a variable with a value of 0 ($i = 0;). We then set the condition of โ€˜if $i
is less than 10, carry onโ€™ ($i  10). We then add one to I ($i++) and execute the contents of the curly braces, looping
back on the original code.
Functions
Functions are a useful tool when it comes to programming. They allow you to write code that is more consistent, and
spend less time writing the same things over and over again by compartmentalizing code into a single snippet that can
be called when required.
Theyโ€™re also really simple to create. This is how we make a function that echoes out โ€˜Hello Worldโ€™ when called. This
function will be called โ€˜sayHello()โ€™.
function sayHello(){
echo(โ€œHello Worldโ€);
}
You can also pass functions values. These are known as parameters, and are put within the two parentheses in the
first line of the declaration. For example:
function sayHello($hello){
echo($hello);
}
And can be called as follows:
sayHello(โ€œHello Worldโ€);
LEARN TO BUILD WITH PHP
13HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
Finally, we can get functions to return values.
function returnHello(){
return โ€œHello Worldโ€;
}
And can be used as follows.
x = returnHello();
echo(returnHello());
2.4ย Moving On
Weโ€™ve learned the basics of flow control in the PHP language, as well as how we can use variables and functions to
store values and snippets of code for future use. In the next chapter, we will expand upon our understanding of the
PHP programming language by looking at how we can capture data with forms, thus forming the first piece of our Twit-
ter clone.
LEARN TO BUILD WITH PHP
14HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
3.ย Forms
3.1ย How Forms Work In HTML
Forms are everywhere.
No, seriously. They are. When you leave a comment on MakeUseOf; when you buy something off Amazon and have
to write down your address and credit card numbers; when you compose and submit a Tweet, you are filling out a
form.
I know I sound like a broken record, but if you havenโ€™t read the MakeUseOf HTML5 guide, you should. You donโ€™t need
it for this chapter, but itโ€™ll show you some cool tricks you can do with forms in the latest version of the HTML markup
language.
3.2ย Creating Our First Form
Youโ€™ve probably seen Twitter before.
LEARN TO BUILD WITH PHP
15HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
The core of a Tweet is a multi-line text box, and a button that submits it to Twitterโ€™s servers. So, how do we create a
rudimentary version of that in HTML? Well, it looks something like this:
body
form action=โ€postForm.phpโ€ method=โ€postโ€
TextArea name=โ€microBlogโ€ id=โ€microBlogโ€ cols=โ€30โ€ rows=โ€œ10โ€
/br
/TextArea
input type=โ€submitโ€
/form
/body
So, letโ€™s break this down.
A form is enclosed within form tags. Form takes two arguments, with the first being a link to a PHP file which contains
the code that handles our form. The second is a method, and this refers to how you send data to the web server.
These can either be โ€˜postโ€™ or โ€˜getโ€™.
Inside, weโ€™ve got a TextArea element. Do you know what the difference between a TextArea and input element is?
Itโ€™s a really subtle difference. They do pretty much the same thing, although a TextArea element allows you to input
multiple lines of content, whereas an Input (when not used to submit a form) can only accept one line of content.
Since weโ€™re creating a clone of Twitter, weโ€™re going to use a TextArea element to capture the post. This element takes
a few arguments. The first two are โ€˜nameโ€™ and โ€˜idโ€™, which weโ€™ve given the value of โ€˜microBlogโ€™. The second two are
โ€˜colsโ€™ and โ€˜rowsโ€™, which we have given the values of โ€™30โ€™ and โ€™10โ€™ respectively. These can be adjusted, as you see fit.
Finally, we have an input element. This has a type of โ€˜submitโ€™, and is rendered in the browser as a button. Once
pressed, it will pass the contents to โ€˜postForm.phpโ€™.
We should have something which looks like this. Not the most pleasant thing in the world, but weโ€™ll worry about that
later.
3.3ย Handling This Input With PHP
In keeping with the gentle pace of this book, weโ€™re going to just look at how we can capture the input, and then print it
to the screen. Weโ€™ll look at persistence and storing it in the database later on.
So, remember that postForm.php file we mentioned earlier? Create that in the document root.
Now, add the following lines.
?php
$microBlog = $_POST[โ€˜microBlogโ€™];
echo $microBlog;
?
So, whatโ€™s that $_POST thing then?
Well, thatโ€™s what we call a super-global variable. That sounds complicated, but it isnโ€™t. In its simplest form, it means
LEARN TO BUILD WITH PHP
16HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
that whenever we need to reference a form input, we have to use that. At the end of $_POST, we write the ID of the
form input weโ€™re referencing. This has to be sandwiched between square braces and quote marks.
We assign the contents of the โ€˜microBlogโ€™ to a variable, and then echo it to the screen. Simple, really.
But does it work? Letโ€™s give it a try.
We navigate to our homepage and write something into the form. Then, we press โ€˜submitโ€™.
As you can see, our input is returned back to us. Hereโ€™s a question though. What happens if we close our browser tab
and reopen localhost/postForm.php?
Thereโ€™s nothing there. Niet. Nada.
Thatโ€™s because itโ€™s not stored anywhere, except in the short-term memory of our web browser. Once itโ€™s gone, itโ€™s
gone.
However, thereโ€™s an easy way to ensure that our data is retained forever. We have to put it into a database. Whilst at
first theyโ€™re not the most exciting subject ever, theyโ€™re pretty easy to get the hang of.
And in the next chapter, Iโ€™m going to show you how you can store your tweets in a database.
LEARN TO BUILD WITH PHP
17HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
4.ย Databases
I have a confession to make. I really like databases.
Ever since computers were invented, weโ€™ve needed to store content. Everything from the password you use to log into
Facebook, to the configuration of your computer, to your bank account, is stored in a database. Earlier versions of da-
tabases were fundamentally primitive and limited. Since then, they have evolved and advanced, improving the speed
and reliability of their functioning. This is largely a result of 50 or so years of development.
One way of storing data is with a relational database. This paradigm of storing data was introduced in the 80s and
relies upon a mesh of interconnected tables, with data organized in rows and columns.
There are a huge number of database management systems that use this paradigm (known as RDBMSโ€™), including
Oracle, MsSQL and MariaDB. But weโ€™re only going to look at one. MySQL.
MySQL is a modern database management system. The number of websites which depend on it is dizzyingly large. It
is the database behind WordPress and Facebook, and is based upon the reliable relational database paradigm.
Advantages of the MySQL database are too numerous to mention.
Firstly, itโ€™s free; both in cost and in terms of licensing. It can be found running on every platform, having been ported to
some of the most obscure operating systems in the world.
Moreover, itโ€™s a reasonably lightweight software package, and can run quite comfortably on most low-powered VPS
systems.
Itโ€™s also remarkably easy to get started with MySQL, and there is a huge wealth of information out there for people
who would like to get their feet wet with it, including some incredibly detailed and accurate user generated documenta-
tion.
In order to interact with MySQL, we need to use the SQL (Structured Query Language) programming language. This
allows us to perform complex queries against a database, whilst strongly resembling written English. As a result, it is
really easy for beginners to get started with.
But before we get to that, letโ€™s talk about MySQL datatypes.
LEARN TO BUILD WITH PHP
18HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
4.1ย MySQL Datatypes
MySQL requires that each column in a table be categorized with a specific datatype. For example, someoneโ€™s age
would be categorized as a number, whilst someoneโ€™s name would consist of a variable number of alphabetic charac-
ters.
We specify datatypes to ensure the consistency of the data stored in the table.
Whilst this sounds complicated, I assure you it isnโ€™t. What weโ€™re talking about is knowing the data that weโ€™re planning
to retain, and knowing how to classify it.
There are a huge number of datatypes in MySQL. Weโ€™re only going to talk about two, which are more than adequate
for the purposes of this book.
Varchar(x)
When youโ€™re inputting content that can contain a variance of numbers, special characters and letters, youโ€™re recom-
mended to use a varchar field. These can be of varying length. A field size with a maximum length of thirty characters
can be represented with varchar(30).
Integer
When storing numbers, we use an integer value. These can range from -2147483648 to 2147483647, although there
are more datatypes available if you need to represent larger numbers. In that case, refer to theย MySQL manual.
Other MySQL Datatypes
There are a huge number of datatypes available, which can be used to represent and retain all sorts of data. These
include large pieces of text, true or false values and binary files. If youโ€™re curious to learn more, have a look at the
MySQL documentation.
4.2ย Creating Our Database
Okay, now itโ€™s time to start working on a database for our Twitter clone.
Firstly, we need to connect to MySQL. If youโ€™re using Linux and youโ€™ve installed MySQL through your package man-
ager, you can connect through the terminal with the following command.
mysql -u root -p
Upon which, you will be prompted for your password.
Users of XAMPP and MAMP can use PHPMyAdmin, which comes bundled in and allows you to edit your database
with a nice web interface.
So, first we need to create the database for our website and create a table to hold our microblog posts.
Either through PHPMyAdmin or through the MySQL console, run the following lines.
CREATE DATABASE MicroBlog;
USE MicroBlog;
LEARN TO BUILD WITH PHP
19HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
CREATE TABLE MicroBlog (
id integer auto_increment,
post varchar(255),
primary key (id)
);
Unless you see an error message, your table has been created without a hitch.
So, a few things you might have noticed there. Firstly, weโ€™re ending each statement with a semi-colon, much like we
did when we were writing PHP.
Secondly, things are pretty self-explanatory, arenโ€™t they? SQL reads like written English, and itโ€™s pretty easy to under-
stand whatโ€™s going on.
That said, there are some things in the CREATE TABLE statement which you may be unfamiliar with. The first is
โ€˜auto_incrementโ€™. What does this do?
Well, ID is a field that uniquely identifies each post. When we created it, we gave it an attribute of โ€˜auto_incrementโ€™,
and whenever a new row is added to the database, that row is given a unique number. This number counts up by one,
for each row that is added.
Finally, what is โ€˜primary key (id)โ€™? Well, we want โ€˜idโ€™ to be completely unique. We also want ID to be a field which can
identify a row. Making โ€˜idโ€™ a primary key ensures that these conditions can be met.
4.3ย The Wrong Way To Query The Database
So, how do we insert a post into our database? Great question.
The traditional way of doing this in PHP looked a bit like this:
$conn = mysqli_connect($DBServer, $DBUser, $DBPass, $DBName);
You would create a connection to the server using the hostname, database credentials and database name, and as-
sign that to an object. In this instance, weโ€™ve called it $conn (for connection).
We then would define the database query we wish to make.
$query = mysqli_query($conn, โ€œINSERT INTO MicroBlog VALUES (โ€˜$postโ€™)โ€);
And then we would close the connection to the database.
LEARN TO BUILD WITH PHP
20HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
mysqli_close($conn);
So, what wrong with this? Well, it relies upon one key assumption; that any input passed to the database can be
trusted.
That isnโ€™t always the case. If youโ€™re not very careful, itโ€™s entirely possible to sneak in some arbitrary SQL code, which
can then result in data leakages or the defacement of the records stored within your database.
LinkedIn learned about this the hard way. A poorly sanitized input lead to the unintended (and unauthorized) release of
thousands of user records in a debacle that was referred to as LeakedIn. It was an incident that cost them dearly, both
with respect to the financial cost of making good, as well as the goodwill lost by losing millions of rows of personal
information.
So, how do we safely use a database with PHP?
4.4ย Meet MeekroDB
MeekroDBย is a library that makes it easy to interact with a database without being wide open to an external threat. It
has been designed from the ground up to beย impervious to SQL Injection attacks. Itโ€™s free for non-profit use, but if you
plan to use it in a commercial project, you need to pay for a license.
Download a copy of MeekroDB from the official website. Once youโ€™ve got it, unzip it and place it in your document root
directory.
Now, letโ€™s go back to your text editor. Open postForm.php and add the following lines.
require_once โ€˜meekrodb.2.2.class.phpโ€™;
DB::$user = โ€˜userโ€™;
DB::$password = โ€˜passwordโ€™;
DB::$dbName = โ€˜databaseโ€™;
Change โ€˜userโ€™, โ€˜passwordโ€™ and โ€˜databaseโ€™ with your actual database username, password and database name.
Now, itโ€™s time to insert your post into your database. Add the following lines of code.
DB::debugMode();
$microBlog = $_POST[โ€˜microBlogโ€™];
DB::insert(โ€˜MicroBlogโ€™, array(
โ€˜postโ€™ = $microBlog) );
So, letโ€™s break this down.
LEARN TO BUILD WITH PHP
21HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
DB::debugMode(); throws out error messages if we do something wrong. As a result, itโ€™s really quite handy to leave
this in our code, as it makes the process of development that bit easier.
DB::insert is called when we need to insert one or more items into the database. โ€˜MicroBlogโ€™ refers to the database
table, whilst โ€˜postโ€™ contains the message which youโ€™ve just posted to the website.
We can see if our posts have reached the database by opening up PHPMyAdmin and having a look.
If youโ€™re using MySQL on Linux, and youโ€™ve installed it from the package manager, you can open up MySQL from the
terminal and run the following commands.
Use MicroBlog;
Select * from MicroBlog;
Simple, right? Give that a go and next, weโ€™re going to look at displaying our posts on the homepage. I promise, itโ€™s not
too hard.
LEARN TO BUILD WITH PHP
22HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
5.ย Getting Content From The Database
Weโ€™ve introduced MeekroDB already. This is the database library that allows us to interact securely with a MySQL
database within the context of a PHP application.
If youโ€™ve completed the previous chapter, you should have some posts in the database. However, theyโ€™re just sitting in
a database not being used. What a pity! So, letโ€™s look at getting them into the browser.
We know that we can use SQL is the language used by MySQL in order to query the database. Whilst MeekroDB
allows you to insert content into your database without using SQL, you have to use some SQL in order to retrieve
records.
5.1ย Selecting And Presenting Results
One such statement is the โ€˜Select Statementโ€™. We have previously used this to see if our files had propagated to the
database. Weโ€™re going to use it again here.
Below the closing form tag, add ?php and ? and in-between write the following lines of code.
?php
require_once โ€˜meekrodb.2.2.class.phpโ€™;
DB::$user = โ€˜rootโ€™;
DB::$password = โ€˜rootโ€™;
DB::$dbName = โ€˜MicroBlogโ€™;
$results = DB::query(โ€œSELECT post FROM MicroBlogโ€);
foreach ($results as $row){
echo โ€œdiv class=โ€™microBlogโ€™โ€ . $row[โ€˜postโ€™] . โ€œ/divโ€;
}
?
Letโ€™s look at this a bit more closely. We know what the first five lines do. We previously used them as part of inserting
our posts into the database.
$results = DB::query(โ€œSELECT post FROM MicroBlogโ€);
This line selects all posts from the table โ€˜MicroBlogโ€™, and then copies them to a variable called $results.
And then it gets interesting. So, $results happens to consist of a number of items. This means that we can iterate over
them using something that is strongly reminiscent of those โ€˜forโ€™ loops that we previously looked at.
foreach ($results as $row){
echo โ€œdiv class=โ€™microBlogโ€™โ€ . $row[โ€˜postโ€™] . โ€œ/divโ€;
}
So, here weโ€™re going over each result, and mapping it to a variable. We then print it out in between some โ€˜divโ€™ tags.
These allow us to encapsulate each post, and apply stylings to each of them.
LEARN TO BUILD WITH PHP
23HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
It doesnโ€™t look like much now, does it? Letโ€™s change that.
5.2ย Styling
Create a new file called โ€˜style.cssโ€™ and add the following line of HTML code in-between the โ€˜Headโ€™ tags.
link rel=โ€stylesheetโ€ type=โ€text/cssโ€ href=โ€style.cssโ€
Now, itโ€™s time to make each post look a bit more distinctive and noticeable. In โ€˜style.cssโ€™, add the following lines.
body {
background-color: #99CCFF ;
}
form {
text-align: center;
margin-left: 300px;
margin-right: 300px;
}
.microBlog {
text-align: center;
margin-left: 300px;
margin-right: 300px;
margin-bottom: 10px;
border-style:solid;
border-width:5px;
}
I wonโ€™t insult your intelligence by explaining line-for-line what this does. You can probably work it out, just by reading it.
Weโ€™ve given each post a bit of padding, so that itโ€™s relatively centered in the screen. Weโ€™ve also given it a border, and
aligned the form in the center of the screen.
This produces something that looks a bit like this.
Cool, right?
Now, in our penultimate chapter, weโ€™re going to bring together everything weโ€™ve learned so far, and look at how we can
handle logins.
LEARN TO BUILD WITH PHP
24HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
6.ย Logins And Authentication
Letโ€™s imagine that we only want one person to be able to post updates on our website. Itโ€™s almost as if weโ€™re creating a
highly personal Twitter.
6.1ย The Users Table
First, letโ€™s create a table to handle our login information. This will have two fields. The first is for the username and the
second is for the password. This can be represented in SQL as follows:
CREATE TABLE Credentials (
username varchar(255),
password varchar(255),
PRIMARY KEY (username)
);
As before, run this against your database, either through the terminal or through PHPMyAdmin.
6.2ย PHP Sessions
Now, we need to handle logins and registrations. We do that with PHP sessions. The way these work is reasonably
simple. You have a number of variables that are present throughout a web application, and these can be in a state of
presence or otherwise, depending on whether a user is logged in or not.
LEARN TO BUILD WITH PHP
25HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
Before you can handle sessions, you have to first initialize the session. Add this line to the top of index.php.
?php session_start(); ?
This line has to appear in every file which accesses the session.
Now, we need to ensure that the post submission form is only visible to those who are logged in. Replace the form we
created earlier with the following lines of code.
?php if(isset($_SESSION[โ€˜loggedinโ€™])){
echo โ€˜form action=โ€postForm.phpโ€ method=โ€postโ€
TextArea name=โ€microBlogโ€ id=โ€microBlogโ€ cols=โ€30โ€ rows=โ€10โ€
/TextArea
/br
input type=โ€submitโ€
/formโ€™;
}
?
$_SESSION[โ€˜loggedinโ€™ ] is a session variable. When itโ€™s set, the user will be able to see the form used to create posts.
Letโ€™s add something else.
else {
echo โ€˜form action=โ€œlogin.phpโ€ method=โ€œpostโ€
Username: input type=โ€œtextโ€ name=โ€œusernameโ€ id=โ€usernameโ€ / /br
Password: input type=โ€œtextโ€ name=โ€œpasswordโ€ id=โ€passwordโ€ /
input type=โ€submitโ€
/formโ€™;
}
When you browse to localhost/index.php now, you will see that you can no longer post a status, and you are being
prompted to log in. It works!
But first, weโ€™re going to have to create an account to log in with. So, letโ€™s add the following lines to our index page.
if (isset($_SESSION[โ€˜loggedinโ€™])){
echo โ€˜a href=โ€logout.phpโ€Log Out/aโ€™;
} else {
echo โ€˜a href=โ€register.phpโ€Register/aโ€™;
}
If our user is logged in, they will be presented with an option to log out. Likewise, if our user isnโ€™t logged in, they will be
presented with an option to register.
Now, we need to create a register form. Create a new file called register.php and add the following.
?php session_start(); ?
!doctype html
html lang=โ€enโ€
head
meta charset=โ€UTF-8โ€
titleRegister/title
link rel=โ€stylesheetโ€ type=โ€text/cssโ€ href=โ€style.cssโ€
/head
body
h2Register/h2
form action=โ€œregisterForm.phpโ€ method=โ€œpostโ€
pUsername: input type=โ€œtextโ€ name=โ€œusernameโ€ id=โ€usernameโ€/p
pPassword: input type=โ€œtextโ€ name=โ€œpasswordโ€ id=โ€passwordโ€/p
input type=โ€submitโ€
/form
/body
LEARN TO BUILD WITH PHP
26HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
/html
While youโ€™re at it, add the following lines to style.css.
h2 { text-align: center; }
6.3ย Registering Users
Now, we need to add some logic for registering a user. Create a new file called registerForm.php and add the follow-
ing lines.
?php
require_once โ€˜meekrodb.2.2.class.phpโ€™;
DB::$user = โ€˜rootโ€™;
DB::$password = โ€˜rootโ€™;
DB::$dbName = โ€˜MicroBlogโ€™;
$username = $_POST[โ€˜usernameโ€™];
$password = $_POST[โ€˜passwordโ€™];
$hash = password_hash($password, PASSWORD_DEFAULT);
DB::insert(โ€˜Credentialsโ€™, array(
โ€˜usernameโ€™ = $username,
โ€˜passwordโ€™ = $hash
));
header(โ€˜Location: http://localhost:8888/index.phpโ€™);
?
A lot of this should be pretty familiar, but some stuff is new. Iโ€™ll explain that now.
Security is always at the forefront of the application developer. Itโ€™s always embarrassing when a major security breach
happens, resulting in a deluge of customer information being leaked. Trust me. Itโ€™s never pleasant.
And it doesnโ€™t help that people tend to recycle passwords. Yep, if your site gets hacked and someone gains access to
your usersโ€™ passwords, it may lead to your usersโ€™ accounts on other sites being compromised.
Hashing allows you to encrypt a password with a cryptographic algorithm, making it remarkably difficult to reverse it to
its original form. That task is accomplished with a single line of code in PHP.
$hash = password_hash($password, PASSWORD_DEFAULT);
However, the example I provided isnโ€™t enough. Passwords need to be salted. What is this, you ask? Well, itโ€™s another
line of defense, and makes it near-enough impossible for your userโ€™s passwords to be decrypted. However, this is a
little too complicated for a small guide. As a result, Iโ€™d encourage you to do some further reading on the topic. This
blog post gives a pretty solid guide to salting passwords with PHP [http://www.sitepoint.com/hashing-passwords-php-
5-5-password-hashing-api/].
Finally, we have this curious line.
header(โ€˜Location: http://localhost:8888/index.phpโ€™);
This does one task, which is to redirect the browser to the home page. Simple, really.
6.4ย Logging In
Create a file called โ€˜login.phpโ€™ and add the following lines.
?php
session_start();
ob_start();
require_once โ€˜meekrodb.2.2.class.phpโ€™;
DB::$user = โ€˜rootโ€™;
DB::$password = โ€˜rootโ€™;
DB::$dbName = โ€˜MicroBlogโ€™;
LEARN TO BUILD WITH PHP
27HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
$username = $_POST[โ€˜usernameโ€™];
$password = $_POST[โ€˜passwordโ€™];
$result = DB::queryFirstRow(โ€œSELECT * FROM Credentials where username = %sโ€,
$username);
$hash = $result[โ€˜passwordโ€™];
if (password_verify($password, $hash)) {
$_SESSION[โ€˜loggedinโ€™] = 1;
header(โ€˜Location: http://localhost:8888/โ€™);
} else {
echo โ€œLogin failedโ€;
}
?
Like before, thereโ€™s nothing wildly new here. Weโ€™ve introduced DB::queryFirstRow. However, this is pretty transparent
with what it does, and retrieves the first row from the database. This is slightly quicker than DB::query, and produces
an object which we donโ€™t have to iterate over.
Another concept which has been introduced is the password_verify() function. This allows us to compare an unhashed
and hashed password, and to see if it is a match. If it is, we then set $_SESSION[โ€˜loggedinโ€™] to a value (in this case,
one) and then redirect to the homepage, where we are then able to log out and to post new tweets.
Now, test it out by seeing if you can log in and create a new post!
6.5ย Logging Out
Logging out is easy. Create a new file with a name of โ€˜logout.phpโ€™. Inside, add the following lines.
?php
session_start();
session_destroy();
header(โ€˜Location: http://localhost:8888/โ€™);
?
The session which previously contained the activated โ€˜loggedinโ€™ variable has now been destroyed, effectively logging
us out. Once destroyed, the user is then redirected to the homepage.
LEARN TO BUILD WITH PHP
28HTTP://MAKEUSEOF.COM
MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share:
7.ย Conclusion And Further Reading
I hope you enjoyed this short introduction to the PHP programming language.
I know it was a whistle-stop tour. I know it was brief. I know it was hurried. Despite this, I hope I communicated all my
points clearly. If you are dissatisfied, or have further questions, please contact me. My email address is me@mat-
thewhughes.co.uk, and I can also be reached on Twitter. My username isย @matthewhughesย and I am always happy to
respond to reader feedback.
Before we wrap things up, I want to address a couple more things.
Firstly, the PHP programming language is an awesome, powerful tool. If you are eager to do some further reading,
please check outย PHP The Right Wayย andย Programming PHPย by Oโ€™Reilly. Both are amazing resources, and are highly
recommended.
My colleagues at MakeUseOf have also previously recommended someย free resources to learn PHP.
Finally, the source code to this project is available on my personal Github. You can find theย repository here. If youโ€™re
unsure of what Git is, check out this article aboutย Git version control. If you donโ€™t know how to use Github, check
outย Git Real by CodeSchool. It will bring you up to speed pretty quickly, and itโ€™s free.
Thank you for your time.
Matthew Hughes
Guide Published: March 2014
Did you like this PDF Guide? Then why not visit MakeUseOf.com for daily posts on
cool websites, free software and internet tips?
If you want more great guides like this, why not subscribe to MakeUseOf and receive
instant access to 50+ PDF Guides like this one covering wide range of topics. More-
over, you will be able to download free Cheat Sheets, Free Giveaways and other cool
things.
Home: 				http://www.makeuseof.com
MakeUseOf Answers:		 http://www.makeuseof.com/answers
PDF Guides: 			 http://www.makeuseof.com/pages/
Tech Deals: 				http://www.makeuseof.com/pages/hot-tech-deals
Follow MakeUseOf:
RSS Feed:				http://feedproxy.google.com/Makeuseof
Newsletter:				http://www.makeuseof.com/subscribe/
Facebook:				http://www.facebook.com/makeuseof
Twitter:				http://www.twitter.com/Makeuseof
Think youโ€™ve got what it takes to write a manual for MakeUseOf.com? Weโ€™re always willing
to hear a pitch! Send your ideas to justinpot@makeuseof.com.

More Related Content

PDF
PHP Doesn't Suck
PDF
Brochure Open Foam En
PDF
lecture2-PerlProgramming
PPT
Openmeetings
ย 
PPT
UOP Week 1 PPT
PDF
Eudays2011 conference lystofparticipant
PPS
The V formation
PPTX
Women
PHP Doesn't Suck
Brochure Open Foam En
lecture2-PerlProgramming
Openmeetings
ย 
UOP Week 1 PPT
Eudays2011 conference lystofparticipant
The V formation
Women

Viewers also liked (8)

PPTX
Jack downey
PPTX
Presentation1
PDF
Securing optimizing linux. the hacking solution
PPT
Android application development
PPTX
Lindberghbaby
PPTX
History
PPTX
History
PPTX
Ir to go jack
Jack downey
Presentation1
Securing optimizing linux. the hacking solution
Android application development
Lindberghbaby
History
History
Ir to go jack
Ad

Similar to Learn to build with php (20)

DOCX
PHP Training In Chandigar1.docx
PPTX
Why do businesses choose PHP as their development language?
PDF
PHP Web Development.pdf
PDF
Php vs asp.net
PPTX
Php myths
PPTX
Php vs asp.net most valuable differences to learn and select the best one f...
PDF
Php tutorial
ย 
PPT
PHP: Hypertext Preprocessor Introduction
PPTX
PHP programmimg
PPTX
Php vs Python: The Comparison You Should Know
PPTX
PHP Vs ASP.NET : How to Choose the Right One?
PPTX
Word press
PDF
Php tutorial
PDF
Php tutorial
PDF
Php tutorial
PDF
PHP vs ASP.NET
PDF
Top 100 PHP Questions and Answers
PPTX
unitI-Introduction to php.pptx
PPTX
Php hypertext Preprocessor
PDF
Manual oficial de php5
PHP Training In Chandigar1.docx
Why do businesses choose PHP as their development language?
PHP Web Development.pdf
Php vs asp.net
Php myths
Php vs asp.net most valuable differences to learn and select the best one f...
Php tutorial
ย 
PHP: Hypertext Preprocessor Introduction
PHP programmimg
Php vs Python: The Comparison You Should Know
PHP Vs ASP.NET : How to Choose the Right One?
Word press
Php tutorial
Php tutorial
Php tutorial
PHP vs ASP.NET
Top 100 PHP Questions and Answers
unitI-Introduction to php.pptx
Php hypertext Preprocessor
Manual oficial de php5
Ad

Recently uploaded (20)

PPTX
Funds Management Learning Material for Beg
PDF
RPKI Status Update, presented by Makito Lay at IDNOG 10
ย 
PDF
๐Ÿ’ฐ ๐”๐Š๐“๐ˆ ๐Š๐„๐Œ๐„๐๐€๐๐†๐€๐ ๐Š๐ˆ๐๐„๐‘๐Ÿ’๐ƒ ๐‡๐€๐‘๐ˆ ๐ˆ๐๐ˆ ๐Ÿ๐ŸŽ๐Ÿ๐Ÿ“ ๐Ÿ’ฐ
ย 
PDF
Slides PDF The World Game (s) Eco Economic Epochs.pdf
PPTX
E -tech empowerment technologies PowerPoint
PPTX
Slides PPTX World Game (s) Eco Economic Epochs.pptx
PDF
Introduction to the IoT system, how the IoT system works
ย 
PPTX
introduction about ICD -10 & ICD-11 ppt.pptx
PPTX
Digital Literacy And Online Safety on internet
PPTX
Power Point - Lesson 3_2.pptx grad school presentation
ย 
PPTX
Module 1 - Cyber Law and Ethics 101.pptx
PPT
tcp ip networks nd ip layering assotred slides
PPTX
artificial intelligence overview of it and more
PPTX
Job_Card_System_Styled_lorem_ipsum_.pptx
PPTX
INTERNET------BASICS-------UPDATED PPT PRESENTATION
PDF
The Internet -By the Numbers, Sri Lanka Edition
ย 
PPT
Design_with_Watersergyerge45hrbgre4top (1).ppt
PPTX
Internet___Basics___Styled_ presentation
PDF
Vigrab.top โ€“ Online Tool for Downloading and Converting Social Media Videos a...
PDF
Paper PDF World Game (s) Great Redesign.pdf
Funds Management Learning Material for Beg
RPKI Status Update, presented by Makito Lay at IDNOG 10
ย 
๐Ÿ’ฐ ๐”๐Š๐“๐ˆ ๐Š๐„๐Œ๐„๐๐€๐๐†๐€๐ ๐Š๐ˆ๐๐„๐‘๐Ÿ’๐ƒ ๐‡๐€๐‘๐ˆ ๐ˆ๐๐ˆ ๐Ÿ๐ŸŽ๐Ÿ๐Ÿ“ ๐Ÿ’ฐ
ย 
Slides PDF The World Game (s) Eco Economic Epochs.pdf
E -tech empowerment technologies PowerPoint
Slides PPTX World Game (s) Eco Economic Epochs.pptx
Introduction to the IoT system, how the IoT system works
ย 
introduction about ICD -10 & ICD-11 ppt.pptx
Digital Literacy And Online Safety on internet
Power Point - Lesson 3_2.pptx grad school presentation
ย 
Module 1 - Cyber Law and Ethics 101.pptx
tcp ip networks nd ip layering assotred slides
artificial intelligence overview of it and more
Job_Card_System_Styled_lorem_ipsum_.pptx
INTERNET------BASICS-------UPDATED PPT PRESENTATION
The Internet -By the Numbers, Sri Lanka Edition
ย 
Design_with_Watersergyerge45hrbgre4top (1).ppt
Internet___Basics___Styled_ presentation
Vigrab.top โ€“ Online Tool for Downloading and Converting Social Media Videos a...
Paper PDF World Game (s) Great Redesign.pdf

Learn to build with php

  • 2. This manual is the intellectual property of MakeUseOf. It must only be published in its original form. Using parts or republishing altered parts of this guide is prohibited without permission from MakeUseOf.com Think youโ€™ve got what it takes to write a manual for MakeUseOf.com? Weโ€™re always willing to hear a pitch! Send your ideas to justinpot@makeuseof.com. share: by Matthew Hughes http://www.matthewhughes.co.uk/ Published March 2014
  • 3. LEARN TO BUILD WITH PHP 3HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: Table Of Contents 1.ย Introduction 5 1.1ย The History Of PHP 6 1.2ย What Are We Going To Cover? 6 1.3ย All About LAMP 6 1.4ย Setting Up Your Development Environment 7 Windows 7 Linux 7 OS X 8 Android 8 1.5ย Choosing The Right Text Editor 8 1.6ย Prerequisites 9 2.ย Hello World! 10 2.1ย Does PHP Have To Be Surrounded By HTML? 11 2.3ย Basic Language Concepts 11 Variables 11 If Statements 11 While Statements 12 For Loops 12 Functions 12 2.4ย Moving On 13 3.ย Forms 14 3.1ย How Forms Work In HTML 14 3.2ย Creating Our First Form 14 3.3ย Handling This Input With PHP 15 4.ย Databases 17 4.1ย MySQL Datatypes 18 Varchar(x) 18 Integer 18 Other MySQL Datatypes 18 4.2ย Creating Our Database 18 4.3ย The Wrong Way To Query The Database 19
  • 4. LEARN TO BUILD WITH PHP 4HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: 4.4ย Meet MeekroDB 20 5.ย Getting Content From The Database 22 5.1ย Selecting And Presenting Results 22 5.2ย Styling 23 6.ย Logins And Authentication 24 6.1ย The Users Table 24 6.2ย PHP Sessions 24 6.3ย Registering Users 26 6.4ย Logging In 26 6.5ย Logging Out 27 7.ย Conclusion And Further Reading 28
  • 5. LEARN TO BUILD WITH PHP 5HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: 1.ย Introduction What was your favorite subject at school? If youโ€™re anything like me, I bet you loved the arts. The humanities. You know, the subjects derided by some as being vacuous and nebulous in nature, but regardless you loved studying them because youย loved being creative. I bet you never thought of your IT classes in the same way you thought of English Language or art; as a purely cre- ative endeavor. Thatโ€™s a pity. Learning to program is a bit like doing a creative language class. You have an idea, and you can execute that however you like. Itโ€™s pure creativity, but instead of baring your soul on paper, you are commanding a computer to do your bidding. If you can dream it, and if you can describe it in a way your computer understands, then you can make it. The way we talk to computers is through abstractions called programming languages. There are a whole bunch of these out there, each with their own advantages, disadvantages and truly bizarre idiosyncrasies. Theyโ€™re imperfect by nature, but people use them to create incredible and wonderful things. One of these languages is called PHP. You may have heard of it before. This is the language that Facebook, WordPress and Wikipedia use to serve billions of requests, daily. It is the de-facto language used for teaching people to program for the web. Itโ€™s beautifully simple, but brilliantly powerful. And in this guide, Iโ€™m going to teach you how you can use it to build your own websites. Do you have a killer startup idea you donโ€™t quite know how to execute? Do you want to learn the language used to extend WordPress? Are you just curious about web programming? Do you just want to learn the skills needed to stay relevant in the modern, tech-oriented knowledge economy? Whatever your motivation, this book aims to teach you the basics of the PHP programming language. But first, letโ€™s have a bit of a history lesson.
  • 6. LEARN TO BUILD WITH PHP 6HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: 1.1ย The History Of PHP In the infancy of the Internet, things were a bitโ€ฆ Well? Flat. Sites werenโ€™t particularly interactive, and those who visited these sites were faced with a relatively one-directional experience. Adding even the simplest aspects of user engagement was incredibly difficult, left in the domain of the computer scientists and the expert programmers. And then Rasmus Lerdorf came around. This Canadian-Greenlandic coder created the PHP programming language, which allowed people to easily add the simplest facets of interaction to their web pages. It was new, it was brave, and it took off almost immediately. Rasmus Lerdorf couldnโ€™t have predicted the impact his idea would have upon the world. A community began to form, with programmers and companies willingly providing time and money to fuel the develop- ment of the language. Slowly but surely, PHP began posing a serious challenge to Sun (now Oracle) and Microsoft, who were hoping to gain traction in the web-development market with their Java and ASP platforms. The rise of the PHP programming language could only be described as startlingly rapid. That was 20 years ago. An age, in the computer world. Since then, the PHP programming language has become the preferred way for millions of programmers, who use PHP in their jobs, to get involved in open source and to bring their ideas to life. Itโ€™s a staple of the digital world. You can become one of those millions. This book will show you how. 1.2ย What Are We Going To Cover? This is a pretty short book, but weโ€™re going to cover a lot. In just a few pages, weโ€™re going to create a simple clone of Twitter. Whilst itโ€™s not going to have the same feature-set and polish of the popular micro-blogging site, but we will be able to post 140 character messages with an account we will log into. 1.3ย All About LAMP By now, we should know that PHP is an incredible language for creating interactive web pages. But we havenโ€™t talked about how we turn that code into a real-life product. So, letโ€™s do that. For the most part, PHP code runs within a web server. A web server is responsible for sending web pages to anyone who navigates to a specific domain name or IP address. The most common choice of web server is the ludicrously popular Apache web server. This open source, cross-plat- form software project powers the majority of the Internet, with 45% of all websites serving pages from the Apache web server. However, itโ€™s helpful to note that there are other web servers available, including LightTTPD and Microsoftโ€™s IIS. This forms the second letter in the LAMP acronym, which stands for Linux, Apache, Mysql and PHP. We know what PHP is. I just explained to you what Apache is. You might have heard of Linux at some point. But what is the โ€˜Mโ€™ in Lamp? MySQL. Letโ€™s talk about MySQL. Iโ€™d put money on your website having to store information that your web application has gath- ered. Whatโ€™s more, I bet youโ€™d want to store that information somewhere that is structured, safe and organized. Yep, youโ€™re going to have to use a database, and for most purposes MySQL is a pretty solid choice. Weโ€™re going to talk about this later on. Finally, letโ€™s briefly touch on Linux. Most PHP websites are served from systems running the popular, open-source Linux operating system. However, you donโ€™t have to use Linux as your development environment if you donโ€™t want to. Everything in this book can be used on OS X, Windows and Android An operating system, Apache, MySQL and an installation of the PHP programming language are the four constituent parts of the most common PHP configurations. But how do we get our hands on them?
  • 7. LEARN TO BUILD WITH PHP 7HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: 1.4ย Setting Up Your Development Environment Unlike some programming languages, setting up a PHP development environment is easy. Indeed, there are a num- ber of packages which do all the hard-work for you, and save you the hassle of installing each component (PHP, MySQL and Apache) individually. Windows The easiest way to set up a PHP development environment in Windows is with XAMPP by Apache Friends. This pack- age includes MySQL, a copy of the PHP programming language and the Apache web server, as well as an administra- tive control panel, and plugins for SSL (the protocol used to encrypt traffic on a network) as well as sending Email. XAMPPย is free, and can be found on the Apache friends site. Itโ€™s important to stress that there are two versions of XAMPP available. One has a version number of 1.8.2 and runs a slightly older version of the PHP programming lan- guage, and the other has a version number of 1.8.3 and runs a current version of PHP. Whilst I would strongly recom- mend that you download the latest version, the contents of this guidebook should work with both. Linux Linux is a bit tricky. There are a number of operating systems that exist under the โ€˜Linuxโ€™ umbrella, although they each handle the installation of software packages in different ways. If youโ€™re using Ubuntu and any distribution which uses the Ubuntu repositories, you can run: sudo apt-get install lamp-server^ This will install a LAMP server, with all the components required for following this article. This process is explained in greater depth in this article, where I show youย how to install a LAMP serverย as part of installing the WordPress blog- ging platform. These instructions will not work on distributions that use YUM or RPM for their package management, with the instruc- tions for setting up a LAMP server differing significantly. I would recommend you to have a look at the documentation that came with your operating system. However, there is another option. Remember XAMPP? Well, it just so happens that it comes with support for Linux, and can be downloadedย here. However, where possible, I would strongly recommend that you install your LAMP server through your package manager.
  • 8. LEARN TO BUILD WITH PHP 8HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: There are a few reasons for this. Firstly, it would be slightly better integrated with your operating system and can be easily updated. Furthermore, installing PHP via the command line is good practice should you everย deploy your ap- plication to a VPS server. OS X I use OS X as my main development platform. I like the flexibility it provides me, and setting up a PHP development environment in OS X is insanely easy. Iโ€™m quite partial toย MAMP. This comes in two products, with one being free and the other costing $59 USD (or โ‚ฌ39). However, the free version is more than adequate for the purposes of this guide book. Getting MAMP is a matter of grabbing a ZIP file from the website, double-clicking a pkg file and pressing โ€˜continueโ€™ as often as necessary. As before, itโ€™s entirely possible for you to create a PHP development environment using XAMPP, which is also ported to OS X. Itโ€™s entirely up to you. Android Android? I mean, Android is great for sending tweets and killing time on Angry Birds. But software development? Nah. right? Wrong. If youโ€™ve bought an Android cell phone in the past year or so, odds are quite good that itโ€™s running a CPU thatโ€™s just as powerful as any VPS youโ€™ll get for under $10. And that means that itโ€™s good enough to run PHP, Apache and MySQL. There are a lot of Android LAMP servers on the market, but I really like Palapa Server. It runs nicely on an aging Nexus 7 tablet, and Iโ€™ve even managed to shoehorn Android onto it without any real difficulties. Itโ€™s not the ideal devel- opment environment, but itโ€™s possible. 1.5ย Choosing The Right Text Editor Youโ€™re probably familiar with what word processors are. Odds are good that youโ€™ve used Microsoft Word, Open Office or Google Docs to write letters, school assignments or business documents. But you might not know that itโ€™s not possible to use a regular word processor to develop software and websites. Why is that? Mainly because when you write a document, you leave all sorts of extraneous markup and formatting in the
  • 9. LEARN TO BUILD WITH PHP 9HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: file. The end product isnโ€™t just the words you write, but also the alignment of each word and its styling. As a result, when writing code, we use text editors. What are they? Simply put, these allow you to write files which are saved in purest plaintext. No formatting. Just characters. When writing code, I tend to use Sublime Text 2. It comes with an indefinite free trial (although, it does occasionally nag you to upgrade), and heaps of features, which makes writing software with it a joy. In particular, it comes built in with syntax highlighting for PHP, Javascript and HTML, which makes it really easy to read the code you produce. You can download Sublime Text 2 here, and it is available for Linux, Windows and OS X. If youโ€™re not convinced, you can read more aboutย Sublime Text 2. If youโ€™re on Android, youโ€™ll find that your choices are quite limited. Iโ€™m fond on VimTouch, which is available for free on the Google Play store. Vim has a pretty steep learning curve, but itโ€™s well worth a try. Read more about why itโ€™sย worth giving Vim text editor a chance. 1.6ย Prerequisites Weโ€™re going to jump straight in to learning PHP. Whilst I plan to gently introduce you to this amazing programming language, there are some things Iโ€™m expecting you to understand beforehand. Specifically, Iโ€™m going to expect that you understand how a website is structured with HTML. If you donโ€™t know your p tags from your span tags, thatโ€™s not a problem. MakeUseOf has aย XHTML bookย which will bring you up to speed. Read through that and once youโ€™re feeling confident, read on. Feeling adventurous? Why not learn about the latest version of HTML with ourย HTML5 e-book? Whilst itโ€™s not essen- tial, it might help you later on.
  • 10. LEARN TO BUILD WITH PHP 10HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: 2.ย Hello World! Time for a whistle-stop tour of PHP. And where better to start than the traditional โ€˜Hello World!โ€™ program. But first, weโ€™re going to need to know where to store our PHP files. We store them in a place called the โ€˜Document Rootโ€™, which sounds complicated, but it really isnโ€™t. All that means is whatever is stored in this folder will be available to anyone who visits the computerโ€™s IP address with their web browser. The location of your document root varies on how your PHP environment is set up. If you are using MAMP on OS X, you can find it in /Applications/MAMP/htdocs. If youโ€™ve installed your LAMP server on Linux using your distribu- tionโ€™s package manager, your Document Root directory will most likely be /var/www. On XAMPP, your root directory is located in C:/xampp/htdocs/. Once youโ€™ve navigated to the Document Root folder, create a file called โ€˜index.phpโ€™ and add the following lines. !doctype html html lang=โ€enโ€ head meta charset=โ€UTF-8โ€ titleMicroblogging Site/title /head body /body /html Nothingโ€™s going on here, but we do have the skeleton of a web page. This homepage will be found at โ€˜localhostโ€™. Sometimes itโ€™s followed with a port number, which usually is โ€™80โ€™, โ€˜8888โ€™ or โ€˜8080โ€™. Although, depending on the PHP development package you use, can vary. If youโ€™re unsure, refer to the documentation. Now, letโ€™s write our first lines of PHP! In between body and /body, write ?php echo(โ€œHello World!โ€); ? So, letโ€™s break this down. All PHP code has to be between a โ€˜?phpโ€™ and โ€˜?โ€™. If it isnโ€™t then the web server will not execute it. Then, we have โ€˜echoโ€™. As Iโ€™m sure youโ€™ve guessed, this function prints content to the browser. Finally, we have the content we want to print out. This is surrounded in parentheses and speech marks. Itโ€™s worth noting that parentheses are (for the most part) optional, when it comes to calling a function. As we have finished the โ€˜echoโ€™ statement, we finish it with a semicolon. If this is missing, your code will not work.
  • 11. LEARN TO BUILD WITH PHP 11HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: If it works, you should see โ€˜Hello Worldโ€™ in your browser. 2.1ย Does PHP Have To Be Surrounded By HTML? No. If weโ€™re performing an action that should be displayed immediately within the web browser, we can have it nested within the HTML document. This is called inline PHP, and thatโ€™s what we used to print โ€˜Hello Worldโ€™ to the screen. However, for anything more complex, we should always aim to put it in its own PHP document. As with the previous example, the file should end with a โ€˜.phpโ€™ extension and all code should start and end with โ€˜?phpโ€™ and โ€˜?โ€™. 2.3ย Basic Language Concepts Before we go on, letโ€™s look at some language concepts in PHP. Whilst this isnโ€™t an exhaustive list, it does include the essentials required to be productive as a PHP programmer. Once weโ€™ve gone through these, weโ€™re going to look at using some of these concepts within the context of forms. Variables Variables are a concept found in virtually all programming languages. They are used to store a value, which can be retrieved, used and changed later on. You might be familiar with a language that requires you to specify the value of a variable. These include C#, C, C++ and Java, and usually look a bit like this. int x = 10; You also might be familiar with Javascript, where variables are declared with the โ€˜varโ€™ keyword. var x = 10; In PHP, however, variables are declared with a dollar symbol. $x = 10; PHP variables cannot start with a number or a special character other than an underscore. Furthermore, they cannot be called โ€˜thisโ€™, as this is a reserved keyword. If Statements If statements are useful. They allow you to execute code contingent upon a specific condition being met. Consider the following code. $x = 5; if ($x == 4) { echo(โ€œHello Worldโ€); } elseif ($x == 3) { echo(โ€œHello Daveโ€); } else { echo(โ€œHello Brianโ€); }
  • 12. LEARN TO BUILD WITH PHP 12HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: So, the first condition being examined is if $x equals four (note the double equals symbols). Since it isnโ€™t, the PHP interpreter will look at the next conditional statement, which is if $x equals 3. If it doesnโ€™t, it will move on to the final statement, which will echo out โ€˜Hello Brianโ€™ if none of the conditions have been met. You can check if a variable is empty (also known as โ€˜nullโ€™, or a โ€˜null valueโ€™) by preceding it with a ! in the โ€˜ifโ€™ statement. For example: if (!$x){ echo(โ€œx is emptyโ€); } While Statements While statements execute code repeatedly whilst a condition is being met. Consider the following code. $x = 10; while ($x 1) { echo($x); $x = $x - 1; } This code looks at the value of $x, and if it is greater than one, it will echo the value of $x and then remove one from it. It will do this, until the condition of โ€˜$x 1โ€™ is no longer met. That is to say, that it equals 1 or less. For Loops For loops are, as a concept in programming, often quite intimidating to beginners. They shouldnโ€™t be, though. Whilst theyโ€™re ostensibly quite complex, theyโ€™re really easy to understand when broken down. Letโ€™s write a simple for loop that counts from one to ten. for($i = 0; $i 10; $i++){ echo($i); } Whatโ€™s happening here? Well, first we create a variable with a value of 0 ($i = 0;). We then set the condition of โ€˜if $i is less than 10, carry onโ€™ ($i 10). We then add one to I ($i++) and execute the contents of the curly braces, looping back on the original code. Functions Functions are a useful tool when it comes to programming. They allow you to write code that is more consistent, and spend less time writing the same things over and over again by compartmentalizing code into a single snippet that can be called when required. Theyโ€™re also really simple to create. This is how we make a function that echoes out โ€˜Hello Worldโ€™ when called. This function will be called โ€˜sayHello()โ€™. function sayHello(){ echo(โ€œHello Worldโ€); } You can also pass functions values. These are known as parameters, and are put within the two parentheses in the first line of the declaration. For example: function sayHello($hello){ echo($hello); } And can be called as follows: sayHello(โ€œHello Worldโ€);
  • 13. LEARN TO BUILD WITH PHP 13HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: Finally, we can get functions to return values. function returnHello(){ return โ€œHello Worldโ€; } And can be used as follows. x = returnHello(); echo(returnHello()); 2.4ย Moving On Weโ€™ve learned the basics of flow control in the PHP language, as well as how we can use variables and functions to store values and snippets of code for future use. In the next chapter, we will expand upon our understanding of the PHP programming language by looking at how we can capture data with forms, thus forming the first piece of our Twit- ter clone.
  • 14. LEARN TO BUILD WITH PHP 14HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: 3.ย Forms 3.1ย How Forms Work In HTML Forms are everywhere. No, seriously. They are. When you leave a comment on MakeUseOf; when you buy something off Amazon and have to write down your address and credit card numbers; when you compose and submit a Tweet, you are filling out a form. I know I sound like a broken record, but if you havenโ€™t read the MakeUseOf HTML5 guide, you should. You donโ€™t need it for this chapter, but itโ€™ll show you some cool tricks you can do with forms in the latest version of the HTML markup language. 3.2ย Creating Our First Form Youโ€™ve probably seen Twitter before.
  • 15. LEARN TO BUILD WITH PHP 15HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: The core of a Tweet is a multi-line text box, and a button that submits it to Twitterโ€™s servers. So, how do we create a rudimentary version of that in HTML? Well, it looks something like this: body form action=โ€postForm.phpโ€ method=โ€postโ€ TextArea name=โ€microBlogโ€ id=โ€microBlogโ€ cols=โ€30โ€ rows=โ€œ10โ€ /br /TextArea input type=โ€submitโ€ /form /body So, letโ€™s break this down. A form is enclosed within form tags. Form takes two arguments, with the first being a link to a PHP file which contains the code that handles our form. The second is a method, and this refers to how you send data to the web server. These can either be โ€˜postโ€™ or โ€˜getโ€™. Inside, weโ€™ve got a TextArea element. Do you know what the difference between a TextArea and input element is? Itโ€™s a really subtle difference. They do pretty much the same thing, although a TextArea element allows you to input multiple lines of content, whereas an Input (when not used to submit a form) can only accept one line of content. Since weโ€™re creating a clone of Twitter, weโ€™re going to use a TextArea element to capture the post. This element takes a few arguments. The first two are โ€˜nameโ€™ and โ€˜idโ€™, which weโ€™ve given the value of โ€˜microBlogโ€™. The second two are โ€˜colsโ€™ and โ€˜rowsโ€™, which we have given the values of โ€™30โ€™ and โ€™10โ€™ respectively. These can be adjusted, as you see fit. Finally, we have an input element. This has a type of โ€˜submitโ€™, and is rendered in the browser as a button. Once pressed, it will pass the contents to โ€˜postForm.phpโ€™. We should have something which looks like this. Not the most pleasant thing in the world, but weโ€™ll worry about that later. 3.3ย Handling This Input With PHP In keeping with the gentle pace of this book, weโ€™re going to just look at how we can capture the input, and then print it to the screen. Weโ€™ll look at persistence and storing it in the database later on. So, remember that postForm.php file we mentioned earlier? Create that in the document root. Now, add the following lines. ?php $microBlog = $_POST[โ€˜microBlogโ€™]; echo $microBlog; ? So, whatโ€™s that $_POST thing then? Well, thatโ€™s what we call a super-global variable. That sounds complicated, but it isnโ€™t. In its simplest form, it means
  • 16. LEARN TO BUILD WITH PHP 16HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: that whenever we need to reference a form input, we have to use that. At the end of $_POST, we write the ID of the form input weโ€™re referencing. This has to be sandwiched between square braces and quote marks. We assign the contents of the โ€˜microBlogโ€™ to a variable, and then echo it to the screen. Simple, really. But does it work? Letโ€™s give it a try. We navigate to our homepage and write something into the form. Then, we press โ€˜submitโ€™. As you can see, our input is returned back to us. Hereโ€™s a question though. What happens if we close our browser tab and reopen localhost/postForm.php? Thereโ€™s nothing there. Niet. Nada. Thatโ€™s because itโ€™s not stored anywhere, except in the short-term memory of our web browser. Once itโ€™s gone, itโ€™s gone. However, thereโ€™s an easy way to ensure that our data is retained forever. We have to put it into a database. Whilst at first theyโ€™re not the most exciting subject ever, theyโ€™re pretty easy to get the hang of. And in the next chapter, Iโ€™m going to show you how you can store your tweets in a database.
  • 17. LEARN TO BUILD WITH PHP 17HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: 4.ย Databases I have a confession to make. I really like databases. Ever since computers were invented, weโ€™ve needed to store content. Everything from the password you use to log into Facebook, to the configuration of your computer, to your bank account, is stored in a database. Earlier versions of da- tabases were fundamentally primitive and limited. Since then, they have evolved and advanced, improving the speed and reliability of their functioning. This is largely a result of 50 or so years of development. One way of storing data is with a relational database. This paradigm of storing data was introduced in the 80s and relies upon a mesh of interconnected tables, with data organized in rows and columns. There are a huge number of database management systems that use this paradigm (known as RDBMSโ€™), including Oracle, MsSQL and MariaDB. But weโ€™re only going to look at one. MySQL. MySQL is a modern database management system. The number of websites which depend on it is dizzyingly large. It is the database behind WordPress and Facebook, and is based upon the reliable relational database paradigm. Advantages of the MySQL database are too numerous to mention. Firstly, itโ€™s free; both in cost and in terms of licensing. It can be found running on every platform, having been ported to some of the most obscure operating systems in the world. Moreover, itโ€™s a reasonably lightweight software package, and can run quite comfortably on most low-powered VPS systems. Itโ€™s also remarkably easy to get started with MySQL, and there is a huge wealth of information out there for people who would like to get their feet wet with it, including some incredibly detailed and accurate user generated documenta- tion. In order to interact with MySQL, we need to use the SQL (Structured Query Language) programming language. This allows us to perform complex queries against a database, whilst strongly resembling written English. As a result, it is really easy for beginners to get started with. But before we get to that, letโ€™s talk about MySQL datatypes.
  • 18. LEARN TO BUILD WITH PHP 18HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: 4.1ย MySQL Datatypes MySQL requires that each column in a table be categorized with a specific datatype. For example, someoneโ€™s age would be categorized as a number, whilst someoneโ€™s name would consist of a variable number of alphabetic charac- ters. We specify datatypes to ensure the consistency of the data stored in the table. Whilst this sounds complicated, I assure you it isnโ€™t. What weโ€™re talking about is knowing the data that weโ€™re planning to retain, and knowing how to classify it. There are a huge number of datatypes in MySQL. Weโ€™re only going to talk about two, which are more than adequate for the purposes of this book. Varchar(x) When youโ€™re inputting content that can contain a variance of numbers, special characters and letters, youโ€™re recom- mended to use a varchar field. These can be of varying length. A field size with a maximum length of thirty characters can be represented with varchar(30). Integer When storing numbers, we use an integer value. These can range from -2147483648 to 2147483647, although there are more datatypes available if you need to represent larger numbers. In that case, refer to theย MySQL manual. Other MySQL Datatypes There are a huge number of datatypes available, which can be used to represent and retain all sorts of data. These include large pieces of text, true or false values and binary files. If youโ€™re curious to learn more, have a look at the MySQL documentation. 4.2ย Creating Our Database Okay, now itโ€™s time to start working on a database for our Twitter clone. Firstly, we need to connect to MySQL. If youโ€™re using Linux and youโ€™ve installed MySQL through your package man- ager, you can connect through the terminal with the following command. mysql -u root -p Upon which, you will be prompted for your password. Users of XAMPP and MAMP can use PHPMyAdmin, which comes bundled in and allows you to edit your database with a nice web interface. So, first we need to create the database for our website and create a table to hold our microblog posts. Either through PHPMyAdmin or through the MySQL console, run the following lines. CREATE DATABASE MicroBlog; USE MicroBlog;
  • 19. LEARN TO BUILD WITH PHP 19HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: CREATE TABLE MicroBlog ( id integer auto_increment, post varchar(255), primary key (id) ); Unless you see an error message, your table has been created without a hitch. So, a few things you might have noticed there. Firstly, weโ€™re ending each statement with a semi-colon, much like we did when we were writing PHP. Secondly, things are pretty self-explanatory, arenโ€™t they? SQL reads like written English, and itโ€™s pretty easy to under- stand whatโ€™s going on. That said, there are some things in the CREATE TABLE statement which you may be unfamiliar with. The first is โ€˜auto_incrementโ€™. What does this do? Well, ID is a field that uniquely identifies each post. When we created it, we gave it an attribute of โ€˜auto_incrementโ€™, and whenever a new row is added to the database, that row is given a unique number. This number counts up by one, for each row that is added. Finally, what is โ€˜primary key (id)โ€™? Well, we want โ€˜idโ€™ to be completely unique. We also want ID to be a field which can identify a row. Making โ€˜idโ€™ a primary key ensures that these conditions can be met. 4.3ย The Wrong Way To Query The Database So, how do we insert a post into our database? Great question. The traditional way of doing this in PHP looked a bit like this: $conn = mysqli_connect($DBServer, $DBUser, $DBPass, $DBName); You would create a connection to the server using the hostname, database credentials and database name, and as- sign that to an object. In this instance, weโ€™ve called it $conn (for connection). We then would define the database query we wish to make. $query = mysqli_query($conn, โ€œINSERT INTO MicroBlog VALUES (โ€˜$postโ€™)โ€); And then we would close the connection to the database.
  • 20. LEARN TO BUILD WITH PHP 20HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: mysqli_close($conn); So, what wrong with this? Well, it relies upon one key assumption; that any input passed to the database can be trusted. That isnโ€™t always the case. If youโ€™re not very careful, itโ€™s entirely possible to sneak in some arbitrary SQL code, which can then result in data leakages or the defacement of the records stored within your database. LinkedIn learned about this the hard way. A poorly sanitized input lead to the unintended (and unauthorized) release of thousands of user records in a debacle that was referred to as LeakedIn. It was an incident that cost them dearly, both with respect to the financial cost of making good, as well as the goodwill lost by losing millions of rows of personal information. So, how do we safely use a database with PHP? 4.4ย Meet MeekroDB MeekroDBย is a library that makes it easy to interact with a database without being wide open to an external threat. It has been designed from the ground up to beย impervious to SQL Injection attacks. Itโ€™s free for non-profit use, but if you plan to use it in a commercial project, you need to pay for a license. Download a copy of MeekroDB from the official website. Once youโ€™ve got it, unzip it and place it in your document root directory. Now, letโ€™s go back to your text editor. Open postForm.php and add the following lines. require_once โ€˜meekrodb.2.2.class.phpโ€™; DB::$user = โ€˜userโ€™; DB::$password = โ€˜passwordโ€™; DB::$dbName = โ€˜databaseโ€™; Change โ€˜userโ€™, โ€˜passwordโ€™ and โ€˜databaseโ€™ with your actual database username, password and database name. Now, itโ€™s time to insert your post into your database. Add the following lines of code. DB::debugMode(); $microBlog = $_POST[โ€˜microBlogโ€™]; DB::insert(โ€˜MicroBlogโ€™, array( โ€˜postโ€™ = $microBlog) ); So, letโ€™s break this down.
  • 21. LEARN TO BUILD WITH PHP 21HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: DB::debugMode(); throws out error messages if we do something wrong. As a result, itโ€™s really quite handy to leave this in our code, as it makes the process of development that bit easier. DB::insert is called when we need to insert one or more items into the database. โ€˜MicroBlogโ€™ refers to the database table, whilst โ€˜postโ€™ contains the message which youโ€™ve just posted to the website. We can see if our posts have reached the database by opening up PHPMyAdmin and having a look. If youโ€™re using MySQL on Linux, and youโ€™ve installed it from the package manager, you can open up MySQL from the terminal and run the following commands. Use MicroBlog; Select * from MicroBlog; Simple, right? Give that a go and next, weโ€™re going to look at displaying our posts on the homepage. I promise, itโ€™s not too hard.
  • 22. LEARN TO BUILD WITH PHP 22HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: 5.ย Getting Content From The Database Weโ€™ve introduced MeekroDB already. This is the database library that allows us to interact securely with a MySQL database within the context of a PHP application. If youโ€™ve completed the previous chapter, you should have some posts in the database. However, theyโ€™re just sitting in a database not being used. What a pity! So, letโ€™s look at getting them into the browser. We know that we can use SQL is the language used by MySQL in order to query the database. Whilst MeekroDB allows you to insert content into your database without using SQL, you have to use some SQL in order to retrieve records. 5.1ย Selecting And Presenting Results One such statement is the โ€˜Select Statementโ€™. We have previously used this to see if our files had propagated to the database. Weโ€™re going to use it again here. Below the closing form tag, add ?php and ? and in-between write the following lines of code. ?php require_once โ€˜meekrodb.2.2.class.phpโ€™; DB::$user = โ€˜rootโ€™; DB::$password = โ€˜rootโ€™; DB::$dbName = โ€˜MicroBlogโ€™; $results = DB::query(โ€œSELECT post FROM MicroBlogโ€); foreach ($results as $row){ echo โ€œdiv class=โ€™microBlogโ€™โ€ . $row[โ€˜postโ€™] . โ€œ/divโ€; } ? Letโ€™s look at this a bit more closely. We know what the first five lines do. We previously used them as part of inserting our posts into the database. $results = DB::query(โ€œSELECT post FROM MicroBlogโ€); This line selects all posts from the table โ€˜MicroBlogโ€™, and then copies them to a variable called $results. And then it gets interesting. So, $results happens to consist of a number of items. This means that we can iterate over them using something that is strongly reminiscent of those โ€˜forโ€™ loops that we previously looked at. foreach ($results as $row){ echo โ€œdiv class=โ€™microBlogโ€™โ€ . $row[โ€˜postโ€™] . โ€œ/divโ€; } So, here weโ€™re going over each result, and mapping it to a variable. We then print it out in between some โ€˜divโ€™ tags. These allow us to encapsulate each post, and apply stylings to each of them.
  • 23. LEARN TO BUILD WITH PHP 23HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: It doesnโ€™t look like much now, does it? Letโ€™s change that. 5.2ย Styling Create a new file called โ€˜style.cssโ€™ and add the following line of HTML code in-between the โ€˜Headโ€™ tags. link rel=โ€stylesheetโ€ type=โ€text/cssโ€ href=โ€style.cssโ€ Now, itโ€™s time to make each post look a bit more distinctive and noticeable. In โ€˜style.cssโ€™, add the following lines. body { background-color: #99CCFF ; } form { text-align: center; margin-left: 300px; margin-right: 300px; } .microBlog { text-align: center; margin-left: 300px; margin-right: 300px; margin-bottom: 10px; border-style:solid; border-width:5px; } I wonโ€™t insult your intelligence by explaining line-for-line what this does. You can probably work it out, just by reading it. Weโ€™ve given each post a bit of padding, so that itโ€™s relatively centered in the screen. Weโ€™ve also given it a border, and aligned the form in the center of the screen. This produces something that looks a bit like this. Cool, right? Now, in our penultimate chapter, weโ€™re going to bring together everything weโ€™ve learned so far, and look at how we can handle logins.
  • 24. LEARN TO BUILD WITH PHP 24HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: 6.ย Logins And Authentication Letโ€™s imagine that we only want one person to be able to post updates on our website. Itโ€™s almost as if weโ€™re creating a highly personal Twitter. 6.1ย The Users Table First, letโ€™s create a table to handle our login information. This will have two fields. The first is for the username and the second is for the password. This can be represented in SQL as follows: CREATE TABLE Credentials ( username varchar(255), password varchar(255), PRIMARY KEY (username) ); As before, run this against your database, either through the terminal or through PHPMyAdmin. 6.2ย PHP Sessions Now, we need to handle logins and registrations. We do that with PHP sessions. The way these work is reasonably simple. You have a number of variables that are present throughout a web application, and these can be in a state of presence or otherwise, depending on whether a user is logged in or not.
  • 25. LEARN TO BUILD WITH PHP 25HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: Before you can handle sessions, you have to first initialize the session. Add this line to the top of index.php. ?php session_start(); ? This line has to appear in every file which accesses the session. Now, we need to ensure that the post submission form is only visible to those who are logged in. Replace the form we created earlier with the following lines of code. ?php if(isset($_SESSION[โ€˜loggedinโ€™])){ echo โ€˜form action=โ€postForm.phpโ€ method=โ€postโ€ TextArea name=โ€microBlogโ€ id=โ€microBlogโ€ cols=โ€30โ€ rows=โ€10โ€ /TextArea /br input type=โ€submitโ€ /formโ€™; } ? $_SESSION[โ€˜loggedinโ€™ ] is a session variable. When itโ€™s set, the user will be able to see the form used to create posts. Letโ€™s add something else. else { echo โ€˜form action=โ€œlogin.phpโ€ method=โ€œpostโ€ Username: input type=โ€œtextโ€ name=โ€œusernameโ€ id=โ€usernameโ€ / /br Password: input type=โ€œtextโ€ name=โ€œpasswordโ€ id=โ€passwordโ€ / input type=โ€submitโ€ /formโ€™; } When you browse to localhost/index.php now, you will see that you can no longer post a status, and you are being prompted to log in. It works! But first, weโ€™re going to have to create an account to log in with. So, letโ€™s add the following lines to our index page. if (isset($_SESSION[โ€˜loggedinโ€™])){ echo โ€˜a href=โ€logout.phpโ€Log Out/aโ€™; } else { echo โ€˜a href=โ€register.phpโ€Register/aโ€™; } If our user is logged in, they will be presented with an option to log out. Likewise, if our user isnโ€™t logged in, they will be presented with an option to register. Now, we need to create a register form. Create a new file called register.php and add the following. ?php session_start(); ? !doctype html html lang=โ€enโ€ head meta charset=โ€UTF-8โ€ titleRegister/title link rel=โ€stylesheetโ€ type=โ€text/cssโ€ href=โ€style.cssโ€ /head body h2Register/h2 form action=โ€œregisterForm.phpโ€ method=โ€œpostโ€ pUsername: input type=โ€œtextโ€ name=โ€œusernameโ€ id=โ€usernameโ€/p pPassword: input type=โ€œtextโ€ name=โ€œpasswordโ€ id=โ€passwordโ€/p input type=โ€submitโ€ /form /body
  • 26. LEARN TO BUILD WITH PHP 26HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: /html While youโ€™re at it, add the following lines to style.css. h2 { text-align: center; } 6.3ย Registering Users Now, we need to add some logic for registering a user. Create a new file called registerForm.php and add the follow- ing lines. ?php require_once โ€˜meekrodb.2.2.class.phpโ€™; DB::$user = โ€˜rootโ€™; DB::$password = โ€˜rootโ€™; DB::$dbName = โ€˜MicroBlogโ€™; $username = $_POST[โ€˜usernameโ€™]; $password = $_POST[โ€˜passwordโ€™]; $hash = password_hash($password, PASSWORD_DEFAULT); DB::insert(โ€˜Credentialsโ€™, array( โ€˜usernameโ€™ = $username, โ€˜passwordโ€™ = $hash )); header(โ€˜Location: http://localhost:8888/index.phpโ€™); ? A lot of this should be pretty familiar, but some stuff is new. Iโ€™ll explain that now. Security is always at the forefront of the application developer. Itโ€™s always embarrassing when a major security breach happens, resulting in a deluge of customer information being leaked. Trust me. Itโ€™s never pleasant. And it doesnโ€™t help that people tend to recycle passwords. Yep, if your site gets hacked and someone gains access to your usersโ€™ passwords, it may lead to your usersโ€™ accounts on other sites being compromised. Hashing allows you to encrypt a password with a cryptographic algorithm, making it remarkably difficult to reverse it to its original form. That task is accomplished with a single line of code in PHP. $hash = password_hash($password, PASSWORD_DEFAULT); However, the example I provided isnโ€™t enough. Passwords need to be salted. What is this, you ask? Well, itโ€™s another line of defense, and makes it near-enough impossible for your userโ€™s passwords to be decrypted. However, this is a little too complicated for a small guide. As a result, Iโ€™d encourage you to do some further reading on the topic. This blog post gives a pretty solid guide to salting passwords with PHP [http://www.sitepoint.com/hashing-passwords-php- 5-5-password-hashing-api/]. Finally, we have this curious line. header(โ€˜Location: http://localhost:8888/index.phpโ€™); This does one task, which is to redirect the browser to the home page. Simple, really. 6.4ย Logging In Create a file called โ€˜login.phpโ€™ and add the following lines. ?php session_start(); ob_start(); require_once โ€˜meekrodb.2.2.class.phpโ€™; DB::$user = โ€˜rootโ€™; DB::$password = โ€˜rootโ€™; DB::$dbName = โ€˜MicroBlogโ€™;
  • 27. LEARN TO BUILD WITH PHP 27HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: $username = $_POST[โ€˜usernameโ€™]; $password = $_POST[โ€˜passwordโ€™]; $result = DB::queryFirstRow(โ€œSELECT * FROM Credentials where username = %sโ€, $username); $hash = $result[โ€˜passwordโ€™]; if (password_verify($password, $hash)) { $_SESSION[โ€˜loggedinโ€™] = 1; header(โ€˜Location: http://localhost:8888/โ€™); } else { echo โ€œLogin failedโ€; } ? Like before, thereโ€™s nothing wildly new here. Weโ€™ve introduced DB::queryFirstRow. However, this is pretty transparent with what it does, and retrieves the first row from the database. This is slightly quicker than DB::query, and produces an object which we donโ€™t have to iterate over. Another concept which has been introduced is the password_verify() function. This allows us to compare an unhashed and hashed password, and to see if it is a match. If it is, we then set $_SESSION[โ€˜loggedinโ€™] to a value (in this case, one) and then redirect to the homepage, where we are then able to log out and to post new tweets. Now, test it out by seeing if you can log in and create a new post! 6.5ย Logging Out Logging out is easy. Create a new file with a name of โ€˜logout.phpโ€™. Inside, add the following lines. ?php session_start(); session_destroy(); header(โ€˜Location: http://localhost:8888/โ€™); ? The session which previously contained the activated โ€˜loggedinโ€™ variable has now been destroyed, effectively logging us out. Once destroyed, the user is then redirected to the homepage.
  • 28. LEARN TO BUILD WITH PHP 28HTTP://MAKEUSEOF.COM MATTHEW HUGHES, HTTP://WWW.MATTHEWHUGHES.CO.UK share: 7.ย Conclusion And Further Reading I hope you enjoyed this short introduction to the PHP programming language. I know it was a whistle-stop tour. I know it was brief. I know it was hurried. Despite this, I hope I communicated all my points clearly. If you are dissatisfied, or have further questions, please contact me. My email address is me@mat- thewhughes.co.uk, and I can also be reached on Twitter. My username isย @matthewhughesย and I am always happy to respond to reader feedback. Before we wrap things up, I want to address a couple more things. Firstly, the PHP programming language is an awesome, powerful tool. If you are eager to do some further reading, please check outย PHP The Right Wayย andย Programming PHPย by Oโ€™Reilly. Both are amazing resources, and are highly recommended. My colleagues at MakeUseOf have also previously recommended someย free resources to learn PHP. Finally, the source code to this project is available on my personal Github. You can find theย repository here. If youโ€™re unsure of what Git is, check out this article aboutย Git version control. If you donโ€™t know how to use Github, check outย Git Real by CodeSchool. It will bring you up to speed pretty quickly, and itโ€™s free. Thank you for your time. Matthew Hughes Guide Published: March 2014
  • 29. Did you like this PDF Guide? Then why not visit MakeUseOf.com for daily posts on cool websites, free software and internet tips? If you want more great guides like this, why not subscribe to MakeUseOf and receive instant access to 50+ PDF Guides like this one covering wide range of topics. More- over, you will be able to download free Cheat Sheets, Free Giveaways and other cool things. Home: http://www.makeuseof.com MakeUseOf Answers: http://www.makeuseof.com/answers PDF Guides: http://www.makeuseof.com/pages/ Tech Deals: http://www.makeuseof.com/pages/hot-tech-deals Follow MakeUseOf: RSS Feed: http://feedproxy.google.com/Makeuseof Newsletter: http://www.makeuseof.com/subscribe/ Facebook: http://www.facebook.com/makeuseof Twitter: http://www.twitter.com/Makeuseof Think youโ€™ve got what it takes to write a manual for MakeUseOf.com? Weโ€™re always willing to hear a pitch! Send your ideas to justinpot@makeuseof.com.