在php中创建目录,避免777权限

I have a php script that is used to create different directories for different users to store their images. One way to do this is use 777 permision like this:

$path = 'images/product/'.$pid;
if( ! file_exists($path)) {
    $mask=umask(0);
    mkdir($path, 0777);
    umask($mask);
}

Is there any other alternative that doesn't involve to use 777 permision for the directory, for example to set the file owner and group?

Changing the file owner/group requires privileges that your Apache should not have if you want to run it safely. However, you don't necessarily need 0777. I guess you are storing images, so you can use 0644!

Side note: chgrp() and chown() are the 2 functions giving you the ability to change file group/owner