PHP and Creating Directories - php

Quick question. I'll start off with an example.
I have a social site similar to Facebook. When a user signs up my PHP script creates a directory named after his username and a custom sub-directory for this user called "photos".
The "photos" directory is never created when someone signs up. I assume it is because the actual server hasn't created the actual username directory in the first place.
My solution is that anytime i need to execute the photo function on my site for a user I should check if the folder exists and if not create it, which works fine. Is this standard procedure? Or is there a better way to create multiple directories at the same time while running checks.
When someone signs up I run this code, and the latter if statement doesn't successfully create the photos folder, so i check these two statements anytime I am editing something that would go in photos as a check for if the folder exists.
if (!file_exists("user/$username")) {
mkdir("user/$username", 0755);
}
if (!file_exists("user/$username/photos"))
{
mkdir("user/$username/photos", 0755);
}

The directories are created sequentially/synchronously thus once execution of the first mkdir() is finished the folder should be there with the indicated permission set.
As stated here the mkdir()
Returns TRUE on success or FALSE on failure.
and
Emits an E_WARNING level error if the directory already exists.
Emits an E_WARNING level error if the relevant permissions prevent
creating the directory.
So you can go:
if (!file_exists("user/$username")) {
if(mkdir("user/$username", 0755))
{
//directory created
if (!file_exists("user/$u/photos"))
{
mkdir("user/$username/photos", 0755);
}
}
else
{
//directory not created
}
}
If the mkdir() returns false - check the logs or handle the error.

You can do a quick directory 'exists' check like this
function check($images_dir) {
if($handle = opendir($images_dir)) {
// directory exists do your thing
closedir($handle);
} else {
// create directory
}
}
Where $images_dir = path/directory/user/$username

Related

PHP mkdir returns 1 but directory does not exist

I am creating directory in php with mkdir it returns true but when i ssh into my server i cannot find directory in specified path.
I have checked in different locations in server.
if (!file_exists('/tmp/tmpfileeee')) {
mkdir('/tmp/tmpfileeee',0755);
echo 'created';
}
Does tmp exist where this is executing? Is tmpfileee a file or directory you are trying to create? If tmp does not exist and neither does tmpfileee, I believe you are trying to make 2 directories without a recursive parameter in the call.
My PHP is definitely rusty so maybe someone else can answer better but that was just my initial thoughts looking at it.
Just try as that:
if (!file_exists('tmp/tmpfileeee') AND !is_dir('tmp/tmpfileeee')) {
mkdir('tmp/tmpfileeee',0755, true);
echo 'created';
}
mkdir creates a folder not file.
If you want to create an file:
if (!file_exists('tmp/tmpfileeee') AND !is_file('tmp/tmpfileeee')) {
$fp = fopen('tmp/tmpfileeee', 'w');
echo 'created';
}
or best way:
// 1. Check folder and xreate if not exists
if (!file_exists('tmp') AND !is_dir('tmp')) {
mkdir('tmp',0755, true);
echo 'folder created';
}
// 2. Check file and create if not exists
if (!file_exists('tmp/tmpfileeee') AND !is_file('tmp/tmpfileeee')) {
$fp = fopen('tmp/tmpfileeee', 'w');
echo 'file created';
}
UPDATE
On some servers, the tmp and temp folders are restricted.
Check for open_basedir.
PHP manual states:
If the directory specified here is not writable, PHP falls back to the system default temporary directory. If open_basedir is on, then the system default directory must be allowed for an upload to succeed.

Why does my script still try to create my directory?

I am attempting to write a PHP script that organizes uploaded files into directories according to the date they were uploaded. The script needs to detect whether or not the appropriate directories exists before it executes the upload. First, it checks if the folder 'attachments/2014' exists. If it doesn't, it's created. Next, it checks if the folder 'attachments/2014/October" exists. If it doesnt, create it. Finally, it checks if the folder 'attachments/2014/October/29' exists. If it doesnt, it's created. Then the file is uploaded to the last folder.
For some reason, my script always tries to create the directory, even if it already exists. It only works if the directory doesn't exist. Not really sure why about the former. This is CodeIgniter PHP.
$dtree = array(
date('Y'),
date('Y').'/'.date('F'),
date('Y').'/'.date('F').'/'.date('d')
);
$this->load->library('ftp');
$this->ftp->connect();
foreach($dtree as $dir) {
if($this->ftp->list_files('attachments/'.$dir)) === FALSE) {
$this->ftp->mkdir('attachments/'.$dir);
}
}
If the directory exists, I get the CI error saying "Unable to create the directory you have specified."

Silverstripe 3.1 - mkdir() issue bug or local issue?

