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?
 

giancarlo

Nuovo Utente
9 Feb 2010
3
0
0
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..
 

giancarlo

Nuovo Utente
9 Feb 2010
3
0
0
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;
}
?>
 

lotus

Utente Attivo
5 Mag 2009
543
8
0
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
 

MarcoGrazia

Utente Attivo
15 Dic 2009
852
20
28
62
Udine
www.stilisticamente.com
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
Autore Titolo Forum Risposte Data
T contatore totale click e media in secondi PHP 7
T Contatore alla rovescia su più elementi simultaneamente Javascript 4
L [PHP] contatore con sqlite PHP 9
T [PHP] [Javascript] Download e contatore PHP 3
bubino8 [PHP] Contatore Scan QR con redirect PHP 10
F Creare un contatore numerico in HTML HTML e CSS 9
M [PHP] Contatore Tempo Server-side PHP 8
M [PHP] contatore record PHP 7
J contatore visualizzazioni video HTML e CSS 1
Monital Contatore sul sito Google Analytics 2
R Contatore alla rovescia per adesioni Supporto Mr.Webmaster 0
Marco_88 Limitare un contatore PHP 1
W Contatore posti in un form, come implementarlo? WordPress 0
Marco_88 Contatore di accessi PHP 5
I contatore caratteri textarea sbagliato Javascript 1
D Record disconesso contatore dove sbaglio? Classic ASP 0
V [risolto] Contatore caratteri stile SMS da una textarea Javascript 6
Alessandro Le Mura Contatore di click su link con redirect ogni 24 ore PHP 4
Alessandro Le Mura [RISOLTO]Contatore di click su link con redirect PHP 5
Alessandro Le Mura Contatore visite per ogni pagina con MYSQL - PHP PHP 40
Alessandro Le Mura Contatore php - txt PHP 8
8 Script per il contatore download PHP 11
L Inserire campo input dinamico con contatore in jquery jQuery 8
A contatore visite PHP 6
Shyson richiamare contatore PHP 5
GoshMaledetto Contatore numero letture PHP 4
C Iframe e contatore visite HTML e CSS 4
Shyson Contatore post non si aggiorna in automatico PHP 7
S Contatore click su link PHP 1
C contatore alfanumerico 0000 -> ZZZZ, idee? PHP 3
F contatore PHP PHP 12
max_400 Contatore Top Forum PHP 17
B contatore di download PHP 1
max_400 Contatore scaricamento file... semplice semplice by max_400 PHP 8
davide1982 Incremento contatore click PHP 14
C Contatore visite su Facebook (era: quesito) PHP 2
davide1982 Problema di redirect dal contatore di click Database 1
T Memberarea, forum, contatore...Mi chiarite le idee? HTML e CSS 7
A Contatore per code di clienti in attesa Flash 0
R Creare un contatore visite senza mysql PHP 6
I contatore crediti a 8574 Supporto Mr.Webmaster 3
foki {PHP Script} Contatore Utenti Registrati PHP 17
danlupo Problemi visualizzazione Contatore PHP 2
danlupo Problema Contatore Accessi PHP 3
whirl Contatore condiviso tra 2 siti PHP 3
Z Contatore fotogallery: problemi a caricare onload laprima PHP 1
A Problema Contatore PHP 6
M Incrementare contatore da flash Flash 12
SolidSnake4 contatore visite PHP 4
SolidSnake4 contatore visite PHP 2

Discussioni simili