contatore commenti

giancarlo

Nuovo Utente
9 Feb 2010
3
0
0
Salve, avrei bisogno di un aiuto, non avendo molta esperienza in php purtroppo. Praticamente ho implementato nel mio sito un semplice sistema di commenti, dove tutti i messaggi vengono salvati in un file di testo (messages.txt)

Quello che mi serve ora è un contatore che mi indichi il numero di commenti presenti.

Sapreste aiutarmi?
 
HTML:
nome(il nome di chi scrive il commento)  commento(il testo del commento)	2009/12/31 03:35:26 (data e ora)	95.239.xxx.xxx (indirizzo IP

questo è il contenuto di un commento nel file di testo.

se vuoi posso postare gli script php..
 
script chiamato inc_form.php che fà visualizzare il form per i commenti e memorizza i dati nel file testo.
PHP:
<?
ob_start();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>phpSHOUT from Designanet.co.uk</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="JavaScript">
function addsmiley(symbol) {
  document.postshout.msg.value += symbol;
  document.postshout.msg.focus();
}

<!-- Begin
function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=500,height=500');");
}

</script>
<link href="phpshoutstyle.css" rel="stylesheet" type="text/css">
</head>

<body class="phpshout_body">
<form name="postshout" method="post" action="<? echo $_SERVER['PHP_SELF']; ?>">
<table align="center" class="phpshout_table">
    <tr>
      <td class="phpshout_form"><?
	include "config.php";
	include "functions.php";

	if (isset($_POST["Submit"])) {
		
		// Remove any tabs
		$_POST["name"] = str_replace("\t"," ",$_POST["name"]);
		$_POST["email"] = str_replace("\t"," ",$_POST["email"]);
		$_POST["msg"] = str_replace("\t"," ",$_POST["msg"]);

		// Make name and string lower case for bad language filter
		$_POST["name"] = strtolower(stripslashes(trim(htmlspecialchars($_POST["name"]))));
		$_POST["msg"] = strtolower(stripslashes(trim(htmlspecialchars($_POST["msg"]))));


		if (!file_exists("messages.txt")) {
		
			echo "<p class=\"error\">Messages.txt non esiste. Per favore crea un file chiamato messages.txt sul tuo server</p>";
		
		} else if ($_POST["name"] == "" || $_POST["msg"] == "" || $_POST["name"] == NULL || $_POST["msg"] == NULL) {
	
			echo "<p class=\"error\">Errore. I campi nome e messaggio sono obbligatori</p>";
	
		}  else {
                       echo "<p class=\"conferma\">Il tuo commento &egrave; stato inserito</p>";
		
			$filename = "messages.txt";
			$handle = fopen($filename,"r");
			$read = file_get_contents($filename);
		
			if ($read != "" || $read != NULL) {
					
					$array = explode("\n", $read);

					if ($array[0] != NULL || $array[0] != "") {
				
					list($name, $email, $msg, $time, $ip) = explode("\t", $array[0]);
										
					$ip = trim($ip);
					
					// Convert timestamp to unix timestamp and get current unix timestamp
					$strtime = strtotime($time);
					$flood_gate_time = $strtime+$floodtime;
					$curtime = time();
					$valid = true;
					}
					
					if ($ip == $_SERVER['REMOTE_ADDR'] && $flood_gate_time > $curtime) {
						echo "<p class=\"error\">Devi attendere ".$floodtime." secondi prima di poter postare ancora</p>";
					} else {

					writetofile($_POST["name"],$_POST["email"],$_POST["msg"]);
					
					}
					
			} else {
				writetofile($_POST["name"],$_POST["email"],$_POST["msg"]);
			}
			
		} // end if file exists
		
	} // end submit

