Zack Tanner
Zack Tanner

Reputation: 2590

Using fopen and fwrite with Zend Framework?

I'm attempting to check for file existence with Zend Framework and, if the file doesn't exist, have it be created. Here's the code being used:

$filename = "/assessmentsFile/rubrics/$rubricID.php";
$somecontent = "test";

if (!$handle = fopen($filename, 'w+')) {
    echo "Cannot open file ($filename)";
    exit;
}

// Write $somecontent to our opened file.
if (fwrite($handle, $somecontent) === false) {
   echo "Cannot write to file ($filename)";
   exit;
}

However, I assume due to Zend's way of handling file structure, if a file doesn't exist it just spits out:

Warning: fopen(/assessmentsFile/rubrics/1.php) [function.fopen]: failed to open stream: No such file or directory

Because the fopen function isn't working, fwrite is unable to write the file.

Is there another way of doing this?

Upvotes: 1

Views: 5642

Answers (2)

drew010
drew010

Reputation: 69957

Most likely the issue is with the path to $filename.

You have

$filename = "/assessmentsFile/rubrics/$rubricID.php";

which tries to create a file in the root of the server in a directory called assessmentsFile.

Most likely you need to be using:

$filename = $_SERVER['DOCUMENT_ROOT'] . "/assessmentsFile/rubrics/$rubricID.php";

$_SERVER['DOCUMENT_ROOT'] should do the trick if the assessmentsFile folder is in your web root. Otherwise there are other variables you can use to get a fully qualified path, or you can simply hard-code the path:

$filename = "/home/yoursite/public_html/assessmentsFile/rubrics/$rubricID.php";

Upvotes: 2

Lord Spectre
Lord Spectre

Reputation: 781

There's a function file_exists that tells you if the file exists, and with is_file you can check it's a file (and not a directory for example).

(Another way is to suppress warnings by putting an @ before the function call (e.g. $handle=@fopen(...), but it's better to check for file existence)

Try this:

if(is_file($filename)){ // exists
  $handle=fopen($filename,"w+");
}else{
  $handle=fopen($filename,"w"); // create it
}
// ...

Upvotes: 1

Related Questions