File_get_contents create file does not exist

Is there an alternative to file_get_contents that will create a file if it does not exist. I am basically looking for one team. I use it to calculate download statistics for a program. I use this PHP code on the preload page:

Download #: <?php $hits = file_get_contents("downloads.txt"); echo $hits; ?>

and then on the download page I have this.

<?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.'" />';
?>

Naturally, the user first accesses the preload page, so it has not yet been created. I do not want to add any functions to the preload page, I want it to be simple and simple and not add / not change.

Edit:

Something like this will work, but it does not work for me?

$count = (file_exists($filename))? file_get_contents($filename) : 0; echo $count;
+3
source share
3 answers
Download #: <?php
$hits = '';
$filename = "downloads.txt";
if (file_exists($filename)) {
    $hits = file_get_contents($filename);
} else {
    file_put_contents($filename, '');
}
echo $hits;
?>

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;
?>
+10

, , . , 0 .

:

$f = file_get_contents('file.php');
$f = $f + 0;
echo is_int($f); //will return 1 for true

, -, . . "download_count" , - . , " download_count $randomValue" - , . , . - . , , . " ", count . . - , , , , , . PHP jQuery Ajax, , .

php jquery.load(file.php), . , . file.php $_GET, , . , , , , . , div , "downloadcount", div , . file.php div # download_count , div. php jquery Ajax/data. jquery, , .

+2

countdownload:

function countdownload($filename) {

    if (file_exists($filename)) {

        file_put_contents($filename, 0);

    } else {

        file_put_contents($filename, file_get_contents($filename) + 1);
    }
}
0

Source: https://habr.com/ru/post/1755001/


All Articles