Dr Andres Baravalle
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.
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 |
file_get_contents(), file() and readfile() can be also be used to get a remote resource.
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. |
Use a combination of file_get_contents()
and regular expressions to include today's t comic strip from phdcomics.com into an HTML page.
Please note: this activity is more challenging than others as phdcomics.com is now using some screenscraping avoidance tecniques. To solve it you will need to impersonate a browser, using curl.
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.
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.
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.
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).
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).
<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
$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>";
}
}
?>
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
:
$_POST
array to decide whether to display the form or parse its content Email is sent with the mail()
function. Your server/workstation needs a configured mail server/mail gateway for the mail function to work.
Update the form you developped in the previous activity to send a email notification after each log-in, as a security measure.
$_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:
$_SERVER['PATH_INFO']
evaluates to the string at the right of the last / sign in a URL.
Examples:
Querystrings and path_info can be used to pass parameters across your PHP pages:
This approach is heavily used in large applications as Wordpress, Magento and Drupal to create fancy URLs.
Querystrings are also often used to save a state (e.g. to pass a paramter between pages, or to store session data):
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).
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 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).
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 informationexpire
is the time the cookie expires (as a unix timestamp) Cookies are stored in the $_COOKIE
array.
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).
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.
Know limiting factors in the use of cookies include:
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.
Sessions are normally used to store data from the user, to improve the experience of users on the web site.
Typical information stored includes:
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).
<?php
// page1.php
session_start();
echo 'Welcome to page #1';
$_SESSION['pages']['timestamp'] = array($_SERVER['PHP_SELF'], time());
?>
Create two pages: page1.php
and page2.php
.
page1.php
will:
page2.php
will:
After a successful log in, page1.php shouldn't display any more the login form. Extra activity: include a log out link.
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License