?></td>
    </tr>
    
   
	  	<? 

	$filename = "messages.txt";

	if (file_exists($filename)) {
	
	$handle = fopen($filename, "r");
	$read = file_get_contents($filename);
	$array = explode("\n", $read);
	
	for($i=0; $i<$numofposts; $i++) {
		
		if ($array[$i] != NULL || $array[$i] != "") {
		
			list($name, $email, $msg, $date) = explode("\t", $array[$i]);
			
			$date = str_replace(" ","/",$date);
			list($year,$month,$day,$time) = explode("/", $date);
			
			// Show date, Yes or No.
			if ($showdate == "1") {
				$title = "title=\"Postato il ".$day."/".$month."/".$year." alle ".$time."\"";
			} else {
				$title = "";
			}	

			if ($display_email == "1") {
				
				echo "<tr><td ".$title." class=\"phpshout_posts\">Postato da:&nbsp;<strong><a class=\"phpshout_link\" href=\"mailto:$email\">".wordwrap($name,18,"<br>\n",1)."</a></strong>&nbsp;il ".$day."/".$month."/".$year." alle ".$time."<br/><br/>";
				$msg = smiles($msg);
				echo ereg_replace("([^ \/]{22})","\\1<wbr>",$msg)."</td></tr>";
				
			} else if ($display_email == "0") {
				
				echo "<tr><td ".$title." class=\"phpshout_posts\">Postato da:&nbsp;<strong>".wordwrap($name,18,"<br>\n",1)."</strong>&nbsp;il ".$day."/".$month."/".$year." alle ".$time."<br/><br/>";
				$msg = smiles($msg);
				echo ereg_replace("([^ \/]{22})","\\1<wbr>",$msg)."</td></tr>";
				
			} else {
			
				echo "Invalid display e-mail value. Please check your config.php file";
				
			}
			
		} else {
		
		break;
		
		}
	}
	
	fclose($handle);
	
	}
	
?>
// Qui è inserito il form per i commenti, nome, email, invia. 

<?
ob_end_flush();
?>

script functions.php
PHP:
<?

// Write posted data to file
function writetofile($post1,$post2,$post3) {
include "config.php";
								
$msgfilename = "messages.txt";
$curdate = date('Y/m/d H:i:s');
$save = file($msgfilename);
$filename = fopen($msgfilename, "r+");
								
					if ($badlang == "1") {
					
						$badwordsfile = "badlanguage.txt";
						if (file_exists($badwordsfile)) {
		
							$handle = fopen("badlanguage.txt", "r");
	
							while (!feof($handle)) {
		
								$buffer = fgets($handle, 4096);
								$badword = explode(",", $buffer);
		
								$post1 = str_replace($badword, "****", $post1);
								$post3 = str_replace($badword, "****", $post3);
							
							} // End While
				
							fclose($handle);

								fwrite($filename, $post1."\t".$post2."\t".$post3."\t".$curdate."\t".$_SERVER['REMOTE_ADDR']."\r\n");
							
								foreach ($save as $reinsert) {
								fwrite($filename, $reinsert);
								}
							
								fclose($filename);					
										
								if ($savename == "1") {
								setcookie("phpSHOUT_Cookie", $_POST["name"], time()+3600);
								}
								header('Location: '.$_SERVER['HTTP_REFERER'].'');
		
						} // End If file exists
					
					} else if ($badlang == "0") {

								fwrite($filename, $post1."\t".$post2."\t".$post3."\t".$curdate."\t".$_SERVER['REMOTE_ADDR']."\r\n");
							
								foreach ($save as $reinsert) {
								fwrite($filename, $reinsert);
								}
							
								fclose($filename);					
												
								if ($savename == "1") {
									setcookie("phpSHOUT_Cookie", $_POST["name"], time()+3600);
								}
							
								header('Location: '.$_SERVER['HTTP_REFERER'].'');
					
					} else {
			
						echo "Invalid Bad Language Value. Check your config.php file.";
			
					} // End If bad Language

} // End function

// Fill fields if error appears
function fillnamevalues($posted,$defaultval) {
include "config.php";
if (isset($_POST["$posted"])) {
	echo $_POST["$posted"];
} else if (isset($_COOKIE["phpSHOUT_Cookie"]) && $savename=="1") {
	echo $_COOKIE["phpSHOUT_Cookie"];
} else {
	echo $defaultval;
}
}

