Array values print twice, not sure why.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
akimm
Forum Contributor
Posts: 460
Joined: Thu Apr 27, 2006 10:50 am
Location: Ypsilanti Michigan, formally Clipsburgh

Array values print twice, not sure why.

Post by akimm »

This code is meant to take form input, put it into an array, then finally print this array to a file, if yes is selected.
For some reason this code prints the entry twice, when entered. I've tried a few different solutions and am at a loss as to how to fix this. Thanks for any help you can give.

-Sean.

Code: Select all

<?php
// This is the path (relative or full) to your directory of files
$filebin = "entrys";
// Initialize array that will eventually store the files
$files = array();

// This is for compatibility with PHP < 4.3.0
// If your version of php doesn't have file_get_contents
// PHP will use this function instead
if(!function_exists('file_get_contents')){
        function file_get_contents($filename){
                if(file_exists($filename)){
                        $filesize = filesize($filename);
                        $fh = fopen($filename, 'r');
                        $contents = fread($fh, $filesize);
                        fclose($fh);
                        return $contents;
                }
                return false;
        }
}

// Check that the directory supplied in $filebin is, in fact a valid directory
if(is_dir($filebin)){
        // Loop through the directory to find .txt files
        foreach(glob($filebin . '/*.txt') as $file){
                // Store all files found in the $files array with the filenames as keys and the content as values
                $files[$file] = file_get_contents($file);
        }
}
$write = $files[$file];
// This checks to see if the form has been submitted
if(isset($_POST['process']) && $_POST['process'] == 'yes'){
        // If so, loop through the $files array
        foreach($files as $name => $file){
                // Assign all files that were checked "approved" to an array called $keep_files
$keep_files = isset($_POST['keep_files']) ? $_POST['keep_files'] : array();
$fp = fopen('guestbook.txt','a');
			#	if($name) {
  ## this is where I think the error might be.  I am not fully sure.  As I said it prints it twice.        
  if(in_array($name, $keep_files)) {
		fwrite($fp, $file);
		break;
		fclose($fp);
                unlink($name);
                unset($files[$name]);
	}
                // If this particular file is not in the keep_files array, delete it both from the directory and from out $files array
                if(!in_array($name, $keep_files)){
                        unlink($name);
                        unset($files[$name]);
                }
        }
}
// Now display the form
?>
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

Your logic was just a little off You had the file open and close inside of a loop, which was unnecessary and asking for buggy behaviour
Any time you have a situation where you compare in_array and then compare !in_array, use if/else

Code: Select all

if(in_array($name, $keep_files)) {
                fwrite($fp, $file);
                break;
                fclose($fp);
                unlink($name);
                unset($files[$name]);
        }
                // If this particular file is not in the keep_files array, delete it both from the directory and from out $files array
                if(!in_array($name, $keep_files)){
                        unlink($name);
                        unset($files[$name]);
                }
Here... this works.

Code: Select all

<?php
// This is the path (relative or full) to your directory of files
$filebin = "./filebin";
// Initialize array that will eventually store the files
$files = array();

// This is for compatibility with PHP < 4.3.0
// If your version of php doesn't have file_get_contents
// PHP will use this function instead
if(!function_exists('file_get_contents')){
        function file_get_contents($filename){
                if(file_exists($filename)){
                        $filesize = filesize($filename);
                        $fh = fopen($filename, 'r');
                        $contents = fread($fh, $filesize);
                        fclose($fh);
                        return $contents;
                }
                return false;
        }
}

