Jump to content

create directory, rename file from source and place into new directory with date


mpg
 Share

Go to solution Solved by Barand,

Recommended Posts

<?php
    $store_path = './';
    $name = date('ydhis');
    if(!is_dir($store_path.$name)) mkdir($store_path.$name);
    
	copy('tokenmaster/starttoken.php', './starttoken.php');

	$filename = './starttoken.php';

	if (file_exists($filename)) {
		$date = new DateTime();
		rename("./starttoken.php", "./tokendone" . $date->format('ydhis') . ".php");
	}
	
	#... your code
    #build your content and store it e.g. by
    file_put_contents($store_path.$name.'/'.$filename, $yourcontent);
?>

I'm stumped as I don't quite get why my new renamed file is not dated and placed into the new directory, rather in the root. any help would be great. Sorry if I'm posting this wrong I'm new here.

Link to comment
Share on other sites

Not sure what is supposed to happen so I did a bit of reorganization of your code to help understand it better.

$store_path = './';	// save to folder above current
$name = date('ydhis');	// use a name of yyddhhmmss
if(!is_dir($store_path . $name))
{
	mkdir($store_path.$name);	// make a new dir above current using current time
	echo "Dir $store_path$name has been created<br>";
}
else
	echo "Dir $store_path$name already exists<br>"; // dir already exists. How?

$filename = $store_path . 'starttoken.php';
if (copy('tokenmaster/starttoken.php', $filename))
	echo "Copy to $filename was successful<br>";
else
{
	echo "Copy to $filename failed<br>";
	exit();
}

$date = new DateTime();
$newname = "./tokendone" . $date->format('ydhis') . ".php";
if(rename($filename, $newname))
	echo "Rename of $filename to $newname was successful<br>";
else
	echo "Rename of $filename failed<br>";

$savename = $store_path.$name.'/'.$filename;
echo "Attempting to save some data to $savename<br>";
if(file_put_contents($savename, $yourcontent) === false)
	echo "Save to $savename failed<br>";
else
	echo "Save to $savename succeeded<br>";
exit();

Run this and see what messages you get.

  • Great Answer 1
Link to comment
Share on other sites

<?php
    $store_path = './';
    $name = date('ydhis');
    if(!is_dir($store_path.$name)) mkdir($store_path.$name);
    
	copy('tokenmaster/starttoken.php', './starttoken.php');

	$filename = './starttoken.php';

	if (file_exists($filename)) {
		$date = new DateTime();
		rename("./starttoken.php", "$name/tokendone" . $date->format('ydhis') . ".php");
	}
?>

Ok comments I have come to this which does what I need it to do. grabs file from directory, renames it with date, creates new folder with date and places the renamed file into it.  Thank you for helping.

Link to comment
Share on other sites

<?php

    // get the last created/modified directory

    $path = "./";

    $latest_ctime = 0;
    $latest_dir = '';    
    $d = dir($path);

    while (false !== ($entry = $d->read())) {
    $filepath = "{$path}/{$entry}";

    if(is_dir($filepath) && filectime($filepath) > $latest_ctime) {
      $latest_ctime = filectime($filepath);
      $latest_dir = $entry;
    }

    } //end loop

    //echo $latest_dir;
	echo "<a href=$latest_dir $latest_file><button>"."continue</button></a><br>";
    ?>	

My next problem is joining this new file in the new directory to link to, i'm not getting this part (echo "<a href=$latest_dir $latest_file><button>"."continue</button></a><br>";)

Link to comment
Share on other sites

Not sure what you mean by "not getting"?

One thing that's important to understand is that url's involve "web space", not filesystem space on a workstation.

If you use FILE|OPEN with your browser, the browser goes into a local mode where it will parse html etc, and will work with local files and paths but rarely do I see this use case.  Since I'm not sure what the purpose of your current scripts are, it's hard to say, but a URL is not a filesystem path.

Is this code meant to be accessed via a browser?  Then your URL's need to be within webspace, and not reflecting a file system path.

Just for clarity, even with what you have, it's odd, and you introduce a space where you probably need a directory separator.  If you are using interpolation, then use it.

Maybe?

echo "<a href='$latest_dir/$latest_file'><button>continue</button></a><br>";

With that said, this should only produce a url with a local filesystem path, and only usable by a browser in local mode, which is almost never what you want to be using PHP for.

  • Great Answer 1
Link to comment
Share on other sites

