Problème d'encodage dans système de commentaire

Petit nouveau ! | 6 Messages

14 août 2011, 18:30

Bonjour à tous,

Alors comme je le dis dans mon titre j'ai un problème d'encodage dans mon système de commentaire... Lorsque je créé un commentaire et que j'insère par exemple : "é,è,à..." et bien ils s'inscrire correctement dans ma base de données mais après ils sont affichés comme celà : "é"

Avez vous une idée de mon problème ?

Voici mon code pour le système de commentaire :

comments.php
<?php
session_start();
// Error reporting:
error_reporting(E_ALL^E_NOTICE);

include "connect.php";
include "comment.class.php";
$idpage=$_REQUEST['idpage'];

/*
/	Select all the comments and populate the $comments array with objects
*/

$comments = array();
$result = mysql_query("SELECT * FROM comments WHERE idpage = '".$idpage."' ORDER BY id ASC");


while($row = mysql_fetch_assoc($result))
{
	$comments[] = new Comment($row);
}



?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>

<body>


<div id="main">

<?php

/*
/	Output the comments one by one:
*/

foreach($comments as $c){
	echo $c->markup();
}

?>


<?php
echo'<div id="addCommentContainer">
	<p>Ajouter un commentaire</p>
	
	<form id="addCommentForm" method="post" action="">
    	<div>
		</br></br>
        	<label for="name">Votre pseudo</label>
        	<input type="text" name="name" id="name" value="'.$_SESSION['pseudo'].'"/>
            
            <label for="email">Votre mail</label>
            <input type="text" name="email" id="email" value="'.$_SESSION['email'].'"/>
            
            <label for="url">Votre site Internet (non requis)</label>
            <input type="text" name="url" id="url" value="'.$_SESSION['url'].'"/>
            
            <label for="body">Votre commentaire</label>
            <textarea name="body" id="body" cols="60" rows="5"></textarea>
            
            <input type="submit" id="submit" value="Envoyer" />
			
			<input type="hidden" name="idpage" value="'.$idpage.'" />
        </div>
    </form>
</div>

</div>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>

</body>
</html>';
?>

Connect.php
<?php

/* Database config */

$db_host		= 'localhost';
$db_user		= 'root';
$db_pass		= '';
$db_database		= 'basketfacile'; 

/* End config */


$link = @mysql_connect($db_host,$db_user,$db_pass) or die('Unable to establish a DB connection');

mysql_query("SET NAMES 'utf8'");
mysql_select_db($db_database,$link);

?>
submit.php
<?php
$idpage=$_REQUEST['idpage'];
// Error reporting:
error_reporting(E_ALL^E_NOTICE);

include "connect.php";
include "comment.class.php";

/*
/	This array is going to be populated with either
/	the data that was sent to the script, or the
/	error messages.
/*/

$arr = array();
$validates = Comment::validate($arr);

