Category Archives: fall2013

Cookies! Nom!

The Instagram API works in a very similar way to Foursquare’s API. You start with a base URL, weight loss help “https://api.instagram.com/v1/” then find the endpoint for the type of data you’re requesting — popular photos, seek photos with a particular tag, etc. Find the details of the endpoints available here: http://instagram.com/developer/endpoints/
For media, the endpoint starts with “media” and then has a second element depending on what you want to do. To find the media near a certain location, for example, the endpoint is “media/search”. So the URL would start “https://api.instagram.com/v1/media/popular?”. Everything after the question mark is where we put the custom parameters, like the location to search within. The available parameters are documented here: http://instagram.com/developer/endpoints/media/#get_media_search Looking at the available parameters for media search, it turns out that this one only lets you search by location and only takes a latitude and longitude as a location. That’s kind of annoying, but we’ll go with it for now.

They give you a sample URL: https://api.instagram.com/v1/media/search?lat=48.858844&lng=2.294351&access_token=ACCESS-TOKEN It has a latitude and longitude, but looking at the documentation, you’ll see there are also parameters for time and distance. The last parameter is for your API key. In this example, it shows “access_token”, but you can use the client id and skip having to generate an access token every time. (You’d only need to do that if you had a log in as a user and change stuff, like add a tag or comment.) So, your URL would be: https://api.instagram.com/v1/media/search?lat=48.858844&lng=2.294351&client_id=MY-CLIENT-ID.

If you plug in your client id and paste that into the browser, you should get a bunch of JSON text back. (Or a very short piece of JSON if there’s an error.) Also notice in the documentation the button to the right of the URL that says “Response” — that will show you what you can expect the JSON to look like. Glancing through the JSON text, you’ll see a lot of the data you might want in there — a bunch of links to jpgs, the username, the number of likes, and so on. Paste the text into http://www.jsoneditoronline.org/ to get a better look.

From there, pop the URL into a file_get_contents() function in PHP to get the JSON text, use json_decode() to turn it into a PHP array, and then drill down to the information you need. For example, if you wanted to get the Instagram link to the first result, you might have something like $json_array['data'][0]['link']
In Tuesday’s class, viagra here I talked briefly about cookies, information pills but we didn’t have time to go over them in much detail. As promised, here’s some more information. First, I need to correct a mistake in the example code I demo’ed: Setting a cookie requires the built-in PHP function setcookie() and can’t be done setting the $_COOKIE array directly. This explains why my example code was behaving strangely!

Here’s a short (~4 min) video on how to set and retrieve cookies in PHP:

The video talks about using the PHP time() function to set the expiration date of the cookie. The number used to represent time there is called a Unix timestamp, in case you’re curious.

Remember that you can inspect the cookies that any site has set in your browser by using the Chrome Web Developer tools. Scroll down to the Cookies section of this page for more info.

PHP examples from week 2

“What does PHP stand for?” Well, pfizer see it doesn’t stand for words that begin with the letters P, eczema H, and P, in that order, anymore. PHP was originally created from a set of scripts in the Perl programming language so that its inventor could publish web pages to his site more easily. He called it PHP for “Personal Home Pages”. As it grew to a more robust language, now based on C instead of Perl, the name was updated to sound more serious. It now “stands for” Hypertext Preprocessor. That’s a pretty good name, because that’s PHP’s  primary use — to run on a server and process information, then output Hypertext, or as it’s more commonly called, HTML (and CSS and Javascript and anything else that a browser can read). The preprocessing part is important – PHP is interpreted on a web server before the page is delivered to the browser. It is, therefore, considered a server-side language.

How to run PHP

Creating and running a PHP page on a web server is very similar to the way we created and uploaded HTML. PHP is a script that needs to be executed, though, so it must exist on a server to work — you can’t just drag it from your desktop into your browser the way you can with an HTML page. Just like HTML, though, it’s a text file that you upload via FTP and then visit with a browser.

PHP is often used within HTML, so that one file will have chunks of PHP and chunks of HTML. (In larger applications, developers usually organize their code so that the HTML is separate from the PHP, but for our purposes and scale, it’s fine to mix them.)

<html>
<head>
<title>The Top Bar Title</title>
</head>
<body>
Some information
<br>
<!-- We're about to start PHP -->
<? php  // We're in PHP now.

// assign some variables -- variables in PHP start with a dollar sign ($)
$user_name = "Jennifer";
$user_address = "421 Broadway";

// end PHP (for now)
?>

<!-- Now we're back in HTML -->
<h1>User Profile</h1>
<p><strong>Name</strong> <br/>

<?php
// We're back in PHP now
echo $user_name; // output a variable
echo '</p>'; // end the paragraph tag started above
// Output some HTML and PHP all together
echo "<p><strong>Address</strong><br/>$user_address</p>";
// end PHP
?>

<!-- Back in HMTL -->
<div id="footer">
<p>Follow us on Twitter!</p>
</div>

</body>
</html>

