简体   繁体   中英

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?

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";

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 (eg $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
}
// ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM