Remote resources and sessions

Andres Baravalle

Remote resources and sessions

  • Remote resources, filesystem functions and mail
  • Forms and querystrings
  • Cookies and sessions

Remote resources, filesystem functions and mail

Filesystem functions

PHP includes a large number of filesystem functions.

You will find useful to familiarise yourself with the ones in the next slides. For the full list of functions, please refer to the PHP on-line documentation.

Reading and writing from files

file_get_contents() Reads entire file into a string
file_put_contents() Write a string to a file
file() Reads an entire file into an array
parse_ini_file() Loads in the ini file specified and returns the settings in it in an associative array
readfile() Reads a file and writes it to the output buffer
copy() Copies a file

Using remote resources

file_get_contents(), file() and readfile() can be also be used to get a remote resource.

Getting information on files

file_exists() Checks whether a file or directory exists
dirname() Returns the parent directory's path
basename() Return the trailing name component of a path
realpath() Expands all symbolic links, resolves references to '/./', '/../' and extra '/' characters in the input path and returns the canonicalized absolute pathname.

Activity #1: screenscraping PhDComics

Use a combination of file_get_contents() and regular expressions to include today's t comic strip from phdcomics.com into an HTML page.

Activity #2: screenscraping Dilbert

Use a combination of file_get_contents() and regular expressions to include today's Dilbert comic strip into an HTML page. To facilitate your work, you should disable JavaScript on your browser, as Dilber's web site has anti-screenscraping features.

Activity #3: BBC news

Use a combination of file_get_contents() and regular expressions to extract all the images in http://feeds.bbci.co.uk/news/rss.xml. Show them in your web page.

Forms and querystrings

$_POST & $_GET

PHP can be used to easily process forms submitted by users. $_POST and $_GET variables are automatically populated when submitting a form, and will contain the valutes of the form submitted.

$_POST is an array populated when the form is submitted using the HTTP post method. $_GET is populated when using get. You define the method in your HTML form

HTML forms and PHP

The value of each element of the form will be stored in the $_POST or $_GET variable. You must set up the name attributes in your elements appropriately (e.g. with meaningful names).

PHP and forms: a practical example

In the next few slides we're going to walk through an example of using a form to build a basic authentication backend with PHP.

In the example, the form and the parsing function are in the same page (the code for the example is available here).

In our example, the the usernames and passwords are stored in the same file where the form is. Under normal circumstances they would be stored in configuration files (for a system with few users only) or in a database.

Please note that in our implementation, passwords are not stored directly, but they are salted and hashed (read this for an explanation of why).

PHP and forms: writing the form

<form method="post" action="<?php echo $PHP_SELF; ?>"> 
	<div>
		<label for="name">username</label>
		<input type="text" name="name">
	</div> 
	<div>
		<label for="password">password</label>     
		<input type="text" name="password">
	</div> 
	<div>
		<input type="submit">
	</div>
</form>

PHP and forms: parsing the data


<?php
$username = "john"; 
$salt = "ab13"; 
// password: savage (crypt'ed & salted) 
$password = "abB/9oNNOMLGY"; 

/* sample $_POST
    Array
    (
        [name] => john
        [password] => savage
    )
*/

if(isset($_POST["name"]) and isset($_POST["password"])) {     
	if($_POST["name"] == $username and crypt($_POST["password"], $salt) == $password ) {         
		echo "<p>You are now logged in in the system.</p>";     
	}         
	else {         
		echo "<p>Incorrect username/password combination.</p>";     
	}
}
?>

Activity #4: parsing forms

Create a contact form including name, surname, mobile telephone number and a UEL email address. The form will be processed by that very same PHP page with $_POST:

  • Check the $_POST array to decide whether to display the form or parse its content
  • Use regular expressions to validate the form on the server side; validate at least name, surname and mobile teleoh
  • Eensure that the users has filled all the elements appropriatelly
  • If any field contains incorrect/unexpected content, return an error and communicate it to the user.

Sending emails

Email is sent with the mail() function. Your server/workstation needs a configured mail server/mail gateway for the mail function to work.

Activity #5: sending email

Update the form you developped in the previous activity to send a email notification after each log-in, as a security measure.

QUERY_STRING and PATH_INFO

$_SERVER["QUERY_STRING"] is one of the server variables exposed by PHP. It evaluates to the string at the right of the ? sign in a URL.