function filltextvalues($posted,$defaultval) {
if (isset($_POST["$posted"])) {
	echo $_POST["$posted"];
} else {
	echo $defaultval;
}
}

// Convert smilies to images
function smiles($messagetext) {

	include "config.php";

	$sm_search = array(":d",
					   ":)",
					   ":(",
					   ":o",
					   ":shock:",
					   ":-?",
					   "8)",
					   ":lol:",
					   ":x",
					   ":p",
					   ":redface:",
					   ":cry:",
					   ":evil:",
					   ":twisted:",
					   ":roll:",
					   ";)",
					   ":!:",
					   ":?:",
					   ":idea:",
					   ":arrow:"
					   );
	$sm_replace = array("<img src=$imagepath/icon_cheesygrin.gif>",
						"<img src=$imagepath/icon_smile.gif>",
						"<img src=$imagepath/icon_sad.gif>",
						"<img src=$imagepath/icon_surprised.gif>",
						"<img src=$imagepath/icon_eek.gif>",
						"<img src=$imagepath/icon_confused.gif>",
						"<img src=$imagepath/icon_cool.gif>",
						"<img src=$imagepath/icon_lol.gif>",
						"<img src=$imagepath/icon_mad.gif>",
						"<img src=$imagepath/icon_razz.gif>",
						"<img src=$imagepath/icon_redface.gif>",
						"<img src=$imagepath/icon_cry.gif>",
						"<img src=$imagepath/icon_evil.gif>",
						"<img src=$imagepath/icon_twisted.gif>",
						"<img src=$imagepath/icon_rolleyes.gif>",
						"<img src=$imagepath/icon_wink.gif>",
						"<img src=$imagepath/icon_exclaim.gif>",
						"<img src=$imagepath/icon_question.gif>",
						"<img src=$imagepath/icon_idea.gif>",
						"<img src=$imagepath/icon_arrow.gif>"
						);
	$output = str_replace($sm_search, $sm_replace, $messagetext);
	
	return $output; 

	}

// Word wrapping for messages.	
function real_wordwrap($string,$width,$break)
{
   $string = preg_replace('/([^\s]{'.$width.'})/i',"$1$break",$string);
   echo $string;
   return $string;
}
?>
 
Scusate se mi intrometto ... :)

A prescindere del condice è necessari capire quando viene utilizzata l'informazione. SXe il contatore dei commenti è una informazione che viene richiesta e visualizzata raramente puoi, quando occorre, aprire il file e contare le occorrenze (o delle righe giacchè ad ogni riga c'è un commento) o del commento stesso (puoi sfruttare sperataore o keywords se c'è).

Invece, qualora, l'informazione venga consumata spesso è più corretto
modificare il codice affinchè, di volta in volta, ad ogni inserimento di un commento venga incrementato il contatore ed eventualmente salvato su un file\db.

Aggiungo inoltre che ti conviene fare attenzione ad utilizzare file per attività quali storage di commenti ed altro. In quanto grazie ad alcune tecniche, per giunta, diffusa è abbastanza semplice sfruttare le vulnerabilità dell'interprete php per modificarne il contenuto.

Ciao, Ciro
 
Ad ogni buon conto per come è strutturato il database ti basta fare
PHP:
$messaggi = count(file('messages.txt'));
e sai quanti messaggi ci sono nel file.
Concordo quasi su tutto con lotus, tranne su una cosa, è inutile scrivere un secondo file da leggere ogni volta, se tanto devi leggere comunque già un file, equivarrebbe a leggere due file al posto di uno.
Per risolvere in parte quello che dice lotus puoi nascondere il file dietro la root del sito, cioè nella cartella prima di public_html/ se stai su un server linux con su Apache.
Sempre che non stai su Altervista o simili, dove non puoi accedere a quella cartella :)
 

Discussioni simili