Jump to content

reading and writing to php file


helpmehelpmehelpme

Recommended Posts

i have this script where the user enters their name and their favorite quotes.  It adds their favorite quotes and their names to quotes.txt and prints out their name and their quotes on view_quote.php.  I need to use a foreach() loop to print out the name and the quotes, but I'm confused about how to set it up. Here's my files.

add_quote.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Add A Quotation</title>
</head>
<body>
<?php // add_quote.php
/* This script displays and handles an HTML form. This script takes text input and stores it in a text file. */

// Identify the file to use:
$file = 'quotes.txt';

// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Handle the form.

if ( !empty($_POST['quote']) && ($_POST['quote'] != 'Enter your quotation here.'
	 ) ){ // Need some thing to write.

	if (is_writable($file)) { // Confirm that the file is writable.

		file_put_contents($file, $_POST['quote'] . PHP_EOL, FILE_APPEND | LOCK_EX); // Write the data.
		file_put_contents($file, $_POST['name'] . PHP_EOL, FILE_APPEND | LOCK_EX);
		// Print a message:
		print '<p>Your quotation has been stored.</p>';

	} else { // Could not open the file.
		print '<p style="color: red;">Your quotation could not be stored due to a system error.</p>';
	}

} else { // Failed to enter a quotation.
	print '<p style="color: red;">Please enter a quotation!</p>';
}

} // End of submitted IF.

// Leave PHP and display the form:
?>

<form action="add_quote.php" method="post">
<p>Name:<input type="text" name="name"/><br />
<textarea name="quote" rows="5" cols="30">Enter your quotation here.</textarea><br />
<input type="submit" name="submit" value="Add This Quote!" />
</form>

</body>
</html>

view_quote.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>View A Quotation</title>
</head>
<body>
<h1>View My Quotes</h1>
<?php // view_quote.php
/* This script displays and handles an HTML form. This script reads in a file and prints a random line from it. */

// Read the file's contents into an array:
$data = file('quotes.txt');

// Count the number of items in the array:
$n = count($data);

// Pick a random item:
$rand = rand(0, ($n - 1));

// Print the quotation:
print '<p>' . trim($data[$rand]) . '</p>';


?>
</body>
</html>

and the quotes.txt file is blank until the user enters their names and quotes.  Im trying to get this done kind of quick so any help would be awesome.

 

 

Link to comment
Share on other sites

The best way to do this would be saving to a database to retrieve the information easily in many ways.

 

But try out this example using a single file and flat file as you did.

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Add A Quotation</title>
<style type="text/css">
p.text {
font-family: cursive;
font-style: normal;
font-variant: normal;
font-weight: normal;
font-size: medium;
line-height: 1em;
word-spacing: 1ex;
letter-spacing: normal;
text-decoration: none;
text-transform: capitalize;
text-align: left;
text-indent: 0ex;
}
</style>
</head>
<body>
<?php // add_quote.php
/* This script displays and handles an HTML form. This script takes text input and stores it in a text file. */
$quote = $_POST['quote'];
$name = $_POST['name'];
// Identify the file to use:
$file = 'quotes.txt';
if($_POST['name'] == ""){
$name = "anonymous";
}


// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Handle the form.

if ( !empty($_POST['quote']) && ($_POST['quote'] != 'Enter your quotation here.'
	 ) ){ // Need some thing to write.

	if (is_writable($file)) { // Confirm that the file is writable.

		//add a new line to end of file
           $write = fopen($file, 'a+');
           $message = "$quote|$name\r\n";
           fputs($write, $message);
           fclose($write);
		// Print a message:
		print '<p>Your quotation has been stored.</p>';

	} else { // Could not open the file.
		print '<p style="color: red;">Your quotation could not be stored due to a system error.</p>';
	}

} else { // Failed to enter a quotation.
	print '<p style="color: red;">Please enter a quotation!</p>';
}

} // End of submitted IF.

// Leave PHP and display the form:
?>

<form action="" method="post">
<p>Name:<input type="text" name="name"/><br />
<textarea name="quote" rows="5" cols="30">Enter your quotation here.</textarea><br />
<input type="submit" name="submit" value="Add This Quote!" />
</form>

<?php
if (file_exists($file)) {
$data = array();
$data = file($file);
$data = array_reverse($data);
$total = count($data);
echo "<br />Total quotes: $total<br />";
foreach ($data as $line) {
$line = trim($line);
$explode_line = explode("|", $line);
$show_quote = $explode_line[0];
$show_name = $explode_line[1];
echo "<p class='text'>$show_quote</p>  $show_name";
}
}
?>

</body>
</html>

 

and the quotes.txt file are saved in this format, seperated by a pipe |

 

feel the heat|anonymous

Smart programmers make computers not be dumb|Quick

amazing things happen to amazing people|mister amazing

Link to comment
Share on other sites

I had some free time, so decided to add some more to this.

placeholders for form and center it

moved messages lower

creation of text file

show all quotes or from just a certain author

linked author from each quote

list all authors

paginated results

 

all you need is this one script and to name it for use, and some style

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Add A Quotation</title>
<style type="text/css">
p.text {
font-family: cursive;
font-style: normal;
font-variant: normal;
font-weight: normal;
font-size: medium;
line-height: 1em;
word-spacing: 1ex;
letter-spacing: normal;
text-decoration: none;
text-transform: capitalize;
text-align: left;
text-indent: 0ex;
}
</style>
</head>
<body>
<?php

$quote = htmlentities(strip_tags(trim($_POST['quote'])), ENT_QUOTES);
$name = htmlentities(strip_tags(trim($_POST['name'])), ENT_QUOTES);