I seem to get this error on my local server when the site is loaded for the first time e.g. in the morning. Once I do a refresh it's gone...
I'm using silverstripe 3.1.
Is there a way to prevent this locally or is this a bug?
Warning: mkdir(): File exists in /framework/core/manifest/ManifestCache.php on line 19
Looks like line 19 is trying to create a TEMP folder but it already exists...
function __construct($name) {
$this->folder = TEMP_FOLDER.'/'.$name;
if (!is_dir($this->folder)) mkdir($this->folder);
}
Should that function check if the folder exists first e.g.
if (!is_dir($this->folder) || !file_exists($this->folder)) mkdir($this->folder);
Seems that there exists a file with the same name as the directory. That's why is_dir() returns false but mkdir() fails because the file exists.
You can change this to:
if (!file_exists($this->folder)) mkdir($this->folder);
This should work so far.
However it is necessary to mention that such file existence tests are vulnerable against race conditions by design. That's why you need to additionally check the return value of mkdir():
if (!file_exists($this->folder)) {
if(#mkdir($this->folder) === FALSE) {
throw new Exception('failed to create ' . $this->folder);
}
}
This may not being required if you (or the framework) has registered a global error handler which turns warning into exceptions, because mkdir() will throw a warning on errors.

Check if directory is created (Wordpress and/or PHP)

I'm relatively new to PHP and I'm trying to write my own plugin. Upon plugin activation it will run the following function:
function kb_create_uploadfolder () {
global $wpdp;
$upload_dir = wp_upload_dir();
$upload_dir = $upload_dir['basedir'] . "/plugin_uploads";
$upload_dircheck = wp_mkdir_p($upload_dir);
}
I didn't bother to check whether the directory already exists before creating it since I figured it won't overwrite anything or delete the contents if it does. Correct me if I'm wrong.
The thing is however, I would like to check if the creation of the directory was succesful or not but I can't figure out how to get this information.
Use is_dir():
if(is_dir($upload_dircheck))
{
echo "It is a dir";
}
else
{
echo "Sorry, non-existent or not a dir";
}
Also, mkdir() doesn't delete or overwrite existing contents, it just creates a directory if it does not yet exist.
If you're using PHP 4 or newer then you can use the is_dir() function.
Try is_dir().

How to check if a file has access denied and how to give rights(777) to a file in php?

I am working in php on ubuntu. When I use any image on web page which has denied access, there is warning on page. I want to check it before displaying and if it does not have rights to open then give it access to open. As we do in terminal command.
chmod 777 myimage.jpg
How to check this and give full access to a file in php.
Thanks
Check the function is_readable() and is_writable().
Example:
$filename = '/home/myuser/example.txt';
if (is_readable($filename) && is_writable($filename))
{
echo "File has read and write permissions.";
}
Use is_readable() to check whether or not the file is readable by the PHP process.
Use chmod() to change the permissions of the file.
Also, you can use is_writable() to test if you can write to the file, and file_exists() to check to see if the file even exists.
One thing you can do is use the fileowner function (and posix_getpwuid) and compare to whatever your PHP user is (often www-data).
If the users are the same you will be able to change permissions if you need to. But first check if the file is writeable anyway.
UPDATE: the chmod and chown functions return TRUE on success and FALSE on failure, so it would be a good idea to put them in an if clause. You can suppress the error output by setting error_reporting(0); at the beginning of the script, or using the # symbol like this:
if ( #chmod($filename, 0666) ) {
// do whatever with file
}
else if ( #chown($filename, 1000) ) {
chmod($filename, 0666);
// do whatever with file
}
else {
// can't change permissions
}
Doing this on the fly from PHP every time a file is referenced is a very inefficient way to manage your files. It also requires all file access to be mediated via a PHP script. Also, allowing content to be world writeable is rather messy from a security point of view.
I'd go with running an admin script once to tidy up the permissions for your existing files, then fixing the problem when new files enter the system.
Sure, if you've not got shell access / shell access as someone other than the webserver uid, then you'll have to implement this using PHP (and therefore readdir/is_readable/is_writeable).
Without knowing how files appear on your webserver its hard to recommend a specific solution.
C.
One thing you can do to make the file readable / writable is to call this function upon file / folder creation without the second argument:
function AutoChmod($path, $chmod = null)
{
if (file_exists($path) === true)
{
if (is_null($chmod) === true)
{
$chmod = (is_file($path) === true) ? 644 : 755;
if (in_array(get_current_user(), array('apache', 'httpd', 'nobody', 'system', 'webdaemon', 'www', 'www-data')) === true)
{
$chmod += 22;
}
}
return chmod($path, octdec(intval($chmod)));
}
return false;
}
Example:
AutoChmod('/path/to/file/you/just/created.txt');
This function will give appropriate permission whether you are working with SuPHP / SuExecPHP or not.
To check permissions you just need to use the functions is_readable() and is_writable().

Categories