SakhaliaNetHome PageSahara TerritoryVorKutaAcceptance of cookiesAcceptance of cookies

PHP Tutorial :: Files (I)

PHP Example #99

Reading and printing a local file

This example shows how to read the contents of a text file by using the function file_get_contents() to later print the data. There are certain tags set in the file that are replaced by certain strings by using the function str_replace(). The content in the file is a simple table with a header and a cell. The title of the header is replaced by ":: WELCOME ::", and the user name and login time stored in the session are displayed in the cell, which can have two background colors, depending on the time. Note that the time displayed is related to the server's location timezone.

These examples do not contain code for checking errors that could happen when accessing a file. In professionally-written programs these errors should be generally checked and we will see how this is done in further examples.

<?php
// Sets the data of the session
session_start();
$_SESSION['username'] = 'Alice Malice';
$_SESSION['logintime'] = date('h:i A');
?>

<?php
// Loads the file
$page = file_get_contents('page-template.html');
// Inserts the title of the table
$page = str_replace('{title}', ':: WELCOME ::', $page);
// Sets the color of the cell to be blue or green depending on time
if (date('H' >= 12)) {
$page = str_replace('{color}', 'blue', $page);
} else {
$page = str_replace('{color}', 'green', $page);
}
// Takes the user name and login time from a previously saved session
$page = str_replace('{name}', $_SESSION['username'], $page);
$page = str_replace('{time}', $_SESSION['logintime'], $page);
// Prints the results
print $page;
?>

// Content of the file page-template.html
<table cellpadding="10" border=1">
<thead>
<tr>
<th align="center">
<h1>{title}</h1>
</th>
</tr>
</thead>
<tr>
<td bgcolor="{color}" align="center">
<h2>Hello, {name}</h2>
<p>You have connected at {time}</p>
</td>
</tr>
</table>

:: WELCOME ::

Hello, Alice Malice

You have connected at 06:40 PM

PHP Example #100

Reading and printing a remote file

With file_get_contents() we can retrieve the contents of a remote file as well, by passing as parameter the URL of a certain webpage. This example retrieves the weather forecast for Redmond WA (ZIP 98052) from the website of the US National Weather Service. The program uses the functions strstr(), strpos() and substr() to extract and print only the part of the page that contains the forecast for the next week.

This example does not work in this host because it has the configuration directive allow_url_fopen deactivated. Also have in mind that if the requested webpage changes its structure, even minimally, the program could stop working properly, and would need to be updated.

<?php
$zip = 98052;
$weather_page = file_get_contents('http://www.srh.noaa.gov/zipcity.php?inputstring=' . $zip);
// Finds the first occurrence of "Detailed Forecast" in the webpage
$page = strstr($weather_page, 'Detailed Forecast');
// Finds where it starts the table of the weather forecast
$table_start = strpos($page, '<table>');
// Finds where it ends the table
// It adds 8 characters to pass the closing tag of the table
$table_end = strpos($page, '</table>') + 8;
// Prints the section of $page that contains the table
print substr($page, $table_start, $table_end - $table_start);
?>

PHP Example #101

Writing a file

This example works like the previous one, but takes the contents from one of the webpages of this website, specifically the reference table for the functions strftime() and date(). After the table is extracted and printed on screen, the function file_put_contents() allows to store the data in a file. The content of the table is stored in the variable $output and it is passed to file_put_contents() along with the name of the file to be written.

The function file_put_contents() allows to write files via remote FTP by passing in its first parameter the full URL with username and password on the FTP host where the file has to be saved. For instance:

file_put_contents(ftp://bruce:hax0r@ftp.example.com/usr/local/htdocs/welcome.html, $page);

<?php
$ref_page = file_get_contents('php_ref001.php');
// Finds the table title in the webpage
$page = strstr($ref_page, '<h3>Format characters for strftime() and date()</h3>');
// Finds where it starts the table
$table_start = strpos($page, '<table>');
// Finds where it ends the table
// It adds 8 characters to pass the closing tag of the table
$table_end = strpos($page, '</table>') + 8;
// Gets the section of the page that contains the table
$output = substr($page, $table_start, $table_end - $table_start);
// Prints the table
print $output;
// Saves the table in a file
file_put_contents("php_ref001.txt", $output);
print '<br/>Link to the file: <a href="php_ref001.txt">php_ref001.txt</a>';
?>

Format characters for strftime() and date()



Type strftime() date() Description Range Windows?
Hour %H H Hour, numeric, 24h clock 00-23 Yes
Hour %I h Hour, numeric, 12h clock 01-12 Yes
Hour %K Hour, numeric, 24h clock, initial 0 as space 0-23 No
Hour %l Hour, numeric, 24h clock, initial 0 as space 1-12 No
Hour %p A A.M. or P.M., according to local use Yes
Hour %P a a.m. or p.m., according to local use No
Hour G Hour, numeric, 24h clock, initial 0 suppressed 0-23 No
Hour g Hour, numeric, 12h clock, initial 0 suppressed 0-11 No
Minute %M i Minute, numeric 00-59 Yes
Second %S s Second, numeric 00-61 * Yes
Day %d d Day of the month, numeric 01-31 Yes
Day %e Day of the month, numeric, initial 0 as space 1-31 No
Day %j z Day of the year, numeric 001-366 for strftime(), 001-365 for date() Yes
Day %u Day of the week, numeric, starting by Monday 1-7 No
Day %w w Day of the week, numeric, starting by Sunday 0-6 Yes
Day j Day of the month, numeric, initial 0 suppressed 1-31 No
Day S English sufix for day of the month "st", "nd", "rd", "th" No
Week %a D Name of the week, shortened, according to local use Yes
Week %A l Name of the week, according to local use Yes
Week %U Number of week on the year, numeric, the first Sunday is the first day of the first week 00-53 Yes
Week %V Name of the week on the year, numeric, the first week is the first one that has at least four days in the current year, Monday is the first day of the week 01-53 No
Week %W Name of the week on the year, numeric, the first Monday is the first day of the first week 00-53 Yes
Month %B F Name of the month, according to local use Yes
Month %b M Name of the month, shortened, according to local use Yes
Month %h Name of the month, shortened, according to local use No
Month %m m Month, numeric 01-12 Yes
Month n Month, numeric, initial 0 suppressed 1-12 No
Month t Duration of the month in days, numeric 28-31 No
Year %C Century, numeric 00-99 No
Year %g Four digits year, numeric 00-99 No
Year %G Four digits year with century, numeric 00-99 No
Year %y y Year, numeric 00-99 Yes
Year %Y Y Year with century, numeric Yes
Year L Indication of leap-year 0-1 No
Timezone %z O GMT timezone, +/-HHMM (-1200)-(+1200) Yes, but like %Z
Timezone %Z T Timezone, textual Yes
Timezone I Indication of Daylight Saving Time 0-1 No
Timezone Z Seconds set according to GMT (negative to the west, positive to the east) (-43200)-(+43200) No
Compound %c Standard date-time Yes
Compound %D Same as %m/%d/%y No
Compound %F Same as %Y-%m-%d No
Compound %r Hour as A.M. or P.M. notation, according to local use No
Compound %R Hour as 24 hours notation, according to local use No
Compound %T Hour as 24 hours notation, same as %H:%M:%S No
Compound %x Standard date format, according to local use Yes
Compound %X Standard time format, according to local use Yes
Compound r Date formatted such as "Thu, 21 Dec 2000 16:01:07 +0200" No
Other %s U Seconds since the epoch No
Other B Change to internet date No
Format %% % character as verbatim Yes
Format %n New line character No
Format %t Tabulation character No

Link to the file: php_ref001.txt