4

I tried to create new file/folder programmatically inside Drupal's sites/default/files. But I'm getting this error: "Can't Open file".

Here is what I'm doing: When my registered user visits a certain page, I will be generating a new file and I will provide them with the download link. When I tried to create a new file I am getting "can't open file" message. I'm in localhost in MS Windows.

Are there any other writable folder other than sites/default/files for doing this stuff?

Below is my code:

$ourFileName = base_path()."/sites/default/files/members-pdf/testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);

Above code is written inside a views's template file.

I want to use PHP file API and not Drupal 7 file API.

  • The part base_path()."/sites/default/files/members-pdf/testFile.txt" doesn't seem right, because base_path() will at least return a single slash. Try if base_path()."sites/default/files/members-pdf/testFile.txt" works better. – marcvangend Apr 24 '12 at 20:31
  • 1
    Why do you want to use the PHP file API and not the Drupal file API? The latter is just a set of handy wrappers around the former. – Clive Apr 24 '12 at 21:05
  • For what it's worth: $ourFileName = $_SERVER['DOCUMENT_ROOT'] . '/sites/default/files/members-pdf/testFile.txt'; should work fine assuming your web server can write to that folder, and your Drupal installation is in the web root (not in a sub-folder) – Clive Apr 24 '12 at 21:09
  • @marcvangend thanks it worked for me. I removed the slash and the base_path(). Just "sites/default/files/members-pdf/testfile.txt" worked for me. – krishnan Apr 25 '12 at 2:18
  • @Clive thanks clive. i am about to use TCPDF for creating a pdf file which uses only php file api. And also your solution worked for me. In my case my drupal installation is in subdirectory so i have to add subdirectory name after $_SERVER['DOCUMENT_ROOT']. – krishnan Apr 25 '12 at 2:27
7

To create folders you can use file_prepare_directory and pass FILE_CREATE_DIRECTORY as second parameter like so:

$new_folder = 'public://newfolder/';
file_prepare_directory($new_folder, FILE_CREATE_DIRECTORY);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.