Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file_get_contents create file is not exists

Tags:

php

Is there any alternative to file_get_contents that would create the file if it did not exist. I am basically looking for a one line command. I am using it to count download stats for a program. I use this PHP code in the pre-download page:

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

and then in 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 though, the user accesses the pre-download page first, so its not created yet. I do not want to add any functions to the pre download page, i want it to be plain and simple and not alot of adding/changing.

Edit:

Something like this would work, but its not working for me?

$count = (file_exists($filename))? file_get_contents($filename) : 0; echo $count;
like image 309
ParoX Avatar asked Jul 16 '10 14:07

ParoX


1 Answers

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

you can also use fopen() with 'w+' mode:

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;
?>
like image 105
Sergey Eremin Avatar answered Sep 26 '22 01:09

Sergey Eremin