Payne's PHP Notes

Back to Payne's PHP Notebook.

6. Date, Timestamp, and Files

Date:

Source Code Result
echo "Today is " . date("Y-m-d") . "."; Today is 2018-01-23.

Timestamp:

Source Code Result
$timestamp = mktime();
echo $timestamp
1516751079
echo date("G:i:s"); 16:44:39

Include or Require A File:

Example Comment
include "fileName.php"; It generates a warning (E_WARNING) when there is an error.
require "fileName.php"; It generates an error (E_COMPILE_ERROR) and stops the script when there is an error.

Open a File and Close a File:

Syntax / Example Comment
$file=fopen("fileName", "mode"); Mode:
r(read), r+(read/write)
w(write), w+ (read/write)
a(append), a+(read/append)
x(write), x+(read/write)
fclose($file);  

Read a File:

HarryPotter.txt

Type Syntax / Example Result
Line by line $file=fopen("HarryPotter.txt", "r") or exit("Unable to open the file!");

while(!feof($file))
{
    echo fgets($file) . "<br />";
}

fclose($file);
1. Harry Potter and the Sorcerer's Stone.
2. Harry Potter and the Chamber of Secrets.
3. Harry Potter and the Prisoner of Azkaban.
4. Harry Potter and the Goblet of Fire.
5. Harry Potter and the Order of the Phoenix.
6. Harry Potter and the Half-Blood Prince.
7. Harry Potter and the Deathly Hallows.
Character by character $file=fopen("HarryPotter.txt", "r") or exit("Unable to open the file!");

while(!feof($file))
{
    echo fgetc($file);
}

fclose($file);
1. Harry Potter and the Sorcerer's Stone. 2. Harry Potter and the Chamber of Secrets. 3. Harry Potter and the Prisoner of Azkaban. 4. Harry Potter and the Goblet of Fire. 5. Harry Potter and the Order of the Phoenix. 6. Harry Potter and the Half-Blood Prince. 7. Harry Potter and the Deathly Hallows.
No such file $file=fopen("HarryPotter1.txt", "r") or exit("Unable to open the file!");

while(!feof($file))
{
    echo fgetc($file);
}

fclose($file);
Unable to open the file!
// The webpage stops here.

Upload a File:

Syntax / Example Result
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileName" />
<br />
<input type="submit" name="SubmitName" value="SubmitValue" />
</form>
File Name:
<!-- upload.php -->
<html>
<body>

<?php
    echo "<b>File Information</b><br />";
    echo "Name: " . $_FILES["fileName"]["name"] . "<br />";
    echo "Type: " . $_FILES["fileName"]["type"] . "<br />";
    echo "Size: " . ($_FILES["fileName"]["size"] / 1024) . " Kb<br />";
    echo "Temp File: " . $_FILES["fileName"]["tmp_name"] . "<br />";
    echo "Error: " . $_FILES["fileName"]["error"];

    if(file_exists("Test.txt"))
    {
        echo "<br /><br />Test.txt already exists.";
    }
    else
    {
        move_uploaded_file($_FILES["fileName"]["tmp_name"], "Test.txt");
    }
?>
</body>
</html>