@


PHPˤ륫󥿤ȥեI/O

WebȤˤ륵СɥץȽ󶡤Ǥ롢 Ǥݥԥ顼Ǽڤʵǽ󥿤Ǥ PHPǤ⥫󥿤񤯤ȤǤ PHPˤեI/OΥץȤƤꤴʤΤǡ ǺܤƤߤޤ

<html><head>
<meta http-equiv="Context-Type" content="text/html;charset=euc-jp">
<title>󥿤Υץ</title>
</head>
<body bgcolor="white">
<?
/*
 * 󥿥եɤߡ󥿤1Ŀʤᡢ֤ͤޤ
 * 顼ȯ$errorMessageƤ򥻥åȤ-1֤ޤ
 */
function readCounter($counterFileName, $errorMessage){
    if(file_exists($counterFileName)){
        /* ե뤬¸ߤ */
        if(($fin = fopen($counterFileName, "r")) == FALSE){
            $errorMessage = "ե뤬ץǤޤ$counterFileName";
            return -1;
        }
        /* ɤ߼ꥪץ(ͭå) */
        if(flock($fin, LOCK_SH) == FALSE){
            $errorMessage = "ե뤬åǤޤ$counterFileName";
            return -1;
        }
        $buf = fgets($fin, 256);
        $value = (int) $buf;
        $value++;
        /* å */
        flock($fin, LOCK_UN);
        fclose($fin);
    }
    else{
        /* ե뤬¸ߤʤ */
        $value = 1;
    }
    /* 񤭹ߥץ(¾å) */
    if(($fout = fopen($counterFileName, "w")) == FALSE){
        $errorMessage = "ե뤬ץǤޤ$counterFileName";
        return -1;
    }
    if(flock($fout, LOCK_EX) == FALSE){
        $errorMessage = "ե뤬åǤޤ$counterFileName";
        return -1;
    }
    /* PHPǤϡfputsfwriteƱΤǤ */
    fputs($fout, (string) $value);
    flock($fout, LOCK_UN);
    fclose($fout);
    return $value;
}
?>

<?
$counter = readCounter("counter.dat", &$errorMessage);
if($counter == -1){
    print "顼$errorMessage<br>";
}
else{
    print "褦ʤ" . (string) $counter .
           "ܤΤͤǤ<br>";
}
?>
</body></html>

եI/O˴ؤPHPȤ߹ߴؿ̾ ȤϣøΤˤ褯Ƥޤ fopenfclosefgetsfputsλȤϣø줫ưפ䤬Ǥ礦 fopen˼ԤͤNULL˥ƥFALSE֤ޤ ޤfwritefputsPHPǤƱΤǤ
¾˴ĤݥȤ򡣤ޤե뤬¸ߤ뤫Ĵ٤ˤ file_existsؿȤޤ is_fileϥե뤬¸ߤʤȥ顼ȯΤǡ ŪΤˤϻȤޤ
ʣ饤ȤƱ񤭹ߤˤäƥե뤬˲Τɤˡ WebץꥱǤɬθʤƤϤʤΤեΥå(¾) ǤPerlʤɤȤäCGIǤϡ ߡΥե󥯤뤳ȤǥåԤΤŪǤ PHPǤPOSIXɸOS٥ΥåȤ߹ߴؿ flockѤǤ褦ˤʤäƤޤ ǽΰåեϥɥ롢ΰǡ

  • LOCK_SH(ͭåɤ߹ߥץΤȤϰ̤ˤ)
  • LOCK_EX(¾å񤭹ߥץΤȤϰ̤ˤ)
  • LOCK_UN(å)
Ӥޤ

ʤ1read¾ˡեΤfreadؿɤˡȤޤ ץϼΤ褦ˤʤޤ

$filename = "/the/path/of/contents.txt";
$fd = fopen ($filename, "r");
if(! $fd){ die("Error!"); }
$contents = fread ($fd, filesize ($filename));
fclose ($fd);

Open Source Web Architecture Top

(first uploaded 2001/12/24 last updated 2002/11/08, MISUMI URANO)

e[NȂECir Yahoo yV LINEf[^[Ōz500~`I
z[y[W ̃NWbgJ[h COiq@COsیI COze