IO

By IO we mean working with files…

Read a file

There are multiple ways to read a file:

are most important ones.

File

The file-function takes a filename as argument and returns an array where each array item corresponds to a line in the file.

$lines = file('/path/to/file.txt');

File_get_contents

This function takes a filename as argument and returns a string containing the complete file contents (hence the name).

$complete_contents = file_get_contents('path/to/file.txt');

Create/Write a file

Touch

touch can be used to update the modification date of a file. If the file doesn’t exist yet, it will be created.

touch('new-file.txt'); // create new-file.txt
touch('new-file.txt'); // update modifaction timestamp of new-file.txt

Write

fwrite can be used to write contents to a file handle.

A handle can be created via fopen.

$handle = fopen('file.txt', 'w'); // 'w' indicatets open file for writing
fwrite($handle, 'Hello world'); // Write hello world to opened file
fclose($handle); // close file

This sequence of opening, writing and closing a file is quite cumbersome, therefor a shorthand is also available: file_put_contents.

$nr_bytes_written = file_put_contents('/path/to/file.txt', $file_contents );

Remove a file

A file can be deleted via unlink.

$delete_ok = unlink('/path/to/file.txt');

Rename a file

A file can be renamed via rename.

$rename_ok = rename('/path/to/file.txt', '/path/to-new-filename.txt');

Directories

Similar functions exist for directories:

  • mkdir: Create directory

    mkdir('/path/to/dir');
  • rmdir: Delete directory

    rmdir('/path/to/dir');
  • rename: Rename directory

    rename('/path/to/dir', '/path/-to-new-dirname');

List all files in a directory:

  • readdir: Iterate over the files in a directory-handle

    $handle = opendir('/path/to/dir');
    
    while (false !== ($file = readdir($handle))) {
    
        echo "$file\n";
    }
  • glob: List all files in a directory (as array) matching a certain pattern.

    $files = glob('/path/to/dir/*.php');

Upload files

File can be uploaded via a form-submission. The tag used to specify files is:

<input type="file" name="uploaded-file">

Info: In order to use the input[type=file], the form must specify the enctype-attribute:

<form action="#" method="post" enctype="multipart/form-data">

    <input type="file" name="uploaded-file">

    <input type="submit" value="submit" name="submit">
</form>

When a form containing files is submitted the $_FILES special PHP-variable is populated with the file(s) currently uploading:

$_FILES = Array
(
    [uploaded-file] => Array
        (
            [name] => MyFile.txt             // name of the file
            [type] => text/plain             // filetype
            [tmp_name] => /tmp/php/php1h4j1o // php stores the file in a randomized tmp location
            [error] => 0                     // 0 = UPLOAD_ERR_OK --> no errors
            [size] => 123                    // the size in bytes
        )

    [file2] => Array
        (
            [name] => MyFile.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/php/php6hst32
            [error] => UPLOAD_ERR_OK
            [size] => 98174
        )
)

PHP stores the uploaded file in a temporary location. We must use the files contents or move the file to a different location. At the next request this tmp_name will be something else. So keep this in mind.

If we opt not to read the file and process it, but move the file instead, the move_uploaded_file should be used to move a file to a new destination.

This function has some additional checks builtin and is thus the recommended way to move uploaded files:

move_uploaded_file('/tmp/php/php1h4j10', '/home/me/some-file.txt');

Exercises

Exercise:

Create a web-page which allows to upload a file, and print the contents of the file.

Exercise:

Create a web-page which allows to upload a file, and:

  • report line-, word-a and character-count in a table
    • nicely spaced cells
    • lines, words, characters as rows but bold (headers)
  • list the top 10 most frequent words.
    • use a list but show all items aside each other (one line).

Exercise:

Create a web-page which allows to upload or paste multi-fasta data and:

  • report number of sequences
  • print the sequences:
    • fasta header is bold
    • nucleotides are monospaced, 80 characters wide
  • report GC-content per sequence

Exercise:

Create a web-page which allows to upload or paste multi-fasta data and:

  • print the sequences:
    • fasta header is header
    • (inter)link to fasta blocks
    • nucleotides are monospaced, 80 characters wide
    • each nucleotide should have its own color:
      • A: red
      • T: yellow
      • G: green
      • C: blue
  • Display the nucleotide frequencies in a bar graph. (A: xx%, T: xx%, …)

Exercise:

Create a web-page which allows to upload or paste multi-fasta data and:

  • Print the sequences:
    • fasta header is header
    • (inter)link to fasta blocks
    • nucleotides are monospaced, 80 characters wide
    • each nucleotide should have its own color the user can select from a list of options
    • add an option (checkbox) indicating the nucleotides should be grouped in groups of 10. (Example: ATGCATCGAT GCATCGATGC ATCGATGCA)
  • Handle invalid nucleotides in one of three ways:
    • Ingore: do nothing: handle the invalid NT as a valid NT.
    • Remove: remove the invalid NT from the output
    • Highlight: highlight the invalid NT in the sequence.
  • Display the nucleotide frequencies in a bar graph. (A: xx%, T: xx%, …)

Exercise:

Create a web-page which allows to upload a file or paste some text, and specify a list of terms.

  • Print the uploaded/pasted text
  • Highlight all the specified terms in the uploaded/pasted text. (for example each term starts at a new line in a textarea)
  • Extra: allow the user to specify the color per term. For example: the|red a|green an

Exercise:

In the previous exercises we created a single page application capable of receiving DNA sequences and displaying the nucleotides sequences colored on screen with an additional frequency graph.

Let’s now extend this single page application into a multi page web-app.

This app is composed out of three pages:

  • Home (index.php)
  • Submit a new job (submit.php)
  • Visualise the sequences (color.php)

All pages also share a common navigation bar and styles.

Exercise:

Create a paste-bin web-app. The app allows the user to create a new snippet and save it (eq. write to file) via a webpage. The user can browse all snippets and view them by clicking a link…

This app is composed out of three pages:

  1. index: list all the uploaded snippets
  2. upload: a form:
    • snippet name
    • contents Allow the user to specify a new snippet to store. Make sure:
    • no empty snippets or snippets with no name can be uploaded.
    • snippet name doesn’t already exists.
  3. snippet contents: show the contents of a snippet