<?php

    // get the last created/modified directory

    $path = "./";

    $latest_ctime = 0;
    $latest_dir = '';    
    $d = dir($path);

    while (false !== ($entry = $d->read())) {
    $filepath = "{$path}/{$entry}";

    if(is_dir($filepath) && filectime($filepath) > $latest_ctime) {
      $latest_ctime = filectime($filepath);
      $latest_dir = $entry;
    }

    } //end loop

    //echo $latest_dir;
	//echo "<a href=$latest_dir $latest_file><button>"."continue</button></a><br>";
	echo "<a href='$latest_dir/tokendone$name.php'><button>"."continue</button></a><br>";
    ?>	

Ok thank you with a little adjustment i have this part working now...............so thank you again. hope im not asking to many questions, I tend to do that.

Link to comment
Share on other sites

<?php
$leave_files = array('done.php', 'done2.php', 'index.php', 'tokenset.php', 'tokenmaster');
function removeDirectory($path) {

	$files = glob($path . '/*');
	foreach ($files as $file) {
		is_dir($file) ? removeDirectory($file, $leave_files) : unlink($file);
	}
	rmdir($path);

	return;
}
?>

Last item on this, I'm trying to remove the directories (and files in each) in the root folder, but leave selected files and folders using $leave_files function, I must be doing something wrong any advise would be great. 

Link to comment
Share on other sites

I would like to see how you call the removeDirectory function. And where is the "$leave_files function" defined?  

Plus - in your recursive call you are using 2 arguments the function is only defined for one.  Is that a new thing in php 8 perhaps?

Are you getting any errors from this code?  Do you have error checking turned on?

Link to comment
Share on other sites

Ok I'm clearly not call the removeDirectory function correctly and the $leave_files function is also not done correctly.

There are no errors though.

Ill keep at it and come up with something better.....Thank you. 😀

Link to comment
Share on other sites

If this latest effort is related to the beginnings of this topic I have to ask this:

Why create a set of folders and files in those folders from the root?  Why not just create one project folder underneath the root and from there create all of your folders and files so that when you get to this point, all you have to do is delete that one project folder?  Much, much easier cleanup process.

Link to comment
Share on other sites

On 1/19/2022 at 9:48 AM, ginerjm said:

Update.

Just did a little testing and surprisingly PHP doesn't error out if you use too many args in a call, only when you use too few args.  Another learning moment.

Being able to pass extra/unlabeled parameters was a feature you could make use of using func_get_args.  

PHP version 5.6 added variable parameter lists(variadic) and the "..." operator to formalize this and make it easier to use.  So now you can have code like this:

function giftBasket($occasion, ...$contents) {
    echo "You purchased the $occasion basket that contains " . implode(', ', $contents) . '.' . PHP_EOL;
}

giftBasket('Holiday', 'Salmon', 'Crackers', 'Candy');
giftBasket('Birthday', 'Balloons', 'Cupcakes');
giftBasket('Valentine', 'Chocolates');

 

The "..." operator is called the Spread operator or spread syntax in javascript.  Some languages like Ruby call it the "splat" operator, although most use the asterisk.   It works to essentially explode an array into individual variables that can then be passed as parameters.

function bio($name, $city, $state) {
    echo "$name is from $city, $state" . PHP_EOL;
}

$players[] = array('Bob', 'Phoenix', 'AZ');
$players[] = array('Samantha', 'Boise', 'ID');
$players[] = array('Charlie', 'New Haven', 'CT');

foreach ($players as $player) {
    bio(...$player);
}

The PHP group has been pretty busy adding features like this to the language.

Link to comment
Share on other sites

<?php
 function rrmdir($dir) {
   if (is_dir($dir)) {
     $objects = scandir($dir);
     foreach ($objects as $object) {
       if ($object != "." && $object != "..") {
         if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
       }
     }
     reset($objects);
     rmdir($dir);
   }
 }
$filesToKeep = array(
    'tokenset.php',
    'index.php',
	'done.php',
	'count.php',
	'tokenmaster',
    'start'
    
);

$dirList = glob('*');
foreach ($dirList as $file) {
    if (! in_array($file, $filesToKeep)) {
        if (is_dir($file)) {
            rrmdir($file);
        } else {
            unlink($file);
        }//END IF
    }//END IF
}//END FOREACH LOOP
?>

Thought I might show the solution that was used....

Link to comment
Share on other sites

Looks good.  Well Done!

Update:

Except for the check on the function's incoming object.  You check if it is a dir yet your mainstream logic doesn't call rrmdir if it isnt a dir.  

Edited by ginerjm
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.