How to save file in subfolder using php - php

I have a script with a mysql query which saves a file called invoice.xml every day automatically by running a cron job. In case no data is found a no_orders.txt is saved.
I would like this file not be saved to the same folder as the script.php file is in but to a subfolder called invoices.
The renaming of the old invoice.xml is done with the following code
// rename old file
$nowshort = date("Y-m-d");
if(file_exists('invoice.xml')) {
rename('invoice.xml','invoice_'.$nowshort.'.xml');
}
The saving is done with the following code:
if($xml1 !='') {
$File = "invoice.xml";
$Handle = fopen($File, 'w');
fwrite($Handle, $xml1);
print "Data Written - ".$nowMysql;
fclose($Handle);
#print $xml;
die();
} else {
print "No new orders - ".$nowMysql;
$File = "no_orders_".$nowshort.".txt";
$Handle = fopen($File, 'w');
fclose($Handle);
die();
}
Could I please get assistance how to save this file to a subfolder. Also the renaming of the existing file would need to be within the subfolder then. I have already tried with possibilities like ../invoice/invoice.xml but unfortunately without any success.
Thank you

Just give the path of file 'invoice.xml' to $File.
Otherwise create some $Dir object which will point to Folder named 'invoice', then use accordingly

Use __DIR__ magic constant to retrieve your script.php directory, then you can append /invoice/invoice.xml .
Example if path to your script php something like this:
/var/www/path/to/script.php
$currentDir = __DIR__; //this wil return /var/www/path/to
$invoicePath = $currentDir.'/invoice/invoice.xml';

Related

How to move/copy a file that has a wildcard in the name in PHP?

