Uploaded by sforshing

PHP Semester Review

advertisement
Intro To Web
Programming
WI TH P HP S EM ESTER R EV IEW
What We Learned
1.
Introduction
2.
Capturing Data & Variables
3.
CRUD
4.
Control Structures
5.
Error Handling, Re-using Code, &
Authentication
6.
Working With Images
7.
Search & Sort
8.
Procedural PHP VS Object Oriented
PHP
Introduction
An Introduction
We covered a lot over this semester. This document will highlight the main milestones that
we explored through our PDF's and our coding videos. It is my hope that this document
helps you to cement the lessons that we have had over the last 13 weeks together.
Although this document will cover our main milestones it is by no means the only document
that you should review before the exam!
Web Application
Architecture
There are two parts to client-side architecture:
• A Server:
▪ A server can be a file, printer, website,
database, or even an email.
• A Network:
▪ A network is a communication system. When
we refer to a network in this scenero we are
talking about how a server can send
information to a client through a process
called routing.
Static Vs. Dynamic Web Applications
On the surface one wouldn't notice a difference between a static and dynamic web
application, however on the backend the difference is like night and day! A static web
application is built using just languages like HTML and CSS, dynamic web applications
however are built using a combination of HTML, CSS, and a sever side language like PHP.
By using a language like PHP developers are able to build agile websites where the
conditions that we dictate combined with how the user interactes with the application will
determine how and what content will be available to them.
In our lesson I provided a diagram of how this
type of application works, so as a refersher, let's
look at the steps:
How Dynamic
Web
Applications
Work?
1.
User makes a HTTP request.
2.
The HTTP request goes to the server.
3.
The server sends a request to the database.
4.
The database sends the response back to
the server.
5.
The server processes the response from
the server using a server-side language.
6.
The server then returns the request back to
the user.
Capturing Data
&
Variables
In our lesson we compared this to how we get
groceries, so let's just sum up the process of
capturing data.
• We create a form this could be a login, sign
up, search bar.
• Once the user has provided the information
that is required from our form, we then send
the data of to be processed.
• Once the form has been "sent off" we gather
Capturing Data
the information and use varibles to contain
the data before it is saved to the database.
Capturing Data
•
Once we have populated our variables, we
then run our validation checks and make
sure they meet our defined conditions.
•
If the conditions are met, we then use a sql
query to inject the data to our database.
Capturing Data – The HTML Form
Ok so we know how to build a form, so let's just focus on the required attributes that we need
to process a form.
•
Method Post
• is an array of variables passed to the current script via the HTTP POST method.
•
Method Get
•
•
is an array of variables passed to the current script via the URL parameters.
GET should NEVER be used for sending passwords or other sensitive information!
Action
•
is how we tell the form what file is supposed to be used to process our form, this can include the
same file that the form is on, or it can be a separate file all together.
So, What Is A Variable?
Easy answer, a variable is a word that a developer creates to store data so that it can be used
later in a program.
Longer answer, a variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume). These variables must adhear to a set of rules. What are these
rules you ask, see them below:
•
A variable must start with a $.
•
A variable name must start with a letter or underscore.
•
A variable name cannot start with a number.
•
A variable name can only contain alpha-numeric characters and underscores.
•
A variable cannot contain any spaces.
Create, Read, Update, & Delete
Also Called
CRUD
What Is a CRUD?
Well as mentioned in the title CRUD stands for Create, Read, Update, and Delete. These four
functions are the cornerstone for any dynamic web application, infact you will not find a content
management system that is not a type of CRUD system.
•
Create – this is the process of gathering data from the user, then creating a record in our
database.
•
Read - this is the process of reading the data stored on our database and then displaying it
to the end user.
•
Update - this is the process of updating the data stored in the database.
•
Delete - this is the process of removing a record from our database. This process cannot be
undone and should be included with safeguards in place.
CRUD Functions
All of the above-mentioned functions can
be completed by using a combination of
SELECT, INSERT, UPDATE, and DELETE
sql statements that are excuted by using
PHP control structures. So, with that in
mind as we move on to the next section
try to keep the CRUD functionality in the
back of your mind
Control Structures
What Are Control Structures?
In PHP, a control structure is a way that a developer can
control how the code is excuted in your program.
Generally, a program is excuted sequentially, a control
structure allows us developers to alter that flow if
needed.
These control structures are the core features of the
PHP language. Our control structures can be broken
down into 3 types:
• Conditional Expressions
• Selection Structures
• Interation Structures
A conditional expression is a combination of different
operators that we use to set the condition of an if
statement or a loop. For example, this if statement:
If($name == 'bob'){
Conditional
Expressions
Add statement
}
In this if statement we are checking to see if our variable
is equal to the string 'bob'. If this condition is found to be
true, then we will proceed to excute the contained
statement.
For a deeper breakdown of the different operators see
the Weekly Learning folder called Control Structures.
Selection
Structures
Where conditional expressions are the
operators that check if a statement is
true, a selection structure is the
statement that is excuted is the condition
is equal to true. These selection
structures are knowen as: if, else, elseif,
while loop, do-while loop, for loop,
foreach loop, break, continue, switch,
declare, return, require, require_once,
and include.
Can't remember what all these do? Go to
weekly learning and find the descriptions
in the Control Structures folder.
Iteration
Structures
Iteration and selection structures are
closely tied to one another. When we
refer to an iteration structure, we are
referencing just the loops. These loops
are:
•
While
•
Do-while
•
For
•
Foreach
For a better understanding of these
loops, go back and review the code part
of the Control Structure lesson.
Error Handling, Re-using Code, &
Authentication
Error Handling
We all make mistakes and users can be unpredictable, because of that we need to know
how to handle the inevitable error. As developers we have a few tools that we can call on to
help deal with an unexpected error, let's take a quick recap:
•
Server Error Codes.
•
Custom Error Pages (the dreaded 404).
•
Try Catch Blocks
•
Error Logging.
•
Email Notifications.
Error Handling – Server Codes
HTTP(s) has a list of predefined error codes that our
applications can use, below is a list of the most common error
codes that we may encounter:
•
404 – Page not found
•
403 – Forbidden
•
500 – Internal Server Error
•
503 – Service Unavailable
Out of all these errors the most common is the 404. Luckly
this is the error that is the easiest to address.
Custom Error
Pages
One way to handle an error is to make it look like it really
isn't an error. Now to be clear this does not work for every
error. A custom error page is more for the 400 error, by
default the browser will always display the error. Now if the
error is a 500 or a 503, there isn't much we can do because
these are considered fatal errors. But our 400 or 403, that is
something we can address.
One of the best ways to handle a 400 / 403 error is to use a
try / catch statement.
The Try & Catch
When we are looking to catch an error the try and catch statement allows us to identify and
address the errors effeciently and gracefully. Here is what our try and catch looks like:
Try{
Add some code
}
Catch (Exception $e){
Handle the error
}
Authentication
When we start talk about authentication, we are actually talking about session control, and
how we can use it to see if a user should be on the page that they are trying to visit. In our
lesson we used authentication to confirm that a user was logged in, we did this by using
session_start().
When session_start() is called or when a session auto starts, PHP will call the open and
read session save handlers. These will either be a built-in save handler provided by default
or by PHP extensions.
Once our session has started, we can do a check to see if it is set, if a session is not
confirmed we can send a user to a page like a sign in page.
Working With Images
Image & File Uploads
In our lesson we explored how we can approach working with file types and storing them in
our database. This can be an incredibly tedious task as we could see in our code lesson. So
where do we start?
In order to upload any type of file to our database we have to circle back to our HTML form
and add the attribute enctype="multipart/form-data". Without that attribute we will not be
able to pass on any type of files. Once we have added our enctype, we will need to add the
right input, this is the type="file".
The Mechanics
Of A File Upload
•
When we upload a file with PHP, the
file is saved to a temporay location in
the server's cache.
•
We can inspect the file then choose to
save it to a permanent directory.
•
We can also access the properties of
our file upload:
•
The name
•
The file type (the extension)
•
The size (in bytes)
•
The tmp_name
For more information on file uploads visit
our coding lesson.
Search & Sort
Sorting With PHP
When we are creating our sort function there are two different parameters, the array and
the flags, the flags parameter is optional. Let's look at the different types of flags:
•
SORT_REGULAR - compare items normally.
•
SORT_NUMERIC - compare items numerically.
•
SORT_STRING - compare items as strings.
•
SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses
the locale, which can be changed using setlocale() .
•
SORT_NATURAL - compare items as strings using "natural ordering" like natsort().
•
SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or
SORT_NATURAL to sort strings case-insensitively.
The Search Function
The search function is a well document and flushed out function with PHP and for our
lesson we looked at the main 4, let's recap:
• strlen – get the string length.
• substr - this extracts a part of a string.
• str_replace – this will replace one or more characters in a string with 1 or more other
characters.
• explode - this will return an array of strings, each of these strings are a substring of
the string formed by splitting in on the boundries formed by the string seperator.
For more info on this topic visit this link: https://www.php.net/manual/en/ref.strings.php
Procedural PHP VS Object
Oriented PHP
Procedural VS OOP
For the better part of the semester, we worked with procedural PHP, procedural is a great
place to start with PHP because it allows us to get use to the PHP syntex. As a natural
progression we moved to working with OOP.
So, what is the difference and why change at all?
Well, for large-scale web applications, OOP is extremely useful. If the project is likely to
require additional functionality at a later time, OOP is a good practice.
Where for smaller modules, OOP is not always necessary. In these cases, the more abstract
quality of the OOP approach tends to add too many unnecessary functions and files.
OOP PHP Concepts
Well there is a lot of them but for now let's stick to the ones we used!
• Class - let's assume we have a class named Fruit. A Fruit can have properties like name,
color, weight, etc. We can define variables like $name, $color, and $weight to hold the
values of these properties. When the individual objects (apple, banana, etc.) are created,
they inherit all the properties and behaviors from the class, but each object will have
different values for the properties.
• Object - we can create multiple objects from a class. Each object has all the properties
and methods defined in the class, but they will have different property values. Objects of a
class is created using the new keyword.
Download