Example:

  • http://www.example.com/index.php?this_is_my_query_string

$_SERVER['PATH_INFO'] evaluates to the string at the right of the last / sign in a URL.

Examples:

  • http://www.example.com/this_is_my_path_info.php
  • http://www.example.com/index.php/this_is_also_my_path_info

Using QUERY_STRINGs and PATH_INFO

Querystrings and path_info can be used to pass parameters across your PHP pages:

  • http://www.example.com/index.php?page=home
  • http://www.example.com/index.php?page=form&action=process
  • http://www.example.com/index.php/form/process

This approach is heavily used in large applications as Wordpress, Magento and Drupal to create fancy URLs.

Using querystrings to save state

Querystrings are also often used to save a state (e.g. to pass a paramter between pages, or to store session data):

  • Saving the state: http://www.example-airline.com/index.php?leaving_from=London&destination=Milan&date=26-01-2015
  • Store session data: http://www.example.com/index.php?session_id=1234567AB

Cookies and sessions

Cookies

Cookies are small pieces of information that scripts can store on a client machines. Cookies are sent through HTTP headers (which means that they must be set before the output of any code in the web page).

Cookies do not kill small kitten

"Although cookies cannot carry viruses, and cannot install malware on the host computer, tracking cookies and especially third-party tracking cookies are commonly used as ways to compile long-term records of individuals' browsing histories."

(from Wikipedia)

Cookies cannot be read by other web sites

Cookies are sent only to the domain that originally set the cookie.

For example, if a cookie was set by a URL http://www.example.com, it cannot be read by URLs in http://www.example2.com.

However, you can set site-wide cookies that are valid across a whole domain (e.g. http://example.com and http://www.example.com and http://www2.example.com).

Setting cookies

A cookie can be set with the function setcookie(); below a simplified prototype:

bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path]]])

  • name is the name for the cookie; use them to distinguish the information you want to save
  • value is the value of the information
  • expire is the time the cookie expires (as a unix timestamp)

Reading cookies

Cookies are stored in the $_COOKIE array.

How to use cookies

Cookies can be used to store information about the user that can be useful in the future (for example, to speed up user navigation).

For example, aereolineas.com.ar stores - amongst others - the language and the country of a visitor (so you do not have to switch to your local site after the first visit).

Most commonly, cookies are used to store a session id (more in the next slides).

Activity #6: setting and reading cookies

Write a simple "Hello World" page that records the number of visits to the web page. The page will greet the user with the following phrase: "Hello World. This is your visit number 1." (increase the number on each visit).

You need to use setcookie() to set the cookie and the $_COOKIE array to read the cookie.

Cookies limitations

Know limiting factors in the use of cookies include:

  • Users disabling cookies to avoid being tracked (think AdWords or similar programs)
  • Privacy concerns: cookies could leave sensitive data accessible to attackers with access to a PC
  • RFC 2965, the document that defines how cookies work, specifies that there should not be any maximum size, but in practice browsers typically limit the maximum size of cookies to around 4,000 bytes

Sessions

In practise, cookies are typically used to store a session id; that session id is then matched in web applications to session variables.

The local computer will just store the name of the session, which will be transmitted to the server every time a new page from the server is loaded. The server will match the session id sent with it's list of session and load any data as needed.

How to use sessions?

Sessions are normally used to store data from the user, to improve the experience of users on the web site.

Typical information stored includes:

  • Number of visits to the web site
  • Pages visited on each visit
  • Dates/times for visits in the website

What is important is that sessions allow to monitor users without identifying them. Sessions are heavily used in advertisement (cookies are associated with domains - so advertisers can keep track of what web sites you have been visiting if they are part of their network).

Using sessions in PHP

<?php
// page1.php
session_start();
echo 'Welcome to page #1';
$_SESSION['pages']['timestamp'] = array($_SERVER['PHP_SELF'], time());
?>

Activity #7: using sessions (part 1)

Create two pages: page1.php and page2.php.

page1.php will:

  1. Start a session
  2. If the session variable "authenticated" is not set, set it to False and show a basic login form

 

Activity #7: using sessions (part 2)

page2.php will:

  1. check the username and password;
  2. if the credentials are valid, set the session variable "authenticated" to true
  3. include a link to page1.php

After a successful log in, page1.php shouldn't display any more the login form. Extra activity: include a log out link.

This work

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License

Creative Commons License