// Identify the file to use:
$file = 'quotes.txt';//name your text file to save the info
//if file does not exist create it
if(!file_exists($file)){
fopen($file, 'w') or die("can't open file");
}

//pagination and display function
function paginate($display, $pg, $total) {
  /* make sure pagination doesn't interfere with other query 
string variables */
  if(isset($_SERVER['QUERY_STRING']) && trim(
    $_SERVER['QUERY_STRING']) != '') {
    if(stristr($_SERVER['QUERY_STRING'], 'pg='))
      $query_str = '?'.preg_replace('/pg=\d+/', 'pg=', 
        $_SERVER['QUERY_STRING']);
    else
      $query_str = '?'.$_SERVER['QUERY_STRING'].'&pg=';
  } else
    $query_str = '?pg=';
    
  /* find out how many pages we have */
  $pages = ($total <= $display) ? 1 : ceil($total / $display);
    
  /* create the links */
  $first = '<a href="'.$_SERVER['PHP_SELF'].$query_str.'1">&#38;#171;
</a>';
  $prev = '<a href="'.$_SERVER['PHP_SELF'].$query_str.($pg - 1).'">
&#38;#139;</a>';
  $next = '<a href="'.$_SERVER['PHP_SELF'].$query_str.($pg + 1).'">
&#38;#155;</a>';
  $last = '<a href="'.$_SERVER['PHP_SELF'].$query_str.$pages.'">
&#38;#187;</a>';
   
  /* display opening navigation */
  echo '<div><p align="center">';
  echo ($pg > 1) ? "$first : $prev :" : '&#38;#171; : &#38;#139; :';
  
  /* limit the number of page links displayed */
  $begin = $pg - 4;
  while($begin < 1)
    $begin++;
  $end = $pg + 4;
  while($end > $pages)
    $end--;
  for($i=$begin; $i<=$end; $i++)
    echo ($i == $pg) ? ' ['.$i.'] ' : ' <a href="'.
      $_SERVER['PHP_SELF'].$query_str.$i.'">'.$i.'</a> ';
    
  /* display ending navigation */
  echo ($pg < $pages) ? ": $next : $last" : ': &#38;#155; : &#38;#187;';
  echo '</p></div>';
}

/* set pagination variables */
$display = 10;
$pg = (isset($_REQUEST['pg']) && ctype_digit($_REQUEST['pg'])) ?
  $_REQUEST['pg'] : 1;
$start = $display * $pg - $display;

//if no name inserted use anonymous as name
if(!isset($_POST['name']) || $name == ""){
$name = "anonymous";
}

// Check for a form submission:
if($_SERVER['REQUEST_METHOD'] == 'POST') { //perform actions only if was POST from form

if(!empty($_POST['quote'])) { //continue to write to file if contains data

	if(is_writable($file)) { // Confirm that the file is writable.

		//add a new quote to end of file
           $write = fopen($file, 'a+');
           $message = "$quote|$name\r\n";
           fputs($write, $message);
           fclose($write);
		//show any messages
		//quote stored
		$message = '<p style="color: green;">Your quotation has been stored.</p>';

	} else { //Could not open the file.
		$message = '<p style="color: red;">Your quotation could not be stored due to a system error.</p>';
	}

} else { // Failed to enter a quotation.
	$message = '<p style="color: red;">Please enter a quotation!</p>';
}

} // End of submitted IF.

//end of inserting quote
?>

<h1>Write a quote</h1>

<div align="center">
<form action="" method="post">
<input type="text" name="name"placeholder="Your name" /><br />
<textarea name="quote" rows="5" cols="30" placeholder="Enter your quote here."></textarea><br />
<input type="submit" name="submit" value="Add This Quote!" />
</form>

<?php
//start of display

//show message if exists
if($message){
echo $message;
}
?>
</div>

<?php
//get author name from address bar
$author = trim($_GET['author']);

//if file does exist, retrieve the data from it
if (file_exists($file)) {
$data = array();//define array
$show_line = array();//define array
$data = file($file);//array for each line in file
$data = array_reverse($data);//reverse the display order

//loop through the results and explode quotes and authors
foreach ($data as $line) {
$author_name = end(explode("|",$line));//explode author from line for matching author content
$authors[] = $author_name;//create array of all authors

//to see just one authors quotes
if(isset($_GET['author']) && $_GET['author'] != ""){
$author = $_GET['author'];
if(preg_match("/$author/i", $author_name)){
$show_line[] = trim($line);
}
} else {
$show_line[] = trim($line);//otherwise show all quotes
}
}

//link to show all authors, same as main page
echo "<a href='index.php'> All Authors </a>";
$authors = array_unique($authors);//remove duplicate authors for links
asort($authors);//sort ascendinding order
//loop all the author links
foreach($authors as $show_author){
echo "<a href='?author=$show_author'> $show_author </a> ";
}

//count displayed quotes
$total = count($show_line);
echo "<br />Total quotes: $total<br />";

//slice results array for pagination
$show = array_slice($show_line, $start, $display);
//show page navigation
paginate($display, $pg, $total);
//loop results paginated
foreach ($show as $show_info) {
$explode_info = explode("|", $show_info);
$show_quote = stripslashes(html_entity_decode($explode_info[0]));
$show_name = stripslashes(html_entity_decode($explode_info[1]));
echo "<p class='text'>$show_quote</p>  <a href='?author=$show_name'>$show_name</a>";
}
//show page navigation
paginate($display, $pg, $total);
}

?>

</body>
</html>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.