Jump to content

File I/O Function


JustinK101

Recommended Posts

I have the following function:

 

function backup_crypto_key($crypto_key) {

	if(file_exists('crypto_key.bak') || empty($crypto_key))
	{
		return -1;
	}

	try {
		$fileObj = fopen('crypto_key.bak', 'w');
		fwrite($fileObja, $crypto_key);
	}
	catch (Exception $e) {
		return $e;	
	}

	@fclose($fileObj);
	return 0;
}

echo backup_crypto_key("123");

 

I broke the code on purpose in the call to fwrite() by passing in an invalid file pointer. I would have expected the catch to happen and output an error, but instead when I execute this code a warning is displayed and 0 is returned. How do I put the file I/O functions in a real try catch and acutally catch errors? Thanks.

Link to comment
https://forums.phpfreaks.com/topic/56908-file-io-function/
Share on other sites

Ok, rewrote the function above to:

 

function backup_crypto_key($crypto_key) {

	if(file_exists('backup/crypto_key.bak') || empty($crypto_key))
	{
		return -1;
	}

	$fileObj = @fopen('backup/crypto_key.bak', 'w');

	if(!$fileObj)
		return -1;

	if(!(@fwrite($fileObj, base64_encode($crypto_key))))
		return -1;

	fclose($fileObj);
	return 0;
}

 

This seems to work now, if either fopen() or fwrite() fail we return -1. I still don't understand why the try catch block didnt work, but whatever.

Link to comment
https://forums.phpfreaks.com/topic/56908-file-io-function/#findComment-281160
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.