phpwebelgg

What is wrong with my 'Save File' php code?


The question is simple but i will give some background information to hopefully make answering it easier.

So, I am working with the ELGG framework and taking information from a form and the text boxes in it in hopes to print that data to a simple text file.

Unfortunately, for some reason this has been giving me lots of trouble and I cannot seem to figure out why no matter where I look.

Code is as followed

    <?php

error_reporting(E_ALL);
//Get the page
$title = get_input('title');
$body = get_input('body');
$date = date("l jS  F Y h:i A");

//remove any possible bad text characters


$FileName = $title . ' ' . $date;
//print to file
//get filename and location to save
$folderName =  '/Reports/' . $FileName . '.txt';
$ReportContent = "| " . $body . " |";

//write to the file
file_put_contents($folderName, $ReportContent, 0);

//error check to see if the file now exists
if (file_put_contents($folderName, $ReportContent)) {
    system_message("Report Created (" . basename($folderName) . ")");
    forward(REFERER);
} else {
    register_error("Report (" . basename($folderName) . ") was not saved!");
    forward(REFERER);
}

So what above SHOULD do is grab the text from the title and body box (which i can confirm it does from the title at least) and then save it under the /reports/ folder (full path for the plugin is Automated_script_view/reports/ if needed). Yet I will always get the register error, and I cannot seem to find why.

I believe it has to do with the declaration of the folder (/reports/), as if I take that part away, it passes and submits, although it doesn't seem to actually save anywhere.

Any and all advice would be very much appreciated!


Solution

  • The Function file_put_contents(file,data,mode,context) returns the number of character written into the file on success, or FALSE on failure. Note the following corrections and your script will work just fine:

    1 Your File name has an 'illegal' character ":" coming from the $date part of the string you concatenate to form the filename.

    2 Remove file_put_contents($folderName, $ReportContent, 0); Since the function returns an integer, simple use:

    if( file_put_contents($folderName, $ReportContent) > 0 ){
    //true
     }else{
    //false
    }