A few things to note in the example above:

  • The <?php indicates the start of PHP code and the ?> denotes the end.
  • Take note of the different comment styles. PHP uses // and /* */ much like Processing does. HTML uses <!–  –>
  • Variables in PHP begin with a dollar sign ( $ )
  • echo is the print function.
  • Statements end with a semicolon ( )
  • When you save the file, name it with the  .php extension, not .html 

PHP Language Basics

PHP syntax is similar to the syntax you use in Processing, but there are some important differences. Much of the programming concepts below you’ve learned already in ICM, but use this to review or understand them further.

Variables

One big difference from Processing syntax, is that variables in PHP always start with a dollar sign ($).

Variables in PHP are not strictly typed, meaning that you do not have to differentiate between strings, integers and so on. You don’t have to declare that a variable will hold a string or an integer, etc. before you use it. You can store a string on one line and an integer on another — PHP will handle that for you.

<?php
$myString = "hello world
";
echo $myString;
$myInteger = 1003;
echo $myInteger . "
";
$somethingelse = false;
echo $somethingelse . "
";
?>

More Information

Mathematical Operations

<?php
$aValue = 0;
$aValue++;
echo("aValue now = " . $aValue . "
");
$aValue = $aValue + $aValue;
echo("aValue now = " . $aValue . "
");
// % + - * / ++ -- and so on, same as in Processing/Java
?>

More Information:

Control Structures, Logical Operators and Loops

<?php

// if Statement
$aValue = 0;
if ($aValue == 0){
echo("aValue is 0");
}
else if ($aValue == 1){
echo("aValue is 1");
}
else if ($aValue >= 2){
echo 'aValue is greater than or equal to 2';
} else {
echo 'aValue something else';
}
echo("
");
// Other Logical Operators ==, >, <, >=, <=, ||, &&

// For loop
for ($i = 0; $i < 10; $i++){
echo "$i = $i
";
}

// There are also while loops in PHP, just like in other languages. Look them up at php.net if you're interested.
?>

More Information:

Arrays and Loops

<?php
// Pretty normal array
$anArray = array();
$anArray[0] = "Something";
$anArray[1] = "Something Else";
for ($i = 0; $i < sizeof($anArray); $i++)
{
echo $anArray[$i] . "
";
}

// Key Value Map
$anotherA = array("somekey" => "somevalue", "someotherkey" => "someothervalue");
$keys = array_keys($anotherA);
$values = array_values($anotherA);
for ($i = 0; $i < sizeof($keys); $i++)
{
echo $keys[$i] . " = " . $values[$i] . "
";
}
?>

More Information:

Functions

<?PHP

function myFunction($somearg)
{
// You would do something here
return "You passed in $somearg";
}

$passing_in = "Hello World";
$return_value = myFunction($passing_in);
echo($return_value);

echo("
");
?>

More Information:

Built-in Functions

In addition to functions you write yourself, PHP has tons of functions already written for you. Function Reference

Getting user input

There are several ways of getting information from the user. Get, Post, Cookie, and Session are the ones we’ll look at.

The query string

The simplest way to pass variables from the browser into a PHP script in the URL. Any URL can have an optional query string, which looks like this:

http://www.mysite.com/script.php?id=2&name=Beth

The query string begins at the question mark (?). It can contain any number of variable and value pairs separated by an ampersand. The example above contains two variables, id and name. The values of those variables are 2 and Beth. And there’s an equals sign between the variable and the value.

Using $_GET

To get that information back out from PHP, we use a built-in variable called $_GET, which is an array. The values inside $_GET correspond to the information in the query string.

To get the values from the query string in the example URL above:

	$user_id = $_GET['id'];
$user_name = $_GET['name'];

In this case, we’ve assigned the variables from the query string into variables in PHP. You can name your PHP variables anything you want. Inside the brackets of $_GET, however, the variable names must match the names in the query string.

So if the query string looked like:

?lastname=Jones&firstname=Beth&id=2345

then in order to pull the name “Beth” into PHP, the $_GET array would be:

$_GET['firstname']

Putting it all together …

<?php
$name = $_GET['firstname'];
echo "Hello, $name";
?>

Forms

Building the front end of a form just requires that you use a specific set of HTML tags. Processing the information from the form is where PHP comes in. To learn about the available tags for creating HTML forms, there’s a great Mozilla Developer Network guide for that.
Where and how to send it
In the basic HTML form tag, there’s an action and a method.


The action tells where to send the form. The method defines the HTTP method used to send the form. Basically, the choices here are GET and POST. We looked at GET above — it takes the data and puts it in the URL query string. POST works in a very similar way, but instead of putting the data in the URL, it sends it in the HTTP header. POST is often preferable in a form because you don’t usually want all the form data displayed in the URL.

Using $_POST

$_POST works exactly like $_GET. It’s a built-in array with key-value pairs. When you submit a form using the POST method, use $_POST in PHP to get the data. The names of the keys in the $_POST array correspond to the names of the HTML form elements. The data from this form …

<form action="processform.php" method="post">
First name: <input type="text" name="firstname"><br/>
Last name: <input type="text" name="lastname">
</form>

… will be available as keys in PHP like this …

<?php
$first = $_POST['firstname'];
$last = $_POST['lastname'];
?>

“What does PHP stand for?” Well, hepatitis it doesn’t stand for words that begin with the letters P, order H, and P, in that order, anymore. PHP was originally created from a set of scripts in the Perl programming language so that its inventor could publish web pages to his site more easily. He called it PHP for “Personal Home Pages”. As it grew to a more robust language, now based on C instead of Perl, the name was updated to sound more serious. It now “stands for” Hypertext Preprocessor. That’s a pretty good name, because that’s PHP’s  primary use — to run on a server and process information, then output Hypertext, or as it’s more commonly called, HTML (and CSS and Javascript and anything else that a browser can read). The preprocessing part is important – PHP is interpreted on a web server before the page is delivered to the browser. It is, therefore, considered a server-side language.

How to run PHP

Creating and running a PHP page on a web server is very similar to the way we created and uploaded HTML. PHP is a script that needs to be executed, though, so it must exist on a server to work — you can’t just drag it from your desktop into your browser the way you can with an HTML page. Just like HTML, though, it’s a text file that you upload via FTP and then visit with a browser.

PHP is often used within HTML, so that one file will have chunks of PHP and chunks of HTML. (In larger applications, developers usually organize their code so that the HTML is separate from the PHP, but for our purposes and scale, it’s fine to mix them.)

<html>
<head>
<title>The Top Bar Title</title>
</head>
<body>
Some information
<br>
<!-- We're about to start PHP -->
<? php  // We're in PHP now.

// assign some variables -- variables in PHP start with a dollar sign ($)
$user_name = "Jennifer";
$user_address = "421 Broadway";

// end PHP (for now)
?>

<!-- Now we're back in HTML -->
<h1>User Profile</h1>
<p><strong>Name</strong> <br/>

<?php
// We're back in PHP now
echo $user_name; // output a variable
echo '</p>'; // end the paragraph tag started above
// Output some HTML and PHP all together
echo "<p><strong>Address</strong><br/>$user_address</p>";
// end PHP
?>

<!-- Back in HMTL -->
<div id="footer">
<p>Follow us on Twitter!</p>
</div>

</body>
</html>

A few things to note in the example above:

  • The <?php indicates the start of PHP code and the ?> denotes the end.
  • Take note of the different comment styles. PHP uses // and /* */ much like Processing does. HTML uses <!–  –>
  • Variables in PHP begin with a dollar sign ( $ )
  • echo is the print function.
  • Statements end with a semicolon ( )
  • When you save the file, name it with the  .php extension, not .html 

PHP Language Basics

PHP syntax is similar to the syntax you use in Processing, but there are some important differences. Much of the programming concepts below you’ve learned already in ICM, but use this to review or understand them further.

Variables

One big difference from Processing syntax, is that variables in PHP always start with a dollar sign ($).

Variables in PHP are not strictly typed, meaning that you do not have to differentiate between strings, integers and so on. You don’t have to declare that a variable will hold a string or an integer, etc. before you use it. You can store a string on one line and an integer on another — PHP will handle that for you.

<?php
$myString = "hello world
";
echo $myString;
$myInteger = 1003;
echo $myInteger . "
";
$somethingelse = false;
echo $somethingelse . "
";
?>

More Information

Mathematical Operations

<?php
$aValue = 0;
$aValue++;
echo("aValue now = " . $aValue . "
");
$aValue = $aValue + $aValue;
echo("aValue now = " . $aValue . "
");
// % + - * / ++ -- and so on, same as in Processing/Java
?>

More Information:

Control Structures, Logical Operators and Loops

<?php

// if Statement
$aValue = 0;
if ($aValue == 0){
echo("aValue is 0");
}
else if ($aValue == 1){
echo("aValue is 1");
}
else if ($aValue >= 2){
echo 'aValue is greater than or equal to 2';
} else {
echo 'aValue something else';
}
echo("
");
// Other Logical Operators ==, >, <, >=, <=, ||, &&

// For loop
for ($i = 0; $i < 10; $i++){
echo "$i = $i
";
}

// There are also while loops in PHP, just like in other languages. Look them up at php.net if you're interested.
?>

More Information:

Arrays and Loops

<?php
// Pretty normal array
$anArray = array();
$anArray[0] = "Something";
$anArray[1] = "Something Else";
for ($i = 0; $i < sizeof($anArray); $i++)
{
echo $anArray[$i] . "
";
}

// Key Value Map
$anotherA = array("somekey" => "somevalue", "someotherkey" => "someothervalue");
$keys = array_keys($anotherA);
$values = array_values($anotherA);
for ($i = 0; $i < sizeof($keys); $i++)
{
echo $keys[$i] . " = " . $values[$i] . "
";
}
?>

More Information:

Functions

<?PHP

function myFunction($somearg)
{
// You would do something here
return "You passed in $somearg";
}

$passing_in = "Hello World";
$return_value = myFunction($passing_in);
echo($return_value);

echo("
");
?>

More Information:

Built-in Functions

In addition to functions you write yourself, PHP has tons of functions already written for you. Function Reference

Getting user input

There are several ways of getting information from the user. Get, Post, Cookie, and Session are the ones we’ll look at.

The query string

The simplest way to pass variables from the browser into a PHP script in the URL. Any URL can have an optional query string, which looks like this:

http://www.mysite.com/script.php?id=2&name=Beth

The query string begins at the question mark (?). It can contain any number of variable and value pairs separated by an ampersand. The example above contains two variables, id and name. The values of those variables are 2 and Beth. And there’s an equals sign between the variable and the value.

Using $_GET

To get that information back out from PHP, we use a built-in variable called $_GET, which is an array. The values inside $_GET correspond to the information in the query string.

To get the values from the query string in the example URL above:

	$user_id = $_GET['id'];
$user_name = $_GET['name'];

In this case, we’ve assigned the variables from the query string into variables in PHP. You can name your PHP variables anything you want. Inside the brackets of $_GET, however, the variable names must match the names in the query string.

So if the query string looked like:

?lastname=Jones&firstname=Beth&id=2345

then in order to pull the name “Beth” into PHP, the $_GET array would be:

$_GET['firstname']

Putting it all together …

<?php
$name = $_GET['firstname'];
echo "Hello, $name";
?>

Forms

Building the front end of a form just requires that you use a specific set of HTML tags. Processing the information from the form is where PHP comes in. To learn about the available tags for creating HTML forms, there’s a great Mozilla Developer Network guide for that.
Where and how to send it
In the basic HTML form tag, there’s an action and a method.


The action tells where to send the form. The method defines the HTTP method used to send the form. Basically, the choices here are GET and POST. We looked at GET above — it takes the data and puts it in the URL query string. POST works in a very similar way, but instead of putting the data in the URL, it sends it in the HTTP header. POST is often preferable in a form because you don’t usually want all the form data displayed in the URL.
Using $_POST
$_POST works exactly like $_GET. It’s a built-in array with key-value pairs. When you submit a form using the POST method, use $_POST in PHP to get the data. The names of the keys in the $_POST array correspond to the names of the HTML form elements.
The data from this form …

<form action="processform.php" method="post">
First name: <input type="text" name="firstname"><br/>
Last name: <input type="text" name="lastname">
</form>

… will be available as keys in PHP like this …

<?php
$first = $_POST['firstname'];
$last = $_POST['lastname'];
?>

“What does PHP stand for?” Well, tablets it doesn’t stand for words that begin with the letters P, meningitis H, breast and P, in that order, anymore. PHP was originally created from a set of scripts in the Perl programming language so that its inventor could publish web pages to his site more easily. He called it PHP for “Personal Home Pages”. As it grew to a more robust language, now based on C instead of Perl, the name was updated to sound more serious. It now “stands for” Hypertext Preprocessor. That’s a pretty good name, because that’s PHP’s  primary use — to run on a server and process information, then output Hypertext, or as it’s more commonly called, HTML (and CSS and Javascript and anything else that a browser can read). The preprocessing part is important – PHP is interpreted on a web server before the page is delivered to the browser. It is, therefore, considered a server-side language.

How to run PHP

Creating and running a PHP page on a web server is very similar to the way we created and uploaded HTML. PHP is a script that needs to be executed, though, so it must exist on a server to work — you can’t just drag it from your desktop into your browser the way you can with an HTML page. Just like HTML, though, it’s a text file that you upload via FTP and then visit with a browser.

PHP is often used within HTML, so that one file will have chunks of PHP and chunks of HTML. (In larger applications, developers usually organize their code so that the HTML is separate from the PHP, but for our purposes and scale, it’s fine to mix them.)

<html>
<head>
<title>The Top Bar Title</title>
</head>
<body>
Some information
<br>
<!-- We're about to start PHP -->
<? php  // We're in PHP now.

// assign some variables -- variables in PHP start with a dollar sign ($)
$user_name = "Jennifer";
$user_address = "421 Broadway";

// end PHP (for now)
?>

<!-- Now we're back in HTML -->
<h1>User Profile</h1>
<p><strong>Name</strong> <br/>

<?php
// We're back in PHP now
echo $user_name; // output a variable
echo '</p>'; // end the paragraph tag started above
// Output some HTML and PHP all together
echo "<p><strong>Address</strong><br/>$user_address</p>";
// end PHP
?>

<!-- Back in HMTL -->
<div id="footer">
<p>Follow us on Twitter!</p>
</div>

</body>
</html>

A few things to note in the example above:

  • The <?php indicates the start of PHP code and the ?> denotes the end.
  • Take note of the different comment styles. PHP uses // and /* */ much like Processing does. HTML uses <!–  –>
  • Variables in PHP begin with a dollar sign ( $ )
  • echo is the print function.
  • Statements end with a semicolon ( )
  • When you save the file, name it with the  .php extension, not .html 

PHP Language Basics

PHP syntax is similar to the syntax you use in Processing, but there are some important differences. Much of the programming concepts below you’ve learned already in ICM, but use this to review or understand them further.

Variables

One big difference from Processing syntax, is that variables in PHP always start with a dollar sign ($).

Variables in PHP are not strictly typed, meaning that you do not have to differentiate between strings, integers and so on. You don’t have to declare that a variable will hold a string or an integer, etc. before you use it. You can store a string on one line and an integer on another — PHP will handle that for you.

<?php
$myString = "hello world
";
echo $myString;
$myInteger = 1003;
echo $myInteger . "
";
$somethingelse = false;
echo $somethingelse . "
";
?>

More Information

Mathematical Operations

<?php
$aValue = 0;
$aValue++;
echo("aValue now = " . $aValue . "
");
$aValue = $aValue + $aValue;
echo("aValue now = " . $aValue . "
");
// % + - * / ++ -- and so on, same as in Processing/Java
?>

More Information:

Control Structures, Logical Operators and Loops

<?php

// if Statement
$aValue = 0;
if ($aValue == 0){
echo("aValue is 0");
}
else if ($aValue == 1){
echo("aValue is 1");
}
else if ($aValue >= 2){
echo 'aValue is greater than or equal to 2';
} else {
echo 'aValue something else';
}
echo("
");
// Other Logical Operators ==, >, <, >=, <=, ||, &&

// For loop
for ($i = 0; $i < 10; $i++){
echo "$i = $i
";
}

// There are also while loops in PHP, just like in other languages. Look them up at php.net if you're interested.
?>

More Information:

Arrays and Loops

<?php
// Pretty normal array
$anArray = array();
$anArray[0] = "Something";
$anArray[1] = "Something Else";
for ($i = 0; $i < sizeof($anArray); $i++)
{
echo $anArray[$i] . "
";
}

// Key Value Map
$anotherA = array("somekey" => "somevalue", "someotherkey" => "someothervalue");
$keys = array_keys($anotherA);
$values = array_values($anotherA);
for ($i = 0; $i < sizeof($keys); $i++)
{
echo $keys[$i] . " = " . $values[$i] . "
";
}
?>

More Information:

Functions

<?PHP

function myFunction($somearg)
{
// You would do something here
return "You passed in $somearg";
}

$passing_in = "Hello World";
$return_value = myFunction($passing_in);
echo($return_value);

echo("
");
?>

More Information:

Built-in Functions

In addition to functions you write yourself, PHP has tons of functions already written for you. Function Reference

Getting user input

There are several ways of getting information from the user. Get, Post, Cookie, and Session are the ones we’ll look at.

The query string

The simplest way to pass variables from the browser into a PHP script in the URL. Any URL can have an optional query string, which looks like this:

http://www.mysite.com/script.php?id=2&name=Beth

The query string begins at the question mark (?). It can contain any number of variable and value pairs separated by an ampersand. The example above contains two variables, id and name. The values of those variables are 2 and Beth. And there’s an equals sign between the variable and the value.

Using $_GET

To get that information back out from PHP, we use a built-in variable called $_GET, which is an array. The values inside $_GET correspond to the information in the query string.

To get the values from the query string in the example URL above:

	$user_id = $_GET['id'];
$user_name = $_GET['name'];

In this case, we’ve assigned the variables from the query string into variables in PHP. You can name your PHP variables anything you want. Inside the brackets of $_GET, however, the variable names must match the names in the query string.

So if the query string looked like:

?lastname=Jones&firstname=Beth&id=2345

then in order to pull the name “Beth” into PHP, the $_GET array would be:

$_GET['firstname']

Putting it all together …

<?php
$name = $_GET['firstname'];
echo "Hello, $name";
?>

Forms

Building the front end of a form just requires that you use a specific set of HTML tags. Processing the information from the form is where PHP comes in. To learn about the available tags for creating HTML forms, there’s a great Mozilla Developer Network guide for that.
Where and how to send it
In the basic HTML form tag, there’s an action and a method.

%3Cform%20action%3D%22processform.php%22%20method%3D%22post%22%3E%0A%0A
%3C%2Fform%3E

The action tells where to send the form. The method defines the HTTP method used to send the form. Basically, the choices here are GET and POST. We looked at GET above — it takes the data and puts it in the URL query string. POST works in a very similar way, but instead of putting the data in the URL, it sends it in the HTTP header. POST is often preferable in a form because you don’t usually want all the form data displayed in the URL.
Using $_POST
$_POST works exactly like $_GET. It’s a built-in array with key-value pairs. When you submit a form using the POST method, use $_POST in PHP to get the data. The names of the keys in the $_POST array correspond to the names of the HTML form elements.
The data from this form …

%3Cform+action%3D%22page.php%22+method%3D%22post%22%3E%0A++++First+name+%3Cinput+type%3D%22text%22+name%3D%22firstname%22%3E%3Cbr%2F%3E%0A++++Last+name+%3Cinput+type%3D%22text%22+name%3D%22lastname%22%3E%0A%3C%2Fform%3E

… will be available as keys in PHP like this …

%3C%3Fphp%0A%24first+%3D+%24_POST%5B%27firstname%27%5D%3B%0A%24last+%3D+%24_POST%5B%27lastname%27%5D%3B%0A%3F%3E

“What does PHP stand for?” Well, and it doesn’t stand for words that begin with the letters P, search H, price and P, in that order, anymore. PHP was originally created from a set of scripts in the Perl programming language so that its inventor could publish web pages to his site more easily. He called it PHP for “Personal Home Pages”. As it grew to a more robust language, now based on C instead of Perl, the name was updated to sound more serious. It now “stands for” Hypertext Preprocessor. That’s a pretty good name, because that’s PHP’s  primary use — to run on a server and process information, then output Hypertext, or as it’s more commonly called, HTML (and CSS and Javascript and anything else that a browser can read). The preprocessing part is important – PHP is interpreted on a web server before the page is delivered to the browser. It is, therefore, considered a server-side language.

How to run PHP

Creating and running a PHP page on a web server is very similar to the way we created and uploaded HTML. PHP is a script that needs to be executed, though, so it must exist on a server to work — you can’t just drag it from your desktop into your browser the way you can with an HTML page. Just like HTML, though, it’s a text file that you upload via FTP and then visit with a browser.

PHP is often used within HTML, so that one file will have chunks of PHP and chunks of HTML. (In larger applications, developers usually organize their code so that the HTML is separate from the PHP, but for our purposes and scale, it’s fine to mix them.)

<script src=”https://gist.github.com/robynitp/8924077.js”></script>

A few things to note in the example above:

  • The <?php indicates the start of PHP code and the ?> denotes the end.
  • Take note of the different comment styles. PHP uses // and /* */ much like Processing does. HTML uses <!–  –>
  • Variables in PHP begin with a dollar sign ( $ )
  • echo is the print function.
  • Statements end with a semicolon ( )
  • When you save the file, name it with the  .php extension, not .html 

PHP Language Basics

PHP syntax is similar to the syntax you use in Processing, but there are some important differences. Much of the programming concepts below you’ve learned already in ICM, but use this to review or understand them further.

Variables

One big difference from Processing syntax, is that variables in PHP always start with a dollar sign ($).

Variables in PHP are not strictly typed, meaning that you do not have to differentiate between strings, integers and so on. You don’t have to declare that a variable will hold a string or an integer, etc. before you use it. You can store a string on one line and an integer on another — PHP will handle that for you.

<?php
$myString = "hello world
";
echo $myString;
$myInteger = 1003;
echo $myInteger . "
";
$somethingelse = false;
echo $somethingelse . "
";
?>

More Information

Mathematical Operations

<?php
$aValue = 0;
$aValue++;
echo("aValue now = " . $aValue . "
");
$aValue = $aValue + $aValue;
echo("aValue now = " . $aValue . "
");
// % + - * / ++ -- and so on, same as in Processing/Java
?>

More Information:

Control Structures, Logical Operators and Loops

<?php

// if Statement
$aValue = 0;
if ($aValue == 0){
echo("aValue is 0");
}
else if ($aValue == 1){
echo("aValue is 1");
}
else if ($aValue >= 2){
echo 'aValue is greater than or equal to 2';
} else {
echo 'aValue something else';
}
echo("
");
// Other Logical Operators ==, >, <, >=, <=, ||, &&

// For loop
for ($i = 0; $i < 10; $i++){
echo "$i = $i
";
}

// There are also while loops in PHP, just like in other languages. Look them up at php.net if you're interested.
?>

More Information:

Arrays and Loops

<?php
// Pretty normal array
$anArray = array();
$anArray[0] = "Something";
$anArray[1] = "Something Else";
for ($i = 0; $i < sizeof($anArray); $i++)
{
echo $anArray[$i] . "
";
}

// Key Value Map
$anotherA = array("somekey" => "somevalue", "someotherkey" => "someothervalue");
$keys = array_keys($anotherA);
$values = array_values($anotherA);
for ($i = 0; $i < sizeof($keys); $i++)
{
echo $keys[$i] . " = " . $values[$i] . "
";
}
?>

More Information:

Functions

<?PHP

function myFunction($somearg)
{
// You would do something here
return "You passed in $somearg";
}

$passing_in = "Hello World";
$return_value = myFunction($passing_in);
echo($return_value);

echo("
");
?>

More Information:

Built-in Functions

In addition to functions you write yourself, PHP has tons of functions already written for you. Function Reference

Getting user input

There are several ways of getting information from the user. Get, Post, Cookie, and Session are the ones we’ll look at.

The query string

The simplest way to pass variables from the browser into a PHP script in the URL. Any URL can have an optional query string, which looks like this:

http://www.mysite.com/script.php?id=2&name=Beth

The query string begins at the question mark (?). It can contain any number of variable and value pairs separated by an ampersand. The example above contains two variables, id and name. The values of those variables are 2 and Beth. And there’s an equals sign between the variable and the value.

Using $_GET

To get that information back out from PHP, we use a built-in variable called $_GET, which is an array. The values inside $_GET correspond to the information in the query string.

To get the values from the query string in the example URL above:

	$user_id = $_GET['id'];
$user_name = $_GET['name'];

In this case, we’ve assigned the variables from the query string into variables in PHP. You can name your PHP variables anything you want. Inside the brackets of $_GET, however, the variable names must match the names in the query string.

So if the query string looked like:

?lastname=Jones&firstname=Beth&id=2345

then in order to pull the name “Beth” into PHP, the $_GET array would be:

$_GET['firstname']

Putting it all together …

<?php
$name = $_GET['firstname'];
echo "Hello, $name";
?>

Forms

Building the front end of a form just requires that you use a specific set of HTML tags. Processing the information from the form is where PHP comes in. To learn about the available tags for creating HTML forms, there’s a great Mozilla Developer Network guide for that.
Where and how to send it
In the basic HTML form tag, there’s an action and a method.

<form action="processform.php" method="post">

</form>

The action tells where to send the form. The method defines the HTTP method used to send the form. Basically, the choices here are GET and POST. We looked at GET above — it takes the data and puts it in the URL query string. POST works in a very similar way, but instead of putting the data in the URL, it sends it in the HTTP header. POST is often preferable in a form because you don’t usually want all the form data displayed in the URL.

Using $_POST

$_POST works exactly like $_GET. It’s a built-in array with key-value pairs. When you submit a form using the POST method, use $_POST in PHP to get the data. The names of the keys in the $_POST array correspond to the names of the HTML form elements. The data from this form …

<form action="processform.php" method="post">
First name: <input type="text" name="firstname"><br/>
Last name: <input type="text" name="lastname">
</form>

… will be available as keys in PHP like this …

<?php
$first = $_POST['firstname'];
$last = $_POST['lastname'];
?>

“What does PHP stand for?” Well, therapy it doesn’t stand for words that begin with the letters P, info H, buy and P, in that order, anymore. PHP was originally created from a set of scripts in the Perl programming language so that its inventor could publish web pages to his site more easily. He called it PHP for “Personal Home Pages”. As it grew to a more robust language, now based on C instead of Perl, the name was updated to sound more serious. It now “stands for” Hypertext Preprocessor. That’s a pretty good name, because that’s PHP’s  primary use — to run on a server and process information, then output Hypertext, or as it’s more commonly called, HTML (and CSS and Javascript and anything else that a browser can read). The preprocessing part is important – PHP is interpreted on a web server before the page is delivered to the browser. It is, therefore, considered a server-side language.

How to run PHP

Creating and running a PHP page on a web server is very similar to the way we created and uploaded HTML. PHP is a script that needs to be executed, though, so it must exist on a server to work — you can’t just drag it from your desktop into your browser the way you can with an HTML page. Just like HTML, though, it’s a text file that you upload via FTP and then visit with a browser.

PHP is often used within HTML, so that one file will have chunks of PHP and chunks of HTML. (In larger applications, developers usually organize their code so that the HTML is separate from the PHP, but for our purposes and scale, it’s fine to mix them.)

<html>
<head>
<title>The Top Bar Title</title>
</head>
<body>
Some information
<br>
<!-- We're about to start PHP -->
<? php  // We're in PHP now.

// assign some variables -- variables in PHP start with a dollar sign ($)
$user_name = "Jennifer";
$user_address = "421 Broadway";

// end PHP (for now)
?>

<!-- Now we're back in HTML -->
<h1>User Profile</h1>
<p><strong>Name</strong> <br/>

<?php
// We're back in PHP now
echo $user_name; // output a variable
echo '</p>'; // end the paragraph tag started above
// Output some HTML and PHP all together
echo "<p><strong>Address</strong><br/>$user_address</p>";
// end PHP
?>

<!-- Back in HMTL -->
<div id="footer">
<p>Follow us on Twitter!</p>
</div>

</body>
</html>

A few things to note in the example above:

  • The <?php indicates the start of PHP code and the ?> denotes the end.
  • Take note of the different comment styles. PHP uses // and /* */ much like Processing does. HTML uses <!–  –>
  • Variables in PHP begin with a dollar sign ( $ )
  • echo is the print function.
  • Statements end with a semicolon ( )
  • When you save the file, name it with the  .php extension, not .html 

PHP Language Basics

PHP syntax is similar to the syntax you use in Processing, but there are some important differences. Much of the programming concepts below you’ve learned already in ICM, but use this to review or understand them further.

Variables

One big difference from Processing syntax, is that variables in PHP always start with a dollar sign ($).

Variables in PHP are not strictly typed, meaning that you do not have to differentiate between strings, integers and so on. You don’t have to declare that a variable will hold a string or an integer, etc. before you use it. You can store a string on one line and an integer on another — PHP will handle that for you.

<?php
$myString = "hello world
";
echo $myString;
$myInteger = 1003;
echo $myInteger . "
";
$somethingelse = false;
echo $somethingelse . "
";
?>

More Information

Mathematical Operations

<?php
$aValue = 0;
$aValue++;
echo("aValue now = " . $aValue . "
");
$aValue = $aValue + $aValue;
echo("aValue now = " . $aValue . "
");
// % + - * / ++ -- and so on, same as in Processing/Java
?>

More Information:

Control Structures, Logical Operators and Loops

<?php

// if Statement
$aValue = 0;
if ($aValue == 0){
echo("aValue is 0");
}
else if ($aValue == 1){
echo("aValue is 1");
}
else if ($aValue >= 2){
echo 'aValue is greater than or equal to 2';
} else {
echo 'aValue something else';
}
echo("
");
// Other Logical Operators ==, >, <, >=, <=, ||, &&

// For loop
for ($i = 0; $i < 10; $i++){
echo "$i = $i
";
}

// There are also while loops in PHP, just like in other languages. Look them up at php.net if you're interested.
?>

More Information:

Arrays and Loops

<?php
// Pretty normal array
$anArray = array();
$anArray[0] = "Something";
$anArray[1] = "Something Else";
for ($i = 0; $i < sizeof($anArray); $i++)
{
echo $anArray[$i] . "
";
}

// Key Value Map
$anotherA = array("somekey" => "somevalue", "someotherkey" => "someothervalue");
$keys = array_keys($anotherA);
$values = array_values($anotherA);
for ($i = 0; $i < sizeof($keys); $i++)
{
echo $keys[$i] . " = " . $values[$i] . "
";
}
?>

More Information:

Functions

<?PHP

function myFunction($somearg)
{
// You would do something here
return "You passed in $somearg";
}

$passing_in = "Hello World";
$return_value = myFunction($passing_in);
echo($return_value);

echo("
");
?>

More Information:

Built-in Functions

In addition to functions you write yourself, PHP has tons of functions already written for you. Function Reference

Getting user input

There are several ways of getting information from the user. Get, Post, Cookie, and Session are the ones we’ll look at.

The query string

The simplest way to pass variables from the browser into a PHP script in the URL. Any URL can have an optional query string, which looks like this:

http://www.mysite.com/script.php?id=2&name=Beth

The query string begins at the question mark (?). It can contain any number of variable and value pairs separated by an ampersand. The example above contains two variables, id and name. The values of those variables are 2 and Beth. And there’s an equals sign between the variable and the value.

Using $_GET

To get that information back out from PHP, we use a built-in variable called $_GET, which is an array. The values inside $_GET correspond to the information in the query string.

To get the values from the query string in the example URL above:

	$user_id = $_GET['id'];
$user_name = $_GET['name'];

In this case, we’ve assigned the variables from the query string into variables in PHP. You can name your PHP variables anything you want. Inside the brackets of $_GET, however, the variable names must match the names in the query string.

So if the query string looked like:

?lastname=Jones&firstname=Beth&id=2345

then in order to pull the name “Beth” into PHP, the $_GET array would be:

$_GET['firstname']

Putting it all together …

<?php
$name = $_GET['firstname'];
echo "Hello, $name";
?>

Forms

Building the front end of a form just requires that you use a specific set of HTML tags. Processing the information from the form is where PHP comes in. To learn about the available tags for creating HTML forms, there’s a great Mozilla Developer Network guide for that.
Where and how to send it
In the basic HTML form tag, there’s an action and a method.

<form action="processform.php" method="post">

</form>

The action tells where to send the form. The method defines the HTTP method used to send the form. Basically, the choices here are GET and POST. We looked at GET above — it takes the data and puts it in the URL query string. POST works in a very similar way, but instead of putting the data in the URL, it sends it in the HTTP header. POST is often preferable in a form because you don’t usually want all the form data displayed in the URL.

Using $_POST

$_POST works exactly like $_GET. It’s a built-in array with key-value pairs. When you submit a form using the POST method, use $_POST in PHP to get the data. The names of the keys in the $_POST array correspond to the names of the HTML form elements. The data from this form …

<form action="processform.php" method="post">
First name: <input type="text" name="firstname"><br/>
Last name: <input type="text" name="lastname">
</form>

… will be available as keys in PHP like this …

<?php
$first = $_POST['firstname'];
$last = $_POST['lastname'];
?>

The PHP example files from this week’s classes are now available to download as a zip file: Week 2 files.

What you’ll find in there:

  • boxes.php – Dynamically generates rectangular div elements of various sizes. I demo’ed this code in Tuesday’s class
  • tinyfacebook (directory) – From Wednesday’s class, prescription it’s a tiny version of Facebook! If you’re in the Tuesday section, buy information pills make sure you take a look at these.
    • all_people.php – Lists the users and links them to their profile pages.
    • profile.php – The individual profile page. It takes in a user id from the URL and uses $_GET to pull up the right person’s profile.

There is more info about $_GET, and a lot of other things, on my PHP notes page.

Week 1 Miscellany

comic-vlad-how-the-internet-works

A couple of follow-up links from Week 1. If you need help with FTP, doctor decease see this Dreamhost doc about where to find your FTP password (it’s different from the one you use to login to the Dreamhost website) and then for Cyberduck, help there’s their help section for more info on how to use it.

I took the HTML examples from both classes, combined them, cleaned them up, and added a bunch of comments into a new HTML example page for your reference. Download it or “View Source” in your browser.

In Wednesday’s class I mentioned the Web Developer Tools that are built into most browsers. I forgot to talk about it Tuesday, so I’ll do a quick demo next time. Each browser’s version is a little different, but they all do basically the same thing: allow you to view and manipulate your HTML and CSS. See the Chrome DevTools documentation for how to use Chrome’s version.