PHP Basics
Contents
PHP Basics
Every PHP file needs to have a .php extension and the PHP code contained within PHP tags in the file. E.g.:
HTML goes here.
If you are writing a pure PHP file (no HTML below the closing tag), then make sure you don't have any new lines below that closing tag. It can cause parsing issues.
Another thing you must be careful of is placing semi-colons at the end of every statement. You'll get cryptic parsing errors if you don't.
(Back to top)Comments
You can use three styles of comments:
- C style:
//
- C++ style:
/* ... */
- Hash:
#
For the C style and Hash comments, everything after the comment marker until the end of the line is a comment. For the C++ style, everything between the comment markers is considered a comment. Here's an example:
(Back to top)Variables
Variable names all start with a $ and there is no explicit typing. PHP uses dynamic typing, so it knows the type of a variable based on the value assigned to the variable. The type can change as different values are assigned. Here are some examples:
(Back to top)Printing
You can print using two different function: echo and print. You don't need to worry about including parentheses. E.g.,
(Back to top)Strings
You can use either single or double quote for strings. However, double quoted strings will be processed by PHP, while single quoted strings will not. The processing that double quoted strings get includes the following:
- escape sequences will be interpreted (\n, \t, etc.)
- PHP scalar variables can be included (e.g., echo "This is the value of myInt: $myInt";)
You can concatenate strings and other variables together using the . operator. E.g., echo "This is the value of myInt: " . $myInt;.
(Back to top)Arrays and associative arrays (tables)
Besides scalar values, PHP also supports arrays and associative arrays (which are sometimes called maps, tables, or hash tables in other languages). Arrays can contain any kind of data and it can be mixed. You can have a single array that consists of strings, ints, floats, arrays, and associative arrays. Associative arrays are basically the same, but rather than being indexed numerically, they are indexed by name—a key that is a string. Here's an example of each:
(Back to top)Functions
Functions are declared using the function keyword. Like any variable, the parameter names must be preceded with a $. Here's a function that squares the input parameter and returns the result:
You cannot directly access global variables within a function. For example, the following will not work (or as expected):
$x = 5; function squareX(){ return $x*$x; }In this example, $x does not exist within the scope of the squareX function. In order to get access to $x you must use either the $GLOBALS array, or the global keyword. Here they are in two separate, but equivalent, functions:
(Back to top)Error handling
When you access a php page via a web browser and there are errors during the parsing or execution of the PHP code, you will not be warned about it. The page will either not load or will be blank (you might get a 500 or similar error). During development, it's handy to have these errors displayed. To do that, at the top of a PHP file and just after the opening php tag, include the following:
Be sure to comment this out before your code goes into production mode! That way users won't see the errors.
(Back to top)PHP + Server information
PHP populates a global array called $_SERVER
on each server
request. Some of the more useful ones, especially in developing RESTful
APIs, are:
$_SERVER['REQUEST_METHOD']
: specifies the request method that was used (e.g., GET, POST, PUT, DELETE)$_SERVER['REQUEST_URI']
: specifies the URI used to reach the current script. E.g., if you reached a page by entering the URL http://foo.com/path/to/page.php,$_SERVER['REQUEST_URI']
would be: /path/to/page.php.
PHP + Reading Request Data (POST/GET/PUT)
Two ways (among others) that information can be passed to a server is via POST and GET requests. POST is used for form data, usually, and is not embedded in the URL. GET, on the other had, is embedded in the URL. Here's what a URL with GET parameters looks like:
http://www.foobar.com?key1=value1&key2=value2&key3=value3
The general pattern is that we need a question mark at the end of the address, then pairs of keys and values (just like a map/associative array/object/table) with &'s in between.
GET
The parameters from GET are stored in the global $_GET
associative
array. You can access a particular parameter's value by doing:
$_GET["key"]
, where key is the key of the parameter you want to
lookup. Suppose I entered the parameters:
?name=hank&password=12345
. Then to get the value of the name
parameter, I would do $_GET["name"]
.
POST
POST is exactly the same as GET, except the global associative array is named $_POST. You access parameters the same way.
PUT
Unlike GET and POST, PHP does not populate a global called $_PUT
when the request method is PUT. A very simple and naive way to create such a
global is with the following code:
After that, you can use $_PUT
just like $_POST
and
$_GET
.
URL encoding
Data sent to a server, especially by GET, is usually encoded in something called
URL Encoding or URI Encoding. Fortunately, that doesn't matter for us, because
the $_GET
and $_POST
variables already take care of
decoding those.
PHP + JSON
JSON is a great format for providing data from an API. It stands for JavaScript Object Notation, the reason being that objects (associative arrays) in JavaScript are written almost exactly the way a JSON string looks.
Converting to and from JSON
Because JSON is a popular data format, PHP has added built-in support for it via
two functions: json_encode()
and json_decode()
.
For example, suppose I have the following PHP associative array:
We can output this as a JSON string by issuing: print json_encode($users);. Here's what the full page would look like:
That produces the following JSON:
Converting from JSON to PHP is easy, too. Consider the following code, which is an extension of the above code:
At the end, the variable $asPHPArrayAgain has the same contents as the original PHP array that we converted into JSON.
A PHP page that only outputs JSON
To create a PHP page that only outputs JSON (not HTML), include the following at
the top of your file: header('Content-type: application/json');
. Be
sure to not emit anything other than JSON. You also cannot have more than one
JSON string output, e.g., you should have only a single print statement and a
single invocation of json_encode()
.
PHP + MongoDB
In order to talk to a MongoDB database in PHP, we have to do a few things:
- establish an authenticated connect to the Mongo client
- select the database you want to access
- specify the collection you want to access
- interact with the collection (insert, retrieve, update, and remove documents)
We'll talk about each of these in turn.
Connect to Mongo client
To establish a connection to the database. For our class, we also need to authenticate (so that each group can only see their own database). To do this, you will need to know your database username, password, and the database you want to access. Here's what it looks like (you can set the variables at the top to your information):
By default, we will be conntecting to localhost:27017—that's the port through which the MongoDB client listens for requests.
In a setting outside of this class, you might have a MongoDB instance running
that does not require authentication. If that's the case, then you can simply
do: $connection = new MongoClient();
.
Select the database
Once you've established connection, you'll want to select the database you want to access. In MongoDB, each database consists of 0 or more collections. In order to get access to a collection, we must first select the database that holds the collection:
Select collection
Now that we've selected a database, we can access collections. In MongoDB, a collection is simply a set of documents ("a collection of documents"). So, databases house collections, and collections house documents. A fun thing about MongoDB is that, if you go to access a collection that doesn't exist in the current database, it'll automatically be created for you! So, let's say we want to create a collection called "example". Here's how we'd do that:
Now $collection
points at our collection.
Operations
There are four main operations we'll need to perform:
- insert a new document
- retrieve an existing document
- update an existing document
- removing a document altogether
In order to insert a document, we need to understand what a document is...
What is a document?
In MongoDB, a document is an object very similar to JSON (it's called BSON—see this page for more info (Links to an external site.)). We can use PHP associative arrays directly as documents and insert these into MongoDB. When you retrieve documents, they are also returned as PHP associative arrays. E.g.,
Inserting a new document
To insert a document, use the insert()
function. This takes as its
only parameter the data you want to store. Here's an example:
A unique identifier will be created for this document. If you have another
document with the same name
and hasPets
fields, they
will each be separate documents in the collection, with distinct ids. We'll see
more about ids in the next section.
Retrieving a document
There are a couple of ways to retrieve documents. If you are looking to iterate
through all of the documents in a collection, then use the find()
function with no arguments. That returns a cursor that you can then iterate
over. Here's an example that prints the result out as a JSON string an also
demonstrates how the result can be accessed just like a usual old associative
array:
You can also add search criteria. You can specify what values select fields must contain in order for a document to be include in the result that the cursor iterates over. For example, if we want to find all documents in our collection where the name field is equal to Bob, then we would issue the following command:
When we iterate over cursor, we will only see documents where name is "Bob". To
find all documents where the hasPets
field is set to
true
, we can do:
Now what if we are only looking for a single result? Perhaps we know that the
name field is unique, so we would rather not get a cursor, but just the first
result. There's a special function for that called findOne()
. This
returns an associative array. Here's how we might use it:
Updating an existing document
A common operation is to update an existing document. First, we need to find the document, then update it. Here's an example of the general process:
Removing an item
Removing an document is easy: just specify the criteria of the document you want
to remove when calling the remove()
function:
PHP + RDBMS using PDO
The most portable way to use an RDBMS like MySQL or PostgreSQL is via PHP Data Objects, or PDOs. The PDO class lets us connect to any database that has a PDO-compatible driver and execute statements, run queries, perform transactions, etc. To switch your DBMS, you only have to edit you PDO instantiations, not all your queries and statements. You can find more about PDO's here.
Connecting/closing
Before you can run queries, you need to connect to the database, which can be done as follows:
For the remainder of this section, I will assume the variable $dbh
is an instance of the PDO database connection.
Transactions
Before doing any set of statements (reading or writing) that you would like to be atomic, you should enter into a transaction. You can read up on why transactions are useful and how they work by visiting this PDO reference page. Not every RDBMS supports transactions, so the following will only work for the ones that do. Transactions begin an end like this:
Sometimes we may want to cancel a transaction, that is, undo the effects of any queries we've issued in the transaction up until now. We can do that by issuing a rollback statement:
The PDO library will implicitly rollback a transaction if a commit statement is not issued prior to the connection closing. What that means is that if your script dies during a transaction before a commit is reached, everything will be rolled back.
Executing statements (the CUD in CRUD)
To issue an SQL statement to your RDBMS that will modify its state (creating,
updating, or deleting data), you will use the
exec()
method
on the PDO instance. This method will return the number of rows that were
modified by the statement. Here's an example of creating a new table:
Running queries (the R in CRUD)
To query your RDBMS, use the
query
method.
This method returns a PDOStatement object, which contains the matched rows.
These can be iterated over using a foreach loop. Each row is stored as an
associative array, with column names as keys, and column values as values.
Here's an example:
Using user-provided data in queries and statements
It is extremely unsafe to embed user provided data directly in a query or statement. This could lead to SQL injection attacks. Instead, use the PDO prepared statements. Prepared statements allow you to insert user provided data, which PDO cleans for you to prevent things like SQL injection attacks. Here's an example of them at work:
Using exceptions
It can be convenient to tell PDO to raise exceptions when there are errors
rather than manually checking error flags (as is returned by the
errorCode()
method). When exceptions are enabled, you can use
try-catch blocks. Here's an example of a transaction that we rollback when
an exception is raised:
PHP Cookies / Sessions
Cookies are small containers of information stored in a user's browser and can be accessed—read and written—by a server. Each cookie is associated with a particular server and a particular directory of that server. A PHP page being served from a directory D on server S can only access cookies from a user's browser that are associated with S and any directory D or higher level D (e.g., if for a given cookie, D is "/" (the root directory), then all directories on S can access that cookie).
Why use a cookie? Cookies can be used to store information about a user that might otherwise be stored in a database, such as the last time the user logged on. They are often used for session management, for example storing a session ID unique to the user. Cookie's have expiration dates, after which they will be removed by the browser. So a website may use a cookie to allow users to stay logged in for a period of hours, days, or whatever they want.
To create a cookie in PHP, use the setcookie()
function. You can read the API
here. Here's a basic view of how it works:
You can use the cookie (or see if the cookie is set) via the
$_COOKIE
global array. E.g.,
Cookies are not always the right choice. For instances, cookies can be stolen or manipulated. As such, you should avoid using cookies to store sensitive information (e.g., passwords). An alternative is to use a session. Sessions, at least by default in PHP, work by storing a unique session ID in a cookie. The ID is used to lookup (behind the scenes) information associated with that session stored on the server (via PHP). The cookie is only valid until the browser closes. That means a new session will be started up each time the user accesses the site in a new browser instance.
Here's an example of how to use sessions in PHP, for example, to store that a user is logged in:
You can explicitly end a session (and all data associated with it in) by
issuing a call to session_destroy()
.