Lesson 7: Storing Data
Objectives
- ...
- ...
Storing Data
Your PHP code can access data stored on your server, whether or not that data is directly
accessible to the user. In these examples, we'll be using data stored in files in our
private/ directory, outside of our webroot. On this site,
you've been given access to the private/ directory,
but on a real website you normally wouldn't!
Many websites store their data in a relational database like MySQL, MariaDB, or PostgreSQL. These are a highly-efficient way or storing, searching, and sorting large volumes of data, but have a significant learning curve (and there are lots more things that can "go wrong"). This lesson will only discuss storing data in files.
Counting Clicks
A popular widget is a "clap counter", where users can click on a counter to increment it
and show support for a page. clap.php is a basic example:
<?php
// Define our file name in a constant so it's easy to use in
// multiple places:
define('CLAP_FILE_NAME', '../../private/clap-count.txt');
// A convenience function that returns the current clap count:
function get_claps(){
// Check if the file private/clap-count.txt exists
if( file_exists(CLAP_FILE_NAME) ) {
// It exists! Load the file to get the current value.
// We use intval() to force it to be an integer (number):
$claps = intval(file_get_contents(CLAP_FILE_NAME));
} else {
// It doesn't exist - treat it as being 0:
$claps = 0;
}
return $claps;
}
// Check if the clap button was clicked:
if( $_POST['clap'] ) {
// Get the current clap count:
$claps = get_claps();
// Add one to the claps count:
$claps++;
// Write the new count back to the file:
file_put_contents(CLAP_FILE_NAME, $claps);
// Redirect the user back to the same page to start over:
header( 'Location: ' . $_SERVER['REQUEST_URI'] );
die();
}
// Before we render the page, load the claps count:
$claps = get_claps();
?>
<p>
Clap if you like this page!
</p>
<form method="post">
<button type="submit" name="clap" value="true">
👏<br>
<?php echo $claps; ?>
</button>
</form>
Here's what's going on:
-
We define a function,
get_claps, which returns the current clap count. It does this by loading the number in the fileprivate/clap-count.txt, if it exists (it returns 0 otherwise). - A form is displayed with a button showing the current number of claps. Clicking the button submits the form.
- When the form is submitted, some PHP code loads the current clap count, increments it by one, and then redirects the user back to the same page.
- When the page is reloaded, the new clap count is displayed.
...