Justin John
Justin John

Reputation: 9616

Error Handling with files in PHP

Error Handling with files in PHP

$path = '/home/test/files/test.csv';
fopen($path, 'w')

Here I want add an error handling by throwing exceptions, on 'No file or directory is found' and 'No permission to create a file'.

I am using Zend Framework.

By using fopen with write mode, I can create a file. But how to handle it when corresponding folder is not there?
i.e if files folder is not present in root structure.

How to throw an exception when no permission is permitted for creating a file?

Upvotes: 0

Views: 415

Answers (4)

Federkun
Federkun

Reputation: 36934

But how to handle it when corresponding folder is not there?

When a folder does not exist .. try to create it!

$dir = dirname($file);
if (!is_dir($dir)) {
    if (false === @mkdir($dir, 0777, true)) {
        throw new \RuntimeException(sprintf('Unable to create the %s directory', $dir));
    }
} elseif (!is_writable($dir)) {
    throw new \RuntimeException(sprintf('Unable to write in the %s directory', $dir));
}

// ... using file_put_contents!

Upvotes: 0

Ben Rowe
Ben Rowe

Reputation: 28711

Something like this should get you started.

function createFile($filePath)
{
  $basePath = dirname($filePath);
  if (!is_dir($basePath)) {
    throw new Exception($basePath.' is an existing directory');
  }
  if (!is_writeable($filePath) {
    throw new Exception('can not write file to '.$filePath);
  }
  touch($filePath);
}

Then to call

try {
  createFile('path/to/file.csv');
} catch(Exception $e) {
  echo $e->getMessage();
}

Upvotes: 3

Blaster
Blaster

Reputation: 9080

Like this:

try
{
  $path = '/home/test/files/test.csv';
  fopen($path, 'w')
}
catch (Exception $e)
{
  echo $e;
}

PHP will echo whatever error would arise there.


Though you can also use is_dir or is_writable functions to see if folder exists and has permission respectively:

is_dir(dirname($path)) or die('folder doesnt exist');
is_writable(dirname($path)) or die('folder doesnt have write permission set');
// your rest of the code here now...

Upvotes: 0

mindandmedia
mindandmedia

Reputation: 6825

I suggest, you take a look at this link: http://www.w3schools.com/php/php_ref_filesystem.asp especially the methods file_exists and is_writable

Upvotes: 0

Related Questions