How to programmatically create new file/folder in Drupal 7 files directory? 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.
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);