I am trying to copy a file that I download it. The file name is test1234.txt, but I want to access it using a wildcard like this: test*.txt and after that to move it to another folder (because I don't know how the file name looks like, but I know that the beginning is test and the rest is changing every time I download a new one). I tried some codes:
$myFile = 'C:/Users/Carl/Downloads/'. date("y-m-d") . '/test*.txt';
$myNewFile = 'C:/Users/Carl/Downloads/'. date("y-m-d").'/text.xml';
if(preg_match("([0-9]+)", $myFile)) {
echo 'ok';
copy($myFile, $myNewFile);
}
I am getting an error because of * in $myFile. Any help is very appreciated.
$myFile= 'C:/Users/Carl/Downloads/'. date("y-m-d") . '/test*.txt';
$myNyFile = 'C:/Users/Carl/Downloads/'.date("y-m-d").'/test.txt';
foreach (glob($myFile) as $fileName) {
copy($fileName, $myNyFile);
}
For complete response, if you want to only move *.txt in NewFolder.
$myFiles = 'C:/Users/Carl/Downloads/*.txt';
$myFolderDest = 'C:/Users/Carl/NewFolder/';
foreach (glob($myFiles) as $file) {
copy($file, $myFolderDest . basename($file));
}

On creating zip file by php I get two files instead of one

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

PHP - Function to read and write a TXT file

I'm making a function on WordPress to get the content of the robots.txt file. If the file doesn't exist, create it with default content. I will use it for my options page. Well, this is my code, it should work almost creating the file, but it doesn't:
function get_robots($robots_file) {
$robots_file = get_home_path() . 'robots.txt'; //The robots file.
$dir = get_home_path(); //The root directory
if(is_file($robots_file)){
$handle = fopen($robots_file, "r");
$robots_content = fread($handle, filesize($robots_file));
fclose($handle);
} else {
$default_content = "User-agent: *\nDisallow:";
chmod($dir, 0777);
$handle = fopen($robots_file, "w+");
$robots_content = fwrite($handle, $default_content);
fclose($handle);
}
chmod($dir, 0744);
return $robots_content;
}
I'm not sure if the problem is is_file, or the fopen($robots_file, "w+" (should it be "r"?) after the else. And I'm not sure about the permissions. Is the 777 needed? Is the 744 the default for the root directory of WordPress?
And I use the return to use it as variable later; I suppose the fopen is already creating the file. Am I right?
Thanks in advance.
The first thing, I would use completely different functions, you have file_put_contents() and file_get_contents() for such simple operations.
So possible simpler solution is:
function get_robots() {
$robots_file = get_home_path() . 'robots.txt'; //The robots file.
if(file_exists($robots_file)){
return file_get_contents($robots_file);
} else {
$default_content = "User-agent: *\nDisallow:";
file_put_contents($robots_file, $default_content);
return $default_content;
}
}
I don't see any point to pass $robots_file as function argument so I removed it. You should check if this code simple works.
I also don't see any reason to change $dir permissions as you showed in your code. It should be rather set manually and you definitely shouldn't change your root directory permission in such function.
EDIT
Because this function uses get_home_path() and this one is available probably only on admin panel you have to do it in different way. You may add the following code to the end of your index.php file:
function get_robots($path)
{
$robots_file = $path . DIRECTORY_SEPARATOR . 'robots.txt'; //The robots file.
if(file_exists($robots_file)){
return file_get_contents($robots_file);
} else {
$default_content = "User-agent: *\nDisallow:";
file_put_contents($robots_file, $default_content);
return $default_content;
}
}
get_robots(getcwd());
(Of course if you want, you may move get_robots() function to some other files.
However you should consider if this is the best approach. You will run this function each time your site will be viewed and it's tiny waste (in fact you will probably want to create robots.txt file just once). You could for example create robots.php file and if you want to run it you can run http://yourwordpressurl/robots.php. It's of course your call.

Check if file exists in .tar using PHP

In my program I need to read .png files from a .tar file.
I am using pear Archive_Tar class (http://pear.php.net/package/Archive_Tar/redirected)
Everything is fine if the file im looking for exists, but if it is not in the .tar file then the function timouts after 30 seconds. In the class documentation it states that it should return null if it does not find the file...
$tar = new Archive_Tar('path/to/mytar.tar');
$filePath = 'path/to/my/image/image.png';
$file = $tar->extractInString($filePath); // This works fine if the $filePath is correct
// if the path to the file does not exists
// the script will timeout after 30 seconds
var_dump($file);
return;
Any suggestions on solving this or any other library that I could use to solve my problem?
The listContent method will return an array of all files (and other information about them) present in the specified archive. So if you check if the file you wish to extract is present in that array first, you can avoid the delay that you are experiencing.
The below code isn't optimised - for multiple calls to extract different files for example the $files array should only be populated once - but is a good way forward.
include "Archive/Tar.php";
$tar = new Archive_Tar('mytar.tar');
$filePath = 'path/to/my/image/image.png';
$contents = $tar->listContent();
$files = array();
foreach ($contents as $entry) {
$files[] = $entry['filename'];
}
$exists = in_array($filePath, $files);
if ($exists) {
$fileContent = $tar->extractInString($filePath);
var_dump($fileContent);
} else {
echo "File $filePath does not exist in archive.\n";
}

Selecting file to be edited

i have an application that is used to edit .txt files. the application is made up of 3 parts
Displays contents of a folder with the files to be edited(each file is a link when clicked it opens on edit mode).
writing in to a file.
saving to file.
part 2 and 3 I have completed using fopen and fwrite functions that wasn't too hard. the part that i need help is part one currently I open the file by inputing its location and file name like so in the php file where i have the display function and save function:
$relPath = 'file_to_edit.txt';
$fileHandle = fopen($relPath, 'r') or die("Failed to open file $relPath ! ");
but what i want is for the file to open in edit mode when clicked instead of typing in the files name every time.
$directory = 'folder_name';
if ($handle = opendir($directory. '/')){
echo 'Lookong inside \''.$directory.'\'<br><br>';
while ($file = readdir($handle)) {
if($file !='.' && $file!='..'){
echo '<a href="'.$directory.'/'.$file.'">'.$file.'<a><br>';
}
}
}
this is the code that ti use to display the list of files that are in a specified folder.
Can anyone give me some pointers how I can achieve this ? any help will be greatly appreciated.
To get content of file use file_get_contents();
To put content of file use file_put_contents(); with FILE_APPEND flag for editing.
To recieve list of files in directory you can use DirectoryIterator
Example:
foreach (new DirectoryIterator('PATH/') as $fileInfo) {
if($fileInfo->isDot()) continue;
echo $fileInfo->getFilename() . "<br>\n";
}
If you don't want to put filenames you can put read files once put in db assign ids to them and use links with id param. The other solution is to store files in session array and assign keys for them. When you want to get a file you just need to provide key instead of whole filename and path.
Example with $_SESSION
$file_arr = array();
foreach (new DirectoryIterator('PATH/') as $fileInfo) {
if($fileInfo->isDot()) continue;
$file_arr[] = array("path" => $fileInfo->getPathname(), 'name' => $fileInfo->getFilename());
}
$_SESSION['files'] = $file_arr;
then in view you can use
foreach($_SESSION['files'] as $k=>$file)
{
echo "<a href='edit.php?f=".$k."'>'.$file['name'].'</a>";
}
and edit.php
$file = (int)$_GET['f'];
if(array_key_exits($file, $_SESSION['files'])
{
$fileInfo = $_SESSION[$file'];
//in file info you have now $fileInfo['path'] $fileInfo['name']
}

Categories