Putting created file to date folder - php

I made some file name.
First I need to create folder with year and month and then in that folder to put my new created csv file.
Everything seems to be working except the part where I need to put that csv file in new created folder.
File is created and folder is created.
Can someone help with the trick.
It puts it outside the folder.
My code:
// get directory path to save csv files
$rootDir = $this->container->get('kernel')->getRootDir();
$dir = $rootDir . '/../web/uploads/files/';
// makeing new directory by date
if(!is_dir($dir . date('Y-m'))) {
mkdir($dir . date('Y-m'), 0777, true);
}
// generating csv file name
$fileName = 'export-'.date('Y-m-d').'.csv';
$fp = fopen($dir .$fileName, 'w');

You create a folder with the year and month, but you never add the new folder to your $dir-variable.
Try this:
$rootDir = $this->container->get('kernel')->getRootDir();
// Let's add the full destination here (including the month-dir)
$dir = $rootDir . '/../web/uploads/files/' . date('Y-m');
// Now we don't need to append the date since it's already included
if(!is_dir($dir)) {
mkdir($dir, 0777, true);
}
// generating csv file name
$fileName = 'export-'.date('Y-m-d').'.csv';
// Just add a / and the filename and it should be the correct path
$fp = fopen($dir . '/' . $fileName, 'w');

Related

PHP define the destination folder for an upload

I use the following PHP script to upload an image to my server. Actually it moves the file in the same folder where my script is (root). I would like to move it into the folder root/imageUploads. Thank you for your hints!
$source = $_FILES["file-upload"]["tmp_name"];
$destination = $_FILES["file-upload"]["name"];
...
if ($error == "") {
if (!move_uploaded_file($source, $destination)) {
$error = "Error moving $source to $destination";
}
}
You will need to check if the destination folder exists.
$destination = $_SERVER['DOCUMENT_ROOT'] . '/imageUploads/'
if (! file_exists($destination)) { // if not exists
mkdir($destination, 0777, true); // create folder with read/write permission.
}
And then try to move the file
$filename = $_FILES["file-upload"]["name"];
move_uploaded_file($source, $destination . $filename);
So now your destination looks like this:
some-file.ext
and it's dir is same as file that executes it.
You need to append some dir path to current destination. E.g.:
$path = __DIR__ . '/../images/'; // Relative to current dir
$path = '/some/path/in/server/images'; // Absolute path. Start with / to mark as beginning from root dir
And then move_uploaded_file($source, $path . $destination)
Full path to the destination folder should be provided to avoid and path issue for moving uploaded files, I have added three variations for destination paths below
$uploadDirectory = "uploads";
// Gives the full directory path of current php file
$currentPath = dirname(__FILE__);
$source = $_FILES["file-upload"]["tmp_name"];
// If uploads directory exist in current folder
// DIRECTORY_SEPARATOR gices the directory seperation "/" for linux and "\" for windows
$destination = $currentPath.DIRECTORY_SEPARATOR.$uploadDirectory.DIRECTORY_SEPARATOR.$_FILES["file-upload"]["name"];
if (!move_uploaded_file($source, $destination)) {
echo $error = "Error moving $source to $destination";
}
// If to current folder where php script exist
$destination = $currentPath.DIRECTORY_SEPARATOR.$_FILES["file-upload"]["name"];
if (!move_uploaded_file($source, $destination)) {
echo $error = "Error moving $source to $destination";
}
// If uploads directory exist outside current folder
$destination = $currentPath.DIRECTORY_SEPARATOR."..".DIRECTORY_SEPARATOR.$uploadDirectory.DIRECTORY_SEPARATOR.$_FILES["file-upload"]["name"];
if (!move_uploaded_file($source, $destination)) {
echo $error = "Error moving $source to $destination";
}

Add file in every directory form foreach

I am trying to add one xlsx file to zip directory and folders for each locale from an existing database with the given name.
This part is working.
I have trouble figuring out how to in every of that created folders add the same JSON file that I defined in my code.
Can anybody help with that?
This is my working code.
$rootDir = $this->container->get('kernel')->getRootDir();
$dir = $rootDir . '/../web/files/';
$file = $dir . 'my_file.xlsx';
$getFile = basename($file);
$findLocale = $this->getLocalRepository()->findAll();
$jsonFileToAdd = $dir . 'jsonFile.json';
$zip = new \ZipArchive();
$zipName = $rootDir . '/../web/my-files/zip/' . 'dictionary.zip';
$zip->open($zipName, \ZipArchive::CREATE);
$zip->addFile($file, $getFile);
if ($zip->addEmptyDir('app')) {
foreach ($findLocale as $locale) {
$zip->addEmptyDir($locale->getLocale());
}
}
$zip->close();

How to store uploaded files in a directory of the main domain from a subdomain upload form

please how can store uploaded file in my main domain directory should it be like this:
move_uploaded_file(https://example.com/uploads)
First step is to start here with handling uploaded files:
http://php.net/manual/en/function.move-uploaded-file.php
The first example is almost exactly what you want:
<?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = basename($_FILES["pictures"]["name"][$key]);
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>
You will need to make two edits. The $uploads_dir will need to have a relative path to where the files are uploaded. Let's say your form is in the root of your subdomain in subdomain.example.com/ and you want to move them to public_html/uploads. Your new $uploads_dir should look like the following:
$uploads_dir = __DIR__ . '/../public_html/uploads';
__DIR__ will give you the current director your php file is running in. This allows you to create a relative path to other directories.
The second edit is to update the $_FILES array to loop through the proper structure of what you are uploading. It might not be pictures as in the example.
This would be a quick and dirty way to do it( assuming you're in the root directory of your subdomain and your main domain is its own folder( if your main directory does not have its own folder remove the 2nd chdir)
Im assuming youre uploading an image. if not make the changes as necessary
chdir(dirname("../"));// this takes you up one level
chdir("main_directory");// use this only if main directory is inside a folder
$filepath = getcwd() . DIRECTORY_SEPARATOR . 'images' .DIRECTORY_SEPARATOR;
if (!file_exists($filepath)) {
mkdir($filepath, 0755);// this is only to create a new images folder if it doesnt exist
}
chdir($filepath);
$filename = 'file_name_you_want';
$info = pathinfo($_FILES['img']['name']);
$ext = $info['extension'];
$newname = $filename . "." . $ext;
$types = array('image/jpeg', 'image/jpg', 'image/png');
if (in_array($_FILES['img']['type'], $types)) {
if (move_uploaded_file($_FILES["img"]["tmp_name"], $newname)) {
$img_path = 'images' . DIRECTORY_SEPARATOR . $newname;
} else {
// do what needs to be done
}
If youre using php 7 you might want to take a look at string
dirname ( string $path [, int $levels = 1 ] );// the 2nd param would be how many levels up you want to go and $path can be your current directory using __DIR__

php recursive iterator fails on file rename

I am having issue with RecursiveIteratorIterator moving to next item. I have a directory which has multiple files, and I am trying to go to each file, rename it, and do some other stuff on it. The RecursiveIteratorIterator picks the first file from the directory and renames it successfully. When I do $it->next(), it stays on same file, and tries to look for the file which was already renamed to something else. Below is my code sample. File permission are set to 777. Any ideas would be appreciated.
This only happens if I rename the file. If I remove renaming functionality, its moves to next item as expected.
//initialize iterator object
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory, 0));
/* loop directly over the object */
while ($it->valid()) {
// check if value is a directory
if (!$it->isDot()) {
if (!is_writable($directory . '/' . $it->getSubPathName())) {
//direcotry not writable, throw error
} else {
// get current file info
$fileinfo = pathinfo($it->getSubPathName());
//get file extension
$ext = $fileinfo['extension'];
//if its a '.', move to next item
if (in_array($fileinfo['filename'], array(".", ".."))) {
$it->next();
}
// the current file name with complete path
$old_file = $directory . '/' . $it->getSubPathName();
throw new Exception('source file doesnot exist ' . $old_file, error::DOESNOTEXIST);
}
//generate new file name with path
$new_file = $directory . '/' . $it->getSubPath() . '/' . $filename . '.' . $ext;
//rename the file
rename($old_file, $new_file);
}
}
/* * * move to the next iteration ** */
$it->next();
}

Zip file add and rename with php

I have this piece of code..,everything works fine ,but an issue with renaming
$zip = new ZipArchive();
$zipPath = 'images/userfiles/'.$company_details->company_name.'_products.zip';
$emptydir = $company_details->company_name.'_product_logos';
if ($zip->open($zipPath, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE)) {
$new_filename = substr($my_file, strrpos($my_file, '/') + 1);
$zip->addFile($my_file, $new_filename);
$zip->addEmptyDir($emptydir);
foreach($parts_list as $pl) {
if(!empty($pl['part_image'])){
if (file_exists($_SERVER['DOCUMENT_ROOT'] . $baseurl . '/images/group-logo/' . $pl['part_image'])) {
$img_file = 'images/group-logo/' . $pl['part_image'];
$new_filename2 = substr($img_file, strrpos($img_file, '/') + 1);
$zip->addFile($img_file,$emptydir . '/' . $new_filename2);
/*********the problem here******
Is there any way to rename the file that i added on the previous line to something else ,already tried zip rename and renameindex but not working
for example i want to rename the file $new_filename2 to $new_filename2.'something' with out affecting the original file's name
P.S the files to be renamed are inside another folder in the zip
*******************************/
}
}
}
$zip->close();
}
Since you do not want to effect the original file I would think that you are going to need to include a copy statement. Something like;
$file = '$new_filename2';
$newfile = '$new_filename2.zip';
if (!copy($file, $newfile)) {
echo "failed to copy $file...\n";
Okay i figured it out
Zip creates a lock on the file..you cant rename on the fly ,close it and rename again
$zip->addFile('.....');
....
$zip->close();
and open zip again and rename

Categories