Jump to content

Programming Fundamentals/Files/PHP

From Wikiversity

files.php

[edit | edit source]
<?php

// This program creates a file, adds data to the file, displays the file,
// appends more data to the file, displays the file, and then deletes the file.
// It will not run if the file already exists.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/PHP_Programming

function create_file($filename)
{
    $file = fopen($filename, "w");
    fwrite($file, "C\tF\n");
    for ($c = 0 ; $c <= 50 ; $c += 1) 
    {
        $f = $c * 9.0 / 5 + 32;
        fwrite($file, $c . "\t" . $f . "\n");
    }
    fclose($file);
}

function read_file($filename)
{
    $file = fopen($filename, "r");
    while (!feof($file))
    {
        $line = fgets($file);
        echo $line;
    }
    fclose($file);
    echo "\n";
}

function append_file($filename)
{
    $file = fopen($filename, "a");
    for ($c = 51 ; $c <= 100 ; $c += 1) 
    {
        $f = $c * 9.0 / 5 + 32;
        fwrite($file, $c . "\t" . $f . "\n");
    }
    fclose($file);
}

function delete_file($filename)
{
    unlink($filename);    
}

function main()
{
    $filename = "~file.txt";

    if (file_exists($filename))
    {
        echo "File already exists.";
    }
    else
    {
        create_file($filename);
        read_file($filename);
        append_file($filename);
        read_file($filename);
        delete_file($filename);
    }
}

main();

?>

Try It

[edit | edit source]

Copy and paste the code above into one of the following free online development environments or use your own PHP compiler / interpreter / IDE.

See Also

[edit | edit source]