So with your help I have been able to assemble the below.
$dir = "./reporting/live-metrics/";
$des = "./reporting/historic-metrics/";
$ctime = time();
foreach (glob($dir."*") as $file) {
$live = file_get_contents($file);
if (strpos($live, 'CORO') === false && filemtime($file) < time() - 1 * 10) {
$exclude[] = $live;
$lines = file( $file , FILE_IGNORE_NEW_LINES );
$lines[3] = 'Taken Down';
$lines[5] = $ctime;
file_put_contents( $file , implode( "\n", $lines ) );
if (!file_exists($des.basename($file).PHP_EOL)) {
mkdir($des.basename($file), 0777, true);
}
rename($file,$des.$ctime);
}
}
My issue is that I am attempting to move the file to the new directory created but I am having a little issue with it. No matter what I do I can only get it to move to $des, i cant seem to get ti to move to the dynamicaly created directory for each specific file. I am assuming it has to do with the fact I am not using rename to its correct params. Below are the some of the combinations I have tried to get it to rename and move.
rename($file,$des.basename($file).PHP_EOL.$ctime); //doesn't move or rename
rename($file,$des.basename($file).$ctime); //adds to historic-metrics/ as jason1465519298
I also tried creating a function and setting the rename to call on that. eg.
$path = $des.basename($file).PHP_EOL;
rename($file,$path.$ctime);
Currently the script is great up until the moving the file. It will move it to ./reporting/historic-metrics/ but I would like it to move to the directory just created. EG, if the file it is currently handeling is called 'Jason' then it will create ./reporting/historic-metrics/Jason but move the file to ./reporting/historic-metrics/
There seems to be two possibilities:
Source or destination file paths may be wrong, you can print and check
The newly created destination directory is getting the
correct permission & ownership.
Otherwise your script looks OK.
I finally got it. My main issue was trying to get the filepath to send the file to. After a few interruptions and rethinking my approach I came up with the below. I know it isn't pretty or as slim as could be made but it does the job perfectly.
$dir = "./reporting/live-metrics/";
$des = "./reporting/historic-metrics/";
$ctime = time();
foreach (glob($dir."*") as $file) {
$live = file_get_contents($file);
if (strpos($live, 'CORO') === false && filemtime($file) < time() - 1 * 10) {
$exclude[] = $live;
$lines = file( $file , FILE_IGNORE_NEW_LINES );
$lines[3] = 'Taken Down';
$lines[5] = $ctime;
file_put_contents( $file , implode( "\n", $lines ) );
if (!file_exists($des.basename($file).PHP_EOL)) {
mkdir($des.basename($file), 0777, true);
}
$user = basename($file); //Gets file name that was used in mkdir
$path = (String) $des.$user."/"; //Compiles variables into string
rename($file,$path.$ctime);
}
}
Related
I have a database back up which I wanted to have a directory using mkdir then save the back-up file inside that new created directory. but I'm having trouble saving the backed up file inside that new created mkdir folder. Here is the saving code together with the creation of the mkdir :) thanks!
//save file
$date = date("Y-m-d");
$dir = "new_folder_name";
if( is_dir($dir) === false )
{
mkdir($dir);
}
$path = '/new_folder_name/';
$handle = fopen($path.'db-backup-'.$date.'.sql','w+');
fwrite($handle,$return);
fclose($handle);
It seems that only the directory path setting is incorrect.
Please check the following codes. It works on my computer.
<?php
//save file
$date = date("Y-m-d");
$dir = "new_folder_name";
if( is_dir($dir) === false )
{
mkdir($dir);
}
//Use this setting will help
$path = 'new_folder_name\\';
$handle = fopen($path.'db-backup-'.$date.'.sql','w+');
fwrite($handle,"abc");
fclose($handle);
I'm using bootstrap tables and rows to count how much files are in a folder, but the destination is pointing to a different server the code below does not work.
As i'm using localhost (xampp) trying to do this don't know if its possible.
<?php
// integer starts at 0 before counting
$i = 0;
$dir = 'uploads/'; <!--\\189.207.00.122\folder1\folder2\folder3\test-->
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
$i++;
}
}
// prints out how many were in the directory
echo "There were $i files";
?>
Here is a handy little function you might want to try out. Just pass the path to the Directory as the first argument to it and you'd get your result.
NOTE: This Function is RECURSIVE, which means: it will traverse all sub-directories... to disable this behaviour, simply comment out or delete the following lines towards the end of the Funciton:
<?php
}else if(is_dir($temp_file_or_dir) && !preg_match('/^\..*/', $val) ){
getFilesInFolder($temp_file_or_dir);
}
THE CODE:
<?php
$folder = dirname(__FILE__).'/uploads'; // ASSUMES YOUR uploads DIRECTORY
// IS IN THE SAME DIRECTORY AS index.php
// (/htdocs/php/pages)
// OR
$folder = dirname(__FILE__).'/../uploads'; // ASSUMES YOUR uploads DIRECTORY
// IS ONE DIRECTORY ABOVE
// THE CURRENT DIRECTORY (/htdocs/php)
// THIS IS MOST LIKELY RIGHT
// OR
$folder = dirname(__FILE__).'/../../uploads';// ASSUMES YOUR uploads DIRECTORY
// IS TWO DIRECTORIES ABOVE
// THE CURRENT DIRECTORY (/htdocs)
// MAKE SURE THE FOLDER IN QUESTION HAS THE RIGHT PERMISSIONS
// OR RATHER CHANGE PERMISSIONS ON THE FOLDER TO BE ABLE TO WORK WITH IT
chmod($folder, 0777);
var_dump(getFilesInFolder($folder));
// IF YOU PASS false AS THE THE 2ND ARGUMENT TO THIS FUNCTION
// YOU'D GET AN ARRAY OF ALL FILES IN THE $path2Folder DIRECTORY
// AS WELL AS IN SUB-DIRECTORIES WITHIN IT...
function getFilesInFolder($path2Folder, $countOnly=true){
$files_in_dir = scandir($path2Folder);
$returnable = array();
foreach($files_in_dir as $key=>$val){
$temp_file_or_dir = $path2Folder . DIRECTORY_SEPARATOR . $val;
if(is_file($temp_file_or_dir) && !preg_match("#^\..*#", $temp_file_or_dir)){
$arrRX = array('#\.{2,4}$#', '#\.#');
$arrReplace = array("", "_");
$returnVal = preg_replace($arrRX, $arrReplace, $val);
$returnable[$returnVal] = $temp_file_or_dir;
}else if(is_dir($temp_file_or_dir) && !preg_match('/^\..*/', $val) ){
getFilesInFolder($temp_file_or_dir);
}
}
return ($countOnly) ? count($returnable) : $returnable;
}
Use $_SERVER['DOCUMENT_ROOT'] to get your root directory.
$dir = $_SERVER['DOCUMENT_ROOT'].'/uploads/';
I'm struggling around with a simple PHP functionality: Creating a ZIP Archive with some files in.
The problem is, it does not create only one file called filename.zip but two files called filename.zip.a07600 and filename.zip.b07600. Pls. see the following screenshot:
The two files are perfect in size and I even can rename each of them to filename.zip and extract it without any problems.
Can anybody tell me what is going wrong???
function zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path = array(), $files_array = array()) {
// Archive File Name
$archive_file = $archiveDir."/".$archive_file_name;
// Time-to-live
$archiveTTL = 86400; // 1 day
// Delete old zip file
#unlink($archive_file);
// Create the object
$zip = new ZipArchive();
// Create the file and throw the error if unsuccessful
if ($zip->open($archive_file, ZIPARCHIVE::CREATE) !== TRUE) {
$response->res = "Cannot open '$archive_file'";
return $response;
}
// Add each file of $file_name array to archive
$i = 0;
foreach($files_array as $value){
$expl = explode("/", $value);
$file = $expl[(count($expl)-1)];
$path_file = $file_path[$i] . "/" . $file;
$size = round((filesize ($path_file) / 1024), 0);
if(file_exists($path_file)){
$zip->addFile($path_file, $file);
}
$i++;
}
$zip->close();
// Then send the headers to redirect to the ZIP file
header("HTTP/1.1 303 See Other"); // 303 is technically correct for this type of redirect
header("Location: $archive_file");
exit;
}
The code which calls the function is a file with a switch-case... it is called itself by an ajax-call:
case "zdl":
$files_array = array();
$file_path = array();
foreach ($dbh->query("select GUID, DIRECTORY, BASENAME, ELEMENTID from SMDMS where ELEMENTID = ".$osguid." and PROJECTID = ".$osproject.";") as $subrow) {
$archive_file_name = $subrow['ELEMENTID'].".zip";
$archiveDir = "../".$subrow['DIRECTORY'];
$files_array[] = $archiveDir.DIR_SEPARATOR.$subrow['BASENAME'];
$file_path[] = $archiveDir;
}
zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path, $files_array);
break;
One more code... I tried to rename the latest 123456.zip.a01234 file to 123456.zip and then unlink the old 123456.zip.a01234 (and all prior added .a01234 files) with this function:
function zip_file_exists($pathfile){
$arr = array();
$dir = dirname($pathfile);
$renamed = 0;
foreach(glob($pathfile.'.*') as $file) {
$path_parts = pathinfo($file);
$dirname = $path_parts['dirname'];
$basename = $path_parts['basename'];
$extension = $path_parts['extension'];
$filename = $path_parts['filename'];
if($renamed == 0){
$old_name = $file;
$new_name = str_replace(".".$extension, "", $file);
#copy($old_name, $new_name);
#unlink($old_name);
$renamed = 1;
//file_put_contents($dir."/test.txt", "old_name: ".$old_name." - new_name: ".$new_name." - dirname: ".$dirname." - basename: ".$basename." - extension: ".$extension." - filename: ".$filename." - test: ".$test);
}else{
#unlink($file);
}
}
}
In short: copy works, rename didn't work and "unlink"-doesn't work at all... I'm out of ideas now... :(
ONE MORE TRY: I placed the output of $zip->getStatusString() in a variable and wrote it to a log file... the log entry it produced is: Renaming temporary file failed: No such file or directory.
But as you can see in the graphic above the file 43051221.zip.a07200 is located in the directory where the zip-lib opens it temporarily.
Thank you in advance for your help!
So, after struggling around for days... It was so simple:
Actually I work ONLY on *nix Servers so in my scripts I created the folders dynamically with 0777 Perms. I didn't know that IIS doesn't accept this permissions format at all!
So I remoted to the server, right clicked on the folder Documents (the hierarchically most upper folder of all dynamically added files and folders) and gave full control to all users I found.
Now it works perfect!!! The only thing that would be interesting now is: is this dangerous of any reason???
Thanks for your good will answers...
My suspicion is that your script is hitting the PHP script timeout. PHP zip creates a temporary file to zip in to where the filename is yourfilename.zip.some_random_number. This file is renamed to yourfilename.zip when the zip file is closed. If the script times out it will probably just get left there.
Try reducing the number of files to zip, or increasing the script timeout with set_time_limit()
http://php.net/manual/en/function.set-time-limit.php
I am taking over a website already build because the original programmer is not available anymore.
I need to rename files in a directory, then move the files to their own folder matching the file name, but if the folder does not exist I need to create the folder.
To rename the files I have this php code that it was using the original programmer of the website (Was tested and is working as expected, Let me clarify that the files are something like STV12543.htm and need to be 12543_Todays-Date.htm)
<?php
function dirList ($directory, $prefijo )
{
$results = array();
$handler = opendir($directory);
while ($file = readdir($handler)) {
$comienzo = substr($file, 0, 3);
if ($file != '.' && $file != '..' && $comienzo== $prefijo)
$results[] = $file;
}
closedir($handler);
return $results;
}
$directory = "ws/archivos-cli/";
$prefijo = "STV";
$resultado = dirList($directory, $prefijo);
foreach($resultado as $file){
$ultima_modificacion = filemtime($directory.$file);
$ultima_modificacion = date("Y-m-d", $ultima_modificacion);
$name = split('STV',$file);
$name = split('.htm',$name[1]);
$newname = $name[0].'_'.$ultima_modificacion.'.htm';
//if (!file_exists($directory.$newname))
rename($directory.$file, $directory.$newname);
}
?>
I guess I can call that scrip with a cron, but for moving files, I have a sh script
#!/bin/sh
source_dir='/ws/archivos-cli/'
target_dir='/ws/archivos-cli/subfolders'
name_separator='_'
(
cd ${source_dir} || {
echo "${source_dir} no existe!" ; exit 1
}
for i in `ls` ; do
client_name="`echo ${i} | cut -f1 -d${name_separator}`"
echo "-> Moving file [${i}] to [${target_dir}/${client_name}/] folder"
mv -vf ${i} ${target_dir}/${client_name}/ || break
echo
done
)
So, how can I combine them (the 2 scripts) and add the option to create the folder if not exists, based on the file name without the date?
Thank you in advance.
How do I create a temporary file with a specified extension in php.
I came across tempnam() but using it the extension can't be specified.
Easiest way i have found is to create tempfile and then just rename it. For example:
$tmpfname = tempnam(sys_get_temp_dir(), "Pre_");
rename($tmpfname, $tmpfname .= '.pdf');
my way is using tempnam
$file = tempnam(sys_get_temp_dir(), 'prefix');
file_put_contents($file.'.extension', $data);
{
//use your file
}
unlink($file);//to delete an empty file that tempnam creates
unlink($file.'.extension');//to delete your file
This might simulate mkstemp() (see http://linux.die.net/man/3/mkstemp) a bit, achieving what you want to do:
function mkstemp( $template ) {
$attempts = 238328; // 62 x 62 x 62
$letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$length = strlen($letters) - 1;
if( mb_strlen($template) < 6 || !strstr($template, 'XXXXXX') )
return FALSE;
for( $count = 0; $count < $attempts; ++$count) {
$random = "";
for($p = 0; $p < 6; $p++) {
$random .= $letters[mt_rand(0, $length)];
}
$randomFile = str_replace("XXXXXX", $random, $template);
if( !($fd = #fopen($randomFile, "x+")) )
continue;
return $fd;
}
return FALSE;
}
So you could do:
if( ($f = mkstemp("test-XXXXXX.txt")) ) {
fwrite($f, "test\n");
fclose($f);
}
Let's say tempnam() gives you a file of "filename". You move it to "filename.ext". At any point, tempnam() can give you "filename" again. If you check for "filename.ext", reject the filename given by tempnam(), and call it again, you still end up with the possibility that between one step and another, a file will get created with the same name. (This is discussed in the user comments on the documentation page for tempnam(): https://www.php.net/manual/en/function.tempnam.php.)
However, if you just leave the file created by tempnam() alone (not deleting "filename" until you delete "filename.ext") and work with that filename + the extension, then there is no chance that tempnam() will use that filename again (as far as I can see). Yes, it is messy to have "filename" and "filename.ext" for every single file. On the other hand, it solves the problem.
public static function makeTempFileInFolder($prefix, $suffix, $folder="")
{
if (strlen($folder)==0) $folder = sys_get_temp_dir();
do {
$file = $folder."/".$prefix.rand(1,99999).time().$suffix;
} while (file_exists($file));
return $file;
}
The same as tempnam() except the additional parameter:
function tempnamp($dir, $prefix, $postfix) {
$maxAttempts = 1000;
// Trim trailing slashes from $dir.
$dir = rtrim($dir, DIRECTORY_SEPARATOR);
// If we don't have permission to create a directory, fail, otherwise we will
// be stuck in an endless loop.
if (!is_dir($dir) || !is_writable($dir)) return false;
// Make sure characters in prefix and postfix are safe.
if (strpbrk($prefix, '\\/:*?"<>|') !== false) return false;
if (strpbrk($postfix, '\\/:*?"<>|') !== false) return false;
// Attempt to create a random file until it works.
$attempts = 0;
do
{
$path = $dir.DIRECTORY_SEPARATOR.$prefix.mt_rand(100000, mt_getrandmax()).$postfix;
$fp = #fopen($path, 'x+');
} while (!$fp && $attempts++ < $maxAttempts);
if ($fp) fclose($fp);
return $path;
}
That 'p' at the end of the name stands for 'postfix'.
I prefer this solution:
$uid = uniqid('', true);
$path = sys_get_temp_dir() . "some_prefix_$uid.myextension";
Note: I do not put the prefix in uniqid because, IMHO, it's not its duty
Maybe using
move_uploaded_file($tmp_name, "$uploads_dir/$name.myextension");
See http://php.net/manual/en/function.move-uploaded-file.php#example-2209
Rename does it, find the extension with pathinfo and then replace with the extension you want.
$tmpfname = tempnam(sys_get_temp_dir(), 'FOO');
$newname = str_replace(pathinfo($tmpfname, PATHINFO_EXTENSION),'pdf',$tmpfname);
rename($tmpfname, $newname);
//do what you want with $newname
unlink($newname);