colinreedy674 colinreedy674 - 1 month ago 6
PHP Question

Checking the size of a json file

I have google a few examples but none seem to be working, what i'm trying to do:

if(isset($_POST)) {
// json parse
$json = file_get_contents('php://input');
// save the json files for later
// make sure they contain data
if(filesize($json) < 16 && empty(trim(file_get_contents($json))) )
{
$file = 'links-'.rand(10000000,99999999).".txt";
file_put_contents('Links/' . trim($file), $json);
}
}
?>


If the file size is empty, don't create the file, but the above code still does (that is the latest code i have tried), am i missing something obvious here?

Answer

The file_get_contents() function reads the content into a string. Once it's in memory you don't need to try and read it again.

if (isset($_POST)) {
    // populate the json variable   
    $json = file_get_contents('php://input');
    // if the variable is not empty
    // save the content for later
    if (!empty($json))
    {
        $file = 'links-'.rand(10000000,99999999).".txt";
        file_put_contents('Links/' . trim($file), $json);       
    }
}
?>