Create directory based on current date - php

At the moment I have a directory called showcase in my root folder. When uploading a file, I want to check if a directory exists and if not, create it based on the current date, and then move the file to that folder.
$dateYear = date('Y');
$dateMonth = date('M');
$dateDay = date('d');
if (!is_dir("/showcase/$dateYear/$dateMonth/$dateDay")) {
mkdir("/showcase/$dateYear/$dateMonth/$dateDay");
}
if (move_uploaded_file($fileTmpLoc,"/showcase/$dateYear/$dateMonth/$dateDay/$newName")){
// stuff
}
$newName is the file's name, e.g. SajdaT.jpg. This code doesn't do anything for me. How can I create something that does what I want?
e.g.
/showcase/2015/09/02 create if it doesn't exist, then move a file to it like
/showcase/2015/09/02/SajdaT.jpg

Pass recursive attribute as true with the method.
<?php
// Desired folder structure
$structure = './dir1/dir2/dir3/';
// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.
if (!mkdir($structure, 0777, true)) {
die('Failed to create folders...');
}
// ...
?>

Related

php mkdir folder tree from array

I'm trying to create a folder tree from an array, taken from a string.
$folders = str_split(564);
564 can actually be any number. The goal is to create a folder structure like /5/6/4
I've managed to create all folders in a single location, using code inspired from another thread -
for ($i=0;$i<count($folders);$i++) {
for ($j=0;$j<count($folders[$i]);$j++) {
$path .= $folders[$i][$j] . "/";
mkdir("$path");
}
unset($path);
}
but this way I get all folders in the same containing path.
Furthermore, how can I create these folders in a specific location on disk? Not that familiar with advanced php, sorry :(
Thank you.
This is pretty simple.
Do a for each loop through the folder array and create a string which appends on each loop the next sub-folder:
<?php
$folders = str_split(564);
$pathToCreateFolder = '';
foreach($folders as $folder) {
$pathToCreateFolder .= DIRECTORY_SEPARATOR . $folder;
mkdir($folder);
}
You may also add the base path, where the folders should be created to initial $pathToCreateFolder.
Here you'll find a demo: http://codepad.org/aUerytTd
Or you do it as Michael mentioned in comments, with just one line:
mkdir(implode(DIRECTORY_SEPARATOR, $folders), 0777, TRUE);
The TRUE flag allows mkdir to create folders recursivley. And the implode put the directory parts together like 5/6/4. The DIRECTORY_SEPARATOR is a PHP constant for the slash (/) on unix machines or backslash (\) on windows.
Why not just do:
<?php
$directories = str_split(564);
$path = implode(DIRECTORY_SEPARATOR, $directories);
mkdir($path, 0777, true);
Don't know what you're really trying to do, but here are some hints.
There are recursive mkdir:
if(!file_exists($dir)) // check if directory is not created
{
#mkdir($dir, 0755, true); // create it recursively
}
Path you want can be made in two function calls and prefixed by some start path:
$path = 'some/path/to/cache';
$cache_node_id = 4515;
$path = $path.'/'.join('/', str_split($cache_node_id));
Resulting path can be used to create folder with the code above
So here we come to a pair of functions/methods
function getPath($node_id, $path = 'default_path')
{
return $path.'/'.join('/', str_split($node_id))
}
function createPath($node_id, $path = 'default_path');
{
$path = getPath($node_id, $path);
if(!file_exists($path)) // check if directory is not created
{
#mkdir($path, 0755, true); // create it recursively
}
}
With these you can easily create such folders everywhere you desire and get them by your number.
As mentioned earlier, the solution I got from a friend was
$folders = str_split(564);
mkdir(implode('/',$folders),0777,true);
Also, to add a location defined in a variable, I used
$folders = str_split($idimg);
mkdir($path_defined_earlier. implode('/',$folders),0777,true);
So thanks for all the answers, seems like this was the correct way to handle this.
Now the issue is that I need to the created path, so how can I store it in a variable? Sorry if this breaches any rules, if I need to create a new thread I'll do it...

PHP Check if dynamic named folder exists

I'm having problems checking if a dinamically named folder exists using php. I know i can use
file_exists()
to check if a folder or file exists, but the problem is that the name of the folders I'm checking may vary.
I have folders where the first part of the name is fixed, and the part after "_" can vary. As an example:
folder_0,
where every folder will start with "folder_" but after the "_" it can be anything.
Anyway i can check if a folder with this property exists?
Thanks in advance.
SR
You make a loop to go through all the files/folders in the parent folder:
$folder = '/path-to-your-folder-having-subfolders';
$handle = opendir($folder) or die('Could not open folder.');
while (false !== ($file = readdir($handle))) {
if (preg_match("|^folder_(.*)$|", $file, $match)) {
$curr_foldername = $match[0];
// If you come here you know that such a folder exists and the full name is in the above variable
}
}
function find_wildcard_dirs($prefix)
{
return array_filter(glob($prefix), 'is_dir');
}
e.g.
print_r(find_wildcard_dirs("/tmp/santos_*'));

Using mkdir(), directory not being created

$ad_title = $_POST['title'];
$ad_content = $_POST['content-ads'];
$ad_region = $_POST['region'];
if (!is_dir("uploads/".$ad_region)) {
// dir doesn't exist, make it
mkdir("uploads/".$ad_region);
echo "directory created!";
}
else {
echo "directory already exist!";
}
I am making a site and I am developing it in localhost for now. My save.php file and the uploads folders where the codes above is saved in the local directory
localhost/system/modules/new/
When I relocated the save.php file and the uploads folder in the directory
localhost/system/
all seems to be working now. But I want it to work in the
localhost/system/modules/new/
directory for better organization. Any help on how to make it work?
First thing I'd do is ensure that the paths are where you think they are.
Try this out
$ad_title = $_POST['title'];
$ad_content = $_POST['content-ads'];
$ad_region = $_POST['region'];
// Make sure the "uploads" directory is relative to this PHP file
$uploads = __DIR__ . '/uploads';
$path = $uploads . DIRECTORY_SEPARATOR . $ad_region;
// ensure that the path hasn't been tampered with by entering any relative paths
// into $_POST['region']
if (dirname($path) !== $uploads) {
throw new Exception('Upload path has been unacceptably altered');
}
if (!is_dir($path)) {
if (!mkdir($path, 0755, true)) {
// you should probably catch this exception somewhere higher up in your
// execution stack and log the details. You don't want end users
// getting information about your filesystem
throw new Exception(sprintf('Failed to create directory "%s"', $path));
}
// Similarly, you should only use this for debugging purposes
printf('Directory "%s" created', $path);
} else {
// and this too
printf('Directory "%s" already exists', $path);
}
you can use relative path ../ such as mkdir("../uploads/".$ad_region)
or use absolution path, such as mkdir("/localhost/system/modules/new/".$ad_region)
ref: http://php.net/manual/en/function.mkdir.php
You can use absolute file paths, like "/var/www/system/modules/new/$ad_region" (unix structure).
Or, for example, if your save.php file is in directory "system" and you want to create the directory in "system/modules/new/" you can do
mkdir("./modules/new/$ad_region");
There is a third parameter for mkdir, recursive, which allows the creation of nested directories. For the second parameter you can simple pass 0, for example
mkdir("./modules/new/$ad_region", 0, true);

Remove Old Remote FTP Folders

I've written a MySQL database backup script which store backup files in remote FTP server. It creates some folders in root named by database name, then in each of them it creates some folders named by current date (Format: yyyy-mm-dd), and it these folders it uploads the backup files named by exact time.
I also need to remove old second level folders (which are named by date); I mean the folders older than 4 days. This is the part I've problem with. I tried some codes with ftp_nlist and I could list folders with it, I also ftp_mdtm to get the creation date and compare it with expiration date. But the result was not okay. Here is my code:
...
$skip = array('.', '..', '.ftpquota', '.htaccess');
$expire_date = date('Y-m-d', strtotime('-4 days', time()));
$ff_list = ftp_nlist($con, $db_dir);
foreach($ff_list as $item)
{
if(in_array($item, $skip))
{
continue;
}
$mod_time = ftp_mdtm($con, $item);
if(strtotime($expire_date ) >= $mod_time)
{
ftp_rmdir($con, $item);
}
}
...
Please attend I need to remove the old folders with all of their contents, So I need the suitable remove command (I don't know if ftp_rmdir works properly).
your using the correct command ftp_rmdir
http://php.net/manual/en/function.ftp-rmdir.php
but i bet the problem is that this function, like rmdir, requires the directory be empty.
here's a recursive delete function WARNING! UNTESTED!
//credentials
$host = "ftp server";
$user = "username";
$pass = "password";
//connect
$handle = #ftp_connect($host) or die("Could not connect to {$host}");
//login
#ftp_login($handle, $user, $pass) or die("Could not login to {$host}");
function recursiveDelete($directory){
//try to delete
if( !(#ftp_rmdir($handle, $directory) || #ftp_delete($handle, $directory)) ){
//if the attempt to delete fails, get the file listing
$filelist = #ftp_nlist($handle, $directory);
//loop through the file list and recursively delete each file in the list
foreach($filelist as $file){
recursiveDelete($file);
}
//if the file list is empty, delete the directory we passed
recursiveDelete($directory);
}
}
Try this :
if(strtotime($expire_date ) >= strtotime($mod_time))

if folder exists with PHP

I'd love some help....i'm not sure where to start in creating a script that searches for a folder in a directory and if it doesnt exist then it will simply move up one level (not keep going up till it finds one)
I am using this code to get a list of images. But if this folder didn't exist i would want it to move up to its parent.
$iterator = new DirectoryIterator("/home/domain.co.uk/public_html/assets/images/bg-images/{last_segment}"); foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile() && !preg_match('/-c\.jpg$/', $fileinfo->getFilename())) {
$bgimagearray[] = "'" . $fileinfo->getFilename() . "'";
} }
Put your directory name in a variable.
$directory = "/home/domain.co.uk/public_html/assets/images/bg-images/{last_segment}";
// if directory does not exist, set it to directory above.
if(!is_dir($directory)){
$directory = dirname($directory)
}
$iterator = new DirectoryIterator($directory);
It works: file_exists($pathToDir)
To test if a directory exists, use is_dir()
http://php.net/function.is-dir
To move up to the parent directory would be by chdir('..');
http://php.net/function.chdir

Categories