PHP create folder if it does not exist

前端 未结 4 707
无人及你
无人及你 2021-01-19 18:31

I am creating a medium size application.

This application consists of a lot of products.

Now these products have many images (one product can have 5 - 6 imag

4条回答
  •  终归单人心
    2021-01-19 18:51

    [I] know that this means that i am missing permission to the folder.

    Actually no =). The error message reads:

    failed to open stream: No such file or directory

    Which makes no reference to permissions the problrm is: the containing-folder you're trying to write to doesn't exist.

    Does this automatically create a new folder if it doesn't already exist?

    No.

    How can i give permission to a newly created folder?

    It's not necessary to do so - anything created will have the correct permissions to permit the webserver user to read the files. However first it's necessary to try and create a folder, which in the question isn't the case.

    Using CakePHP, the Folder class can be used to do that:

    App::uses('Folder', 'Utility');
    $dir = new Folder('/path/to/folder', 2);
    

    The second parameter is used to create a new folder if it doesn't exist. In the context of the question that means the code would look something like this:

    function whatever() {
    
        if ($this->request->data) {
            ...
            
            $unused = new Folder(APP.'product_images/'.$product_id, true);
            if (move_uploaded_file($file, APP.'product_images/'.$product_id.'/'.$image['name'])) {
                ...
            } else {
                ...
            }
        }
    }
    

    The folder APP/product_images should already exist, and must have permissions such that the webserver user (e.g. apache) can write to it otherwise it will not be possible to create the sub-folders/upload files. Assuming APP/product_images exists and the webserver user has permissions to write to it, there is no need to modify permissions of uploaded files - files created by a user are by default readable by that user.

提交回复
热议问题