if($validates)
{
	/* Everything is OK, insert to database: */
	
	mysql_query("	INSERT INTO comments(name,url,email,body,idpage)

					VALUES (
						'".$arr['name']."',
						'".$arr['url']."',
						'".$arr['email']."',
						'".$arr['body']."',
                        '".$arr['idpage']."'
					)");
	
	$arr['dt'] = date('r',time());
	$arr['id'] = mysql_insert_id();
	
	/*
	/	The data in $arr is escaped for the mysql query,
	/	but we need the unescaped variables, so we apply,
	/	stripslashes to all the elements in the array:
	/*/
	
	$arr = array_map('stripslashes',$arr);
	
	$insertedComment = new Comment($arr);

	/* Outputting the markup of the just-inserted comment: */

	echo json_encode(array('status'=>1,'html'=>$insertedComment->markup()));

}
else
{
	/* Outputtng the error messages */
	echo '{"status":0,"errors":'.json_encode($arr).'}';
}

?>
comment.class.php
<?php
session_start();
$idpage=$_REQUEST['idpage'];
class Comment
{
	private $data = array();
	
	public function __construct($row)
	{
		/*
		/	The constructor
		*/
		
		$this->data = $row;
	}
	

	
	public function markup()
	{
		/*
		/	This method outputs the XHTML markup of the comment
		*/
		
		// Setting up an alias, so we don't have to write $this->data every time:
		$d = &$this->data;
		
		$link_open = '';
		$link_close = '';
		
		if($d['url']){
			
			// If the person has entered a URL when adding a comment,
			// define opening and closing hyperlink tags
			
			$link_open = '<a href="'.$d['url'].'">';
			$link_close =  '</a>';
		}
		
		// Converting the time to a UNIX timestamp:
		$d['dt'] = strtotime($d['dt']);
		
		// Needed for the default gravatar image:
		$url = 'http://'.dirname($_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]).'/img/default_avatar.gif';
		
		return '

		
			<div class="comment">
				<div class="avatar">
					'.$link_open.'
					<img src="http://www.gravatar.com/avatar/'.md5($d['email']).'?size=50&default='.urlencode($url).'" />
					'.$link_close.'
				</div>
				
				<div class="name">'.$link_open.$d['name'].$link_close.'</div>
				<div class="date" title="Added at '.date('H:i \o\n d M Y',$d['dt']).'">'.date('d M Y',$d['dt']).'</div>
				<p>'.$d['body'].'</p>
			</div>
		';

	}
	
	public static function validate(&$arr)
	{
		/*
		/	This method is used to validate the data sent via AJAX.
		/
		/	It return true/false depending on whether the data is valid, and populates
		/	the $arr array passed as a paremter (notice the ampersand above) with
		/	either the valid input data, or the error messages.
		*/
		
		$errors = array();
		$data	= array();
		
		// Using the filter_input function introduced in PHP 5.2.0
		
		if(!($data['email'] = filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)))
		{
			$errors['email'] = '</br></br>Email obligatoire';
		}
		
		if(!($data['url'] = filter_input(INPUT_POST,'url',FILTER_VALIDATE_URL)))
		{
			// If the URL field was not populated with a valid URL,
			// act as if no URL was entered at all:
			
			$url = '';
		}

		
		// Using the filter with a custom callback function:
		
		if(!($data['body'] = filter_input(INPUT_POST,'body',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
		{
			$errors['body'] = '</br></br>Commentaire obligatoire';
		}
		
		if(!($data['name'] = filter_input(INPUT_POST,'name',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
		{
			$errors['name'] = '</br></br>Pseudo obligatoire';
		}
				if(!($data['idpage'] = filter_input(INPUT_POST,'idpage',FILTER_VALIDATE_INT)))
{
	$data['idpage'] = 0;
}
		
		if(!empty($errors)){
			
			// If there are errors, copy the $errors array to $arr:
			
			$arr = $errors;
			return false;
		}
		
		// If the data is valid, sanitize all the data and copy it to $arr:
		
		foreach($data as $k=>$v){
			$arr[$k] = mysql_real_escape_string($v);
		}
		
		// Ensure that the email is lower case:
		
		$arr['email'] = strtolower(trim($arr['email']));
		
		return true;
		
	}

	private static function validate_text($str)
	{
		/*
		/	This method is used internally as a FILTER_CALLBACK
		*/
		
		if(mb_strlen($str,'Latin1')<1)
			return false;
		
		// Encode all html special characters (<, >, ", & .. etc) and convert
		// the new line characters to <br> tags:
		
		$str = nl2br(htmlspecialchars($str));
		
		// Remove the new line characters that are left
		$str = str_replace(array(chr(10),chr(13)),'',$str);
		
		return $str;
	}

}

?>

Avatar du membre
Modérateur PHPfrance
Modérateur PHPfrance | 8758 Messages

14 août 2011, 18:47

salut,

a tu tester faq-tutoriels/encodage-utf-t245062.html ?

sait tu ou cela coince ?
- est ce que dans la table c'est bien en utf8 ?
- est ce que le formulaire est bien en utf-8 ? (les données du formulaire peuvent être en iso (faut forcer le charset dans le formulaire, pour être certain que tu envoie bien des infos utf-8 à la base et non de l'iso (au pire utilise utf8_encode par exemple :) )


@+
Il en faut peu pour être heureux ......

Petit nouveau ! | 6 Messages

14 août 2011, 21:03

Merci des conseils j'ai réussi à faire ce que je voulais.

A plus