如果file_get_contents不存在,会创建该文件吗?我基本上是在找一行命令.我用它来计算程序的下载统计数据.我在预下载页面中使用此PHP代码:
Download #: <?php $hits = file_get_contents("downloads.txt"); echo $hits; ?>
Run Code Online (Sandbox Code Playgroud)
然后在下载页面中,我有这个.
<?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.'" />';
?>
Run Code Online (Sandbox Code Playgroud)
当然,用户首先访问预下载页面,因此尚未创建.我不想在预下载页面添加任何功能,我希望它简单明了,而且不需要添加/更改.
编辑:
这样的东西会起作用,但它对我不起作用?
$count = (file_exists($filename))? file_get_contents($filename) : 0; echo $count;
Run Code Online (Sandbox Code Playgroud)
Ser*_*min 12
Download #: <?php
$hits = '';
$filename = "downloads.txt";
if (file_exists($filename)) {
$hits = file_get_contents($filename);
} else {
file_put_contents($filename, '');
}
echo $hits;
?>
Run Code Online (Sandbox Code Playgroud)
您也可以使用fopen()'w +'模式:
Download #: <?php
$hits = 0;
$filename = "downloads.txt";
$h = fopen($filename,'w+');
if (file_exists($filename)) {
$hits = intval(fread($h, filesize($filename)));
}
fclose($h);
echo $hits;
?>
Run Code Online (Sandbox Code Playgroud)