How to php an "unsuccessful" message

My php should write a text file to the webhost. I have a ‘success’ page, when the text file is written. Up to now I did not have an ‘unsuccessful’ message.

If, for any reason, the text file cannot be written, I would like to display a message.

From php.net I see:

fwrite() returns the number of bytes written, or FALSE on error.
fopen() Returns a file pointer resource on success, or FALSE on failure

I can’t see how to provoke an fwrite error, but I can provoke an fopen error, by using a nonexistent path. Sure enough , this jumps to my ‘unsuccessful’ message.

$path = "/home/myusername/public_html/nopath/";
$fp = fopen($path . $newname, 'w');
if ($fp === false) {
            header("Location: email_unsuccessful.php");
        }
    else {
        header("Location: email_success.php");}
//endif;
fwrite($fp, $body);
fclose($fp);
?>

Do you see any reason why the same should not work with fwrite??

This way, if fwrite() fails for any reason, the user will get a message and can try to send again.

Why are you trying to induce a failure? And what are you actually trying to do? You don’t induce failures to direct logic.

if(fwrite($fp, $bod) === false)
{
    // failed
}

Just to see if, when fwrite fails, the user gets a message.

So I induced an fopen failure. Then I see my fail message.

I did not have any kind of fail message before.

Of course, my path will not be wrong, fopen will open. But maybe fwrite will fail. So I’d like to have a message, just in case fwrite fails, for any reason.

I prefer this way personally.

$date = new DateTime();
file_put_contents("{$date->format('Y-m-d')}_error_log.txt", "\n[{$date->format('Y-m-d H:i:s')}] " . print_r($data, 1));
1 Like

Put an exit; after the header function to terminate your app. Otherwise it will still continue.

1 Like

Thanks for the tip. Exit should go where?? Call the first line line 1. You mean line 5 and line 8??

$path = "/home/myusername/public_html/nopath/";
$fp = fopen($path . $newname, 'w');
$result = fwrite($fp, $body);
if ($result === false) {
            header("Location: email_unsuccessful.php");
        }
    else {
        header("Location: email_success.php");}
//endif;

// don’t seem to need endif
fclose($fp);
?>

You are using if bass ackwards. if is a truthy check by default so your code should be as follows

if ($result) {
 header("Location: email_success.php");}
die;         
}
 header("Location: email_unsuccessful.php");
die;
       

You are going to want to close the file before you do any headers.

Sponsor our Newsletter | Privacy Policy | Terms of Service