Creating Files With Yii


Does yii have a premade class for creating files? With alle the functions in gii i would guess so, but i’ve googled it and looked for it, but i’ve had no luck. My apologies if theres threds about it allready. In the case that there is no such function, and fwrite is the way to go, what path-request would be the best practice? Ive encounterd some errors trying to use request->baseUrl…

Thanks in advance.

Hi Solid,

No, we usually use fopen, fwrite and fclose for that.

Gii is using file_put_contents in CCodeFile … but it’s only a short cut for consecutive calls of fopen, fwrite and fclose.

Probably you are confusing url with path. Could you show us how you tried to save a file?


Thanks for your quick reply.

I tried this:

$url = Yii::app()->request->baseUrl.'/files/';

$handle = fopen($url.'name.php', 'w');

But that resulted in this error:

fopen(/files/name.php): failed to open stream: No such file or directory

I read that fopen is supposed to create the file when its non-existing. So this error throws me off alittle.

Appriciate the help, Softark!

You have to use the path of the file, not the url, when you want to read or write it.

$webroot = Yii::getPathOfAlias('webroot');

$file =  $webroot . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR . 'name.php';

$handle = fopen($file, 'w');

1 Like

thanks a bunch!