// Check that the directory supplied in $filebin is, in fact a valid directory
if(is_dir($filebin)){
        // Loop through the directory to find .txt files
        foreach(glob($filebin . '/*.txt') as $file){
                // Store all files found in the $files array with the filenames as keys and the content as values
                $files[$file] = file_get_contents($file);
        }
}
// This checks to see if the form has been submitted
if(isset($_POST['process']) && $_POST['process'] == 'yes'){
        // If so, loop through the $files array
		$fp = fopen('guestbook.txt','a');
        foreach($files as $name => $file){
                // Assign all files that were checked "approved" to an array called $keep_files
				$keep_files = isset($_POST['keep_files']) ? $_POST['keep_files'] : array();
                        #       if($name) {
                // If this particular file is not in the keep_files array, delete it both from the directory and from out $files array
                if(in_array($name, $keep_files)){
	                fwrite($fp, $file);
                }
                unlink($name);
                unset($files[$name]);
        }
        fclose($fp);
}
?>
EDIT: OH and I answered all your questions in the last thread, so go take a look if you are still interested in finding out why I did things the way I did. If you have any questions about this fix... please don't hesitate to ask.
User avatar
MrPotatoes
Forum Regular
Posts: 617
Joined: Wed May 24, 2006 6:42 am

Post by MrPotatoes »

dude, way to help out!
User avatar
akimm
Forum Contributor
Posts: 460
Joined: Thu Apr 27, 2006 10:50 am
Location: Ypsilanti Michigan, formally Clipsburgh

Post by akimm »

yes ninja, I just got home from a little get together with my team mates, read your answered questions, Thanks for that. As for the response on here, thanks.
User avatar
akimm
Forum Contributor
Posts: 460
Joined: Thu Apr 27, 2006 10:50 am
Location: Ypsilanti Michigan, formally Clipsburgh

Ninja

Post by akimm »

I can't figure out a problem I'm having with my scripts. Since I added your code to my directory, one of my codes has gone weird. When it writes to the directory entries, it just creates the file, it doesn't actually write anything to it. I am very confused as to why it would do this, if you have any ideas or anyone else, i'd appreciate where my mistake is.

If it wasn't your code, which it probably wasn't, I've added two new functions to my code, which also was around when you gave me that, hence why I make two possibilities, but my two functions were to generate an email list of all the people who wrote to my guestbook, and an ip recorder, so if ever someone is being malicious I can block them.

Thanks for anyone who can find these errors.

Code: Select all

<?php
header("Refresh: 15; url=guestbook.php");
?>  
<?php
$write_string  = "<blockquote>";
$write_string  .= "<table width=" . "75%" . "height=" . "50%" . "cellspacing=" . "2" . ">" . "<tr>";  
$write_string .= "<td width=" . "50%" . ">"; 
$write_string .= "Posted by: " . $_POST['person'];
$write_string  .= "</td>" . "</tr>";  
$write_string .= "<tr>" . "<td width=" . "50%" . "align=" . "left" . ">" . "<a href=" . "mailto:" . $_POST['mail'] . ">";
$write_string .= "<img src=" . "images/mail.gif" . ">" . "</a>" . "</td>";
$write_string .=  "<td width=" . "50%" . "align=" . "left" . ">";
$write_string .= "<a href=" . $_POST['web'] . ">";
$write_string .= "<img src=" . "images/web.gif>" . "</a>" . "</td>" . "</tr>";
$write_string .= "<tr>" . "<td width=" . "75%" . ">" . "<br />" . "Author: " . stripslashes($_POST['message']);
$write_string .=  "</td>";
$write_string .= "</tr>" . "<tr>" . "<td width=" . "75%" . ">";
$write_string .= "Posted on:" . $_POST['date'] . "</td>" . "</tr>" . "</table>" .
$write_string .= "<br>" . "<br>" . $_SERVER['REMOTE_ADDR'] . "</blockquote>";
$fp = fopen( 'entries/' . $_POST['person'] . rand(1, 10) . '.txt', 'a');
if($fp) {
fwrite($fp, $p);
} else {
	die();
}
$fc = fopen('ip.txt','a');
$write_ip = $_SERVER['REMOTE_ADDR'] . "<br>" . "<br>";
if($fc) {
	fwrite($fc, $write_ip);
$fd = fopen('email_list.txt','a');
$write_ip = $_POST['mail'] . "<br>" . "<br>";
if($fc) {
	fwrite($fd, $write_ip);
                   }
              }
