1stPHP

リロード、二重ポスト対策

ソース

header

<?php
define
(LOG "./data/dpost.txt");

function 
counter($up){
  
$fp = @fopen(LOG "r+");
  
flock($fpLOCK_EX);
  
$count fgets($fp);
  if (
$up) {
    
$count++;
    
rewind($fp);
    
fwrite($fp$count);
  }
  
flock($fpLOCK_UN);
  
fclose($fp);
  return 
$count;
}



if (
$_POST['submit']) {
  
counter(true);
  
header("Location: {$_SERVER['PHP_SELF']}");
  exit;
}


print 
'
  <form action="'
.$_SERVER['PHP_SELF'].'" method="post">
  <p>
    <input type="submit" name="submit" value="送信" />
  </p>
  </form>
'
;

$count counter(false);
print 
"<p style=\"font-size:200%\">$count</p>"


?>

cookie

<?php
define
(LOG "./data/dpost.txt");

function 
counter($up){
  
$fp = @fopen(LOG "r+");
  
flock($fpLOCK_EX);
  
$count fgets($fp);
  if (
$up) {
    
$count++;
    
rewind($fp);
    
fwrite($fp$count);
  }
  
flock($fpLOCK_UN);
  
fclose($fp);
  return 
$count;
}


$error false;

if (
$_POST['submit']) {
  if (
$_POST["rand"] == $_COOKIE["sample"]) {
    
//有効期限を設定していない為、ブラウザを閉じた時が有効期限になります
    
setcookie("sample"0);
    
counter(true);
  }else{
    
$error ture;
  }
}else{
  
mt_srand((double)microtime() * 10000000);
  
$rand md5((string)mt_rand());
  
setcookie("sample"$rand);
}


print 
'
  <form action="'
.$_SERVER['PHP_SELF'].'" method="post"> 
  <p>
    <input type="hidden" name="rand" value="'
.$rand.'" />
  <input type="submit" name="submit" value="送信" /> 
  </p>
  </form>
'


$count counter(false); 
print 
"<p style=\"font-size:200%\">$count</p>"

if (
$error) {
  print 
"<p style=\"color:red\">二重送信は出来ません</p>"
}

?>

session

<?php
define
(LOG "./data/dpost.txt");

function 
counter($up){
  
$fp = @fopen(LOG "r+");
  
flock($fpLOCK_EX);
  
$count fgets($fp);
  if (
$up) {
    
$count++;
    
rewind($fp);
    
fwrite($fp$count);
  }
  
flock($fpLOCK_UN);
  
fclose($fp);
  return 
$count;
}


$error false;

if (
$_POST['submit']) {
  
session_start();
  if (
$_POST["rand"] == $_SESSION["sample"]) {
    unset(
$_SESSION["sample"]);
    
counter(true);
  }else{
    
$error ture;
  }
}else{
  
mt_srand((double)microtime() * 10000000);
  
$rand md5((string)mt_rand());
  
session_start();
  
$_SESSION["sample"] = $rand;
}



print 
'
  <form action="'
.$_SERVER['PHP_SELF'].'" method="post"> 
  <p>
    <input type="hidden" name="rand" value="'
.$rand.'" />
  <input type="submit" name="submit" value="送信" /> 
  </p>
  </form>
'


$count counter(false); 
print 
"<p style=\"font-size:200%\">$count</p>"

if (
$error) {
  print 
"<p style=\"color:red\">二重送信は出来ません</p>"
}

?>

サンプル実行

header

クッキー

セッション