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 associate 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 + POST/GET
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.
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 + PostgreSQL
One way of accessing PostgreSQL from PHP is to use the PostgreSQL Functions (the other way is to use the PDO_PGSQL driver and then use the PDO functions).
Connecting/closing
Before you can run queries, you need to connect to the database, which can be done as follows:
In most cases, you won't need the $dbconn
variable any
more—most pg_*()
functions only take it as an optional
parameter. Once you're finished, close the connection like this:
Transactions
Before doing any insert statement or series of atomic statement, you should enter into a transaction. Transactions begin an end like this:
Sometimes it may be the case that we realize we want to cancel a transaction,
that is, ignore any queries up until now. We can do that by issuing a
ROLLBACK
statement:
Running queries
There are several ways to issue queries to a PostgreSQL database. The simplest, which is not secure when you are interpolating user provided values, is as follows:
Note that pg_query()
returns a query result resource if successful
and false otherwise. The query result resource is basically a 2D array of
table rows and columns. Columns are listed in the order specified by the
select statement, or the table (if *
is used).
As mentioned, the pg_query()
function shouldn't be used when
using user provided data (e.g., values provided via POST or GET). This leaves
us open for SQL injection attacks. On safer alternative (there are several)
is to use the pg_query_params()
function, which works like this:
PHP Cookies
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, by storing in the cookie that a user has logged in. 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.,