Erreur script de vote, setcookie/$_COOKIES

rimolas Messages postés 500 Date d'inscription mercredi 30 novembre 2011 Statut Membre Dernière intervention 18 janvier 2016 - Modifié par f0xi le 1/03/2014 à 17:08
f0xi Messages postés 4205 Date d'inscription samedi 16 octobre 2004 Statut Modérateur Dernière intervention 12 mars 2022 - 1 mars 2014 à 17:08
Bonjour,

J'ai une erreur dans ce code (au niveau de la création du cookie) et je n'arrive pas à la trouver.

Merci de bien vouloir m'aider

Cordialement,

Rimolas.

Si vous avez résolu votre problème, ou si vous avez eu la réponse que vous cherchiez à votre question, n'oubliez pas de mettre votre sujet en tant que "Résolu" Merci

2 réponses

Whismeril Messages postés 19028 Date d'inscription mardi 11 mars 2003 Statut Non membre Dernière intervention 24 avril 2024 656
Modifié par Whismeril le 28/02/2014 à 22:56
Bonjour

merci de poster le code dans la discussion en utilisant les balises de coloration syntaxique, comme décrit ici, et de trouver un titre plus explicite.


Penser aux balises de coloration syntaxique: bouton <>, préciser le langage :<code csharp>.
Quand la solution est trouvée, mettre la discussion Résolue.
0
f0xi Messages postés 4205 Date d'inscription samedi 16 octobre 2004 Statut Modérateur Dernière intervention 12 mars 2022 35
Modifié par f0xi le 1/03/2014 à 17:09
Y'a une grosse erreur de conception dans ton truc, au niveau récupération des GET/POST au niveau du test cookie, de l'utilisation de mysql (obsolete), de l'écriture des requetes, des tests non efféctué sur les paramètres passé au requetes ...

ça m'a amusé un peu et j'ai voulus t'en proposer l'amélioration suivante, attention j'ai tout fait sans test, donc je ne sais pas du tout si cela fonctionne, mais je pense que ça te donnera de quoi réfléchir sur la présentation et la structure de code.
<?php/* hack404.php */

// Logging remote address, request uri and script name
$f = fopen('hack404.log','a');
fwrite($f, sprintf("%s > [%s] calling [%s] on [%s]\n"., 
  date('Y-m-d H:i:s'), $_SERVER['REMOTE_ADDR'], $_SERVER['REQUEST_URI'], $_SERVER['SCRIPT_NAME']);
fclose($f);  

// returning "fake" 404 error. Best for skunk lamers and robots
header('HTTP/1.1 404 Not Found');
echo 
  "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n<html><head>\n<title>404 Not Found</title>\n</head>",
  "<body>\n<h1>Not Found</h1>\n<p>The requested URL ".$_SERVER['REQUEST_URI']." was not found on this server.</p>\n",
  "<hr>\n".$_SERVER['SERVER_SIGNATURE']."\n</body></html>\n";
exit;

/* hack404.php */?>

<?php/* config.php : begin */

  /** NO HACK **/
    // define HaCK (like microtime,date or other value) and 
    // define HaCKey (= md5(HaCK)) in script who require this file
  if(!defined('HaCK') || !defined('HaCKey')) { include 'hack404.php'; }
  if(HaCKey <> md5(HaCK))                    { include 'hack404.php'; }
  /** /NO HACK **/
  
    /* notes :
      DB_HOST     host name for DB connection
      DB_USER     user name of DB connection
      DB_PASW     user password of DB connection
      DB_NAME     working database name
      DB_PREFIX   database's tables prefix
      tblTopsite  table topsite
      *NODB       define NOBD const in a script before include config, $DB was not created
      $DB         MySQLi auto created object  (control with define NODB)
      
      HTRUE       hash value of true for cookie
      HFALSE      hash value of false for cookie
      COOKIE      cookie name
      
      SITE_URL    url of website 
      
      THEME_PATH  path of current theme
    */
    
/* DATABASE */  
  define('DB_HOST', 'localhost');
  define('DB_USER', 'user');
  define('DB_PASW', 'pass');
  define('DB_NAME', 'database');

  define('DB_PREFIX', '');

  define('tblTopsite', DB_PREFIX.'topsite');

  if(!defined('NODB'))
  {
    $DB = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
  }

/* COOKIES NAME & VALUES */
  define('HTRUE',   hash('haval128,3', 'true')); 
  define('HFALSE',  hash('haval128,3', 'false')); 
  define('COOKIE',  hash('tiger160,4', 'topsite'));
  
/* WEBSITE */
  define('SITE_URL', 'www.topsite.com');
  
/* THEMES */
  define('THEME_PATH', 'themes/default/');

/* config.php : end */?>

<?php/* vote.php : begin */

  /** NO HACK **/
  define('HaCK',   microtime(true)); // no fixed value
  define('HaCKey', md5(HaCK));       // depend of HaCK value
  /** /NO HACK **/

// Including configuration  
require_once('config.php');

  /* notes :
     ID         (int)  ID of candidat in database
     CONFIRM    (bool) confirmation of submitting form for vote (if not equal to 1 ... it's an error) 
     VOTED      (bool) user have already voted for ID in last 24 hours
     VOTECPT    (bool) Vote is comptabilized or not (update / cookie success)
     VOTENAME   (html str) Name of ID candidat
  */

// Get value of poste var id & cf
define('ID',      isset($_POST['id']) ? ( preg_match('/^\d{1,11}$/',$_POST['id']) ? (int) $_POST['id'] : 0 ): 0);
define('CONFIRM', isset($_POST['cf']) ? ( preg_match('/^[0|1]{1}$/',$_POST['cf']) ? (bool) $_POST['cf'] : false ) : false);


//If valid ID
if(ID !== 0 && CONFIRM)
{
  // Test cookie and value of
  define('VOTED', isset($_COOKIES[COOKIE][ID]) ? ((bool) $_COOKIES[COOKIE][ID] == HTRUE) : false );
  
  // getting name from id
  $sql = sprintf("SELECT %s FROM '%s' WHERE id=%d LIMIT 1", 'name', tblTopsite, ID);
  
  if($result = $DB->query($sql)){
    if($result->num_rows == 1)
    {
      $row = $result->fetch_assoc();
      // define Name of candidat
      define('VOTENAME', htmlentities( $row['name'] ));
      $result->free();
    }
  }

  // if not already voted and vote confirmed
  if(!VOTED)
  {
    // increment vote value
    $sql = sprintf("UPDATE '%s' SET vote=vote+1 WHERE id=%d LIMIT 1", tblTopsite, ID);
    
    define('VOTECPT', $DB->query($sql));
    
    // and set a cookie on ID if success or not
    setcookie(COOKIE.'['.ID.']', VOTECPT ? HTRUE : HFALSE, time()+3600);
  }
}

// define lost consts.
if(!defined('VOTED')){    define('VOTED',    false); }
if(!defined('VOTENAME')){ define('VOTENAME', null); }
if(!defined('VOTECPT')) { define('VOTECPT',  false); }
?>
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="utf-8"/>
 
  <title>Voter pour "<?php echo VOTENAME; ?>" ?</title>

  <link href="<?php echo THEME_PATH.'/style.css'; ?>" rel="stylesheet"/>
  <style>
  .msg
  {
    display:block;
    clear:both;
    margin:8px 0;
    padding:8px;
    border-radius:3px;
    color:#fff;
    border:1px solid #666;
    background-color:#999;
    text-shadow:1px 1px 1px #666;
  }
  .warning
  {
    background-color:#e70;
    border-color:#b40;
    text-shadow:1px 1px 1px #900;
  }
  .success
  {
    background-color:#8b0;
    border-color:#680;
    text-shadow:1px 1px 1px #680;
  }
  .question
  {
    color:#444;
    background-color:#fff;
    border-color:#fff;
    text-shadow:-1px -1px 1px #ccc;
    font-style:italic;
    font-size:16pt;
  }
  .question:first-letter
  {
    font-weight:bold;
    font-size:200%;
  }
  .button
  {
    cursor:pointer;
    display:inline-block;
    vertical-align:middle;
    padding:0 8px;
    margin:4px 8px;
    height:48px;
    line-height:48px;
    min-width:100px;
    overflow:none;
    border-radius:4px;
    font-weight:bold;
    font-size:14pt;
    color:#fff;
    border:none;
    background: #07c; 
    background: -webkit-linear-gradient( #07c, #049); 
    background: -moz-linear-gradient( #07c, #049); 
    background: -ms-linear-gradient( #07c, #049); 
    background: -o-linear-gradient( #07c, #049); 
    background: linear-gradient( #07c, #049);
    text-shadow: 0px 1px 0px rgba( 0, 0, 0, 0.4);
    box-shadow: 0 0 5px rgba( 0, 0, 0, 0.5), 0 -1px 0 rgba( 255, 255, 255, 0.4);
  }
  .button:hover{
    background: #049; 
    background: -webkit-linear-gradient( #049, #07c); 
    background: -moz-linear-gradient( #049, #07c); 
    background: -ms-linear-gradient( #049, #07c); 
    background: -o-linear-gradient( #049, #07c); 
    background: linear-gradient( #049, #07c);
    text-shadow: 0px -1px 0px rgba( 0, 0, 0, 0.4);
    box-shadow: 1px 1px 10px black inset, 0 1px 0 rgba( 255, 255, 255, 0.4);     
  }
  .btnyes
  {
    background: #9b0; 
    background: -webkit-linear-gradient( #9b0, #680); 
    background: -moz-linear-gradient( #9b0, #680); 
    background: -ms-linear-gradient( #9b0, #680); 
    background: -o-linear-gradient( #9b0, #680); 
    background: linear-gradient( #9b0, #680);
  }
  .btnno
  {
    background: #c00; 
    background: -webkit-linear-gradient( #c00, #900); 
    background: -moz-linear-gradient( #c00, #900); 
    background: -ms-linear-gradient( #c00, #900); 
    background: -o-linear-gradient( #c00, #900); 
    background: linear-gradient( #c00, #900);
  }
  </style>
</head>
<body>
  <!-- HEADER -->
  <div class="header">
    <a href="<?php echo SITE_URL; ?>"><img src="<?php echo THEME_PATH.'/images/logo.png'; ?>" alt="Top site" /></a>
  </div>
  
  <!-- CONTENT -->
  <div class="content">
    <?php
    // If already voted
    if(VOTED)
    { ?>
      <p class="msg warning">Vous ne pouvez voter qu'une fois par heure et par site.</p>
      <?php
    {
    //We check if the user has already voted
    else
    {
      //If the vote has been confirmed
      if(VOTECPT)
      { ?>
        <p class="msg success">Votre vote a été enregistré avec succès.</p>';
        <?php
      }
      //Else we display the form
      else 
      { ?>
        <form action="vote.php" method="post">
          <input type="hidden" name="id" value="<?php echo ID;?>" />
          <input type="hidden" name="cf" value="1" />
          <p class="msg question">
            Êtes-vous sûr de vouloir voter pour "<?php echo VOTENAME; ?>" ?
          </p>
          <p>
            <input type="submit" class="button btnyes" value="Oui" /> 
            <input type="button" class="button btnno" value="Non" onclick="javascript:history.back();" />
          </p>
        </form>
        <?php
      }
    }
    ?>
    </div>
    
    <!-- FOOTER -->
    <div class="footer">
      <a href="<?php echo SITE_URL; ?>">Retour à l'accueil</a>
    </div>
</body>
</html>


________________________________________________________
[ besoin de câbles audio, vidèo, informatique pas cher ?]
0
Rejoignez-nous