#close all files that were written to	
fclose($fd);
fclose($fc);
fclose($fp);
?>
<h1>Entry submitted for review, I will add it in a few days.</h1>
<?php
#echo all posted data
echo "<font color=red>" . "Your name:  " .  $_POST['person'] . "<br>";
echo "<font color=blue>" . "Your email:  " . $_POST['mail'] . "<br>";
echo "<font color=green>" . "Website:  " .$_POST['web'] . "<br>" . "<br>";
echo "<font color=black>" . "Entry:  " .  "<br>" . $_POST['message'] . "<br>";
echo "Date posted: " . $_POST['date'] . "<br>";
echo "<br" . "Your ip is this" . "<br>" . $_SERVER['REMOTE_ADDR'];
?>
<?php echo "<h2>" . "Please wait 15 seconds while the page redirects you back to my guestbook : ), thanks for the post!" . "</h2>";
?>

Also ninja, if you do answer, with your code, for whatever reason now it only prints the file name, I am pretty sure this is due to the file writing error though, since no content is being written to be printed.

Thanks for any help.

Goodbye!
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Let's start with
$write_string = "<blockquote>";
$write_string .= "<table width=" . "75%" . "height=" . "50%" . "cellspacing=" . "2" . ">" . "<tr>";
$write_string .= "<td width=" . "50%" . ">";
$write_string .= "Posted by: " . $_POST['person'];
$write_string .= "</td>" . "</tr>";
$write_string .= "<tr>" . "<td width=" . "50%" . "align=" . "left" . ">" . "<a href=" . "mailto:" . $_POST['mail'] . ">";
$write_string .= "<img src=" . "images/mail.gif" . ">" . "</a>" . "</td>";
$write_string .= "<td width=" . "50%" . "align=" . "left" . ">";
$write_string .= "<a href=" . $_POST['web'] . ">";
$write_string .= "<img src=" . "images/web.gif>" . "</a>" . "</td>" . "</tr>";
$write_string .= "<tr>" . "<td width=" . "75%" . ">" . "<br />" . "Author: " . stripslashes($_POST['message']);
$write_string .= "</td>";
$write_string .= "</tr>" . "<tr>" . "<td width=" . "75%" . ">";
$write_string .= "Posted on:" . $_POST['date'] . "</td>" . "</tr>" . "</table>" .
$write_string .= "<br>" . "<br>" . $_SERVER['REMOTE_ADDR'] . "</blockquote>";
Why e.g. "<table width=" . "75%" ?
why splitting the string literal there? Why not

Code: Select all

$write_string  = '
		<blockquote>
			<table width="75%" height="50%" cellspacing="2" >
				<tr>
					<td width="50%">"Posted by: ' . $_POST['person'] . '</td>
				</tr>
[...]
much easier, more readable.

Do you really want to use the POST data unchecked/unfiltered in your html code?
User avatar
akimm
Forum Contributor
Posts: 460
Joined: Thu Apr 27, 2006 10:50 am
Location: Ypsilanti Michigan, formally Clipsburgh

Post by akimm »

well Volka, I know its not so responsible, but this code is passed to a approval script, which I can then approve or disapprove after.

So for now I just need to get this code working right.
User avatar
akimm
Forum Contributor
Posts: 460
Joined: Thu Apr 27, 2006 10:50 am
Location: Ypsilanti Michigan, formally Clipsburgh

Post by akimm »

I didn't know you could do that, multiple tags in one set of quotes, I always thought it had to be '<tag' . 'output' . '<tag>';

Plus I didn't know you could spread it out like that, I thought the interpreter would encounter an error of whitespaces or something.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

your not doing anything with the variable $write_string
User avatar
akimm
Forum Contributor
Posts: 460
Joined: Thu Apr 27, 2006 10:50 am
Location: Ypsilanti Michigan, formally Clipsburgh

Post by akimm »

Wow, that is one hell of an oversight.

I guess when i rewrote the code to add in ip and email logging i somehow deleted that portion.

Thanks!
Post Reply