有没有替代file_get_contents的方法,可以在文件不存在时创建文件。我基本上是在寻找一行命令。我正在使用它来统计程序的下载统计信息。我在预下载页面中使用这个PHP代码:
然后在下载页面,我有这个。
Download #: <?php $hits = file_get_contents("downloads.txt"); echo $hits; ?>
然后在下载页面,我有这个。
<?php
function countdownload($filename) {
if (file_exists($filename)) {
$count = file_get_contents($filename);
$handle = fopen($filename, "w") or die("can't open file");
$count = $count + 1;
} else {
$handle = fopen($filename, "w") or die("can't open file");
$count = 0;
}
fwrite($handle, $count);
fclose($handle);
}
$DownloadName = 'SRO.exe';
$Version = '1';
$NameVersion = $DownloadName . $Version;
$Cookie = isset($_COOKIE[str_replace('.', '_', $NameVersion)]);
if (!$Cookie) {
countdownload("unqiue_downloads.txt");
countdownload("unique_total_downloads.txt");
} else {
countdownload("downloads.txt");
countdownload("total_download.txt");
}
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$DownloadName.'" />';
?>
自然地,用户首先会访问预下载页面,因此该页面尚未创建。我不想向预下载页面添加任何功能,我希望它简单明了,不要添加或更改太多内容。
编辑:
像这样的东西应该可以工作,但对我来说却没有起作用?
$count = (file_exists($filename))? file_get_contents($filename) : 0; echo $count;
file_get_contents()
将返回一个字符串,因此您应该将其转换为int
以确保。 - MrWhite