Execute second statement if the first one holds - php

If a directory does not exist, i create the directory and save a file, i can also just save a file if the directory exists. One file should be created at a time not all at the same time as the code below does. If the first file is created now then the next should only be created when the function is called. The files are Named R1,R2....Rn. How can I achieve this, This creates them all at the same time
$fileName1=$fileName1='somedir/'.$thedir.'/'.$thefile.'_R1.xlsx';
...
if (!dir($dirName))
{
mkdir('somedir/' . thedir, 0777);
$objWriter->save($fileName);
}
if (dir($dirName) && (!file_exists($fileName)))
{
$objWriter->save($fileName);
}
if (dir($dirName) && file_exists($fileName))
{
$objWriter->save('somedir/' . $thedir . '/' . $thefile . '_R1.xlsx');
}
if (dir($dirName) && file_exists($fileName1))
{
$objWriter->save('somedir/' . $thedir . '/' . $thefile . '_R2.xlsx');
}
...

if (!is_dir($dir))
mkdir($dir, 0777);
$suffixes = array('_R1.xlsx', '_R2.xlsx');
foreach($suffixes as $suffix) {
$fileName = $dir.'/' . $thefile . $suffix;
if (! file_exists($fileName)) {
$objWriter->save($fileName);
break;
}
}
You have to add error handling, and note that just checking for a file can create concurrency issues (two processes trying both seeing that the file doesn't exist and try to create it).

You will need to use the [is_dir][1] function to check if a folder exists.
Check out this code - a bit of a rework from yours
$fileName1=$fileName1='somedir/'.$thedir.'/'.$thefile.'_R1.xlsx';
....
// Directory does not exist - create it
if (!is_dir($dirName))
{
mkdir('somedir/' . thedir, 0777);
$objWriter->save($fileName);
}
// Directory exists
if (is_dir($dirName))
{
// File does not exist - create it
if (!file_exists($fileName)))
{
$objWriter->save($fileName);
}
// Check one more time if the file exists
if (file_exists($fileName)))
{
$objWriter->save('somedir/' . $thedir . '/' . $thefile . '_R1.xlsx');
$objWriter->save('somedir/' . $thedir . '/' . $thefile . '_R2.xlsx');
}
}
.......

Related

Am trying to create a folder with random digits, and put a file inside of it

Here is my code
$file = 'post.php';
$root = '/' . $dir_auth1 . '/'. $file;
$folder = mkdir(rand(10,10000));
$folder5 = $folder . '/' . $file;
echo $folder5;
if($folder) {
if (!copy($root, $folder5)) {
echo "failed to copy $file...\n";
} else {
echo "<p style='font-size:35px;font-family:verdana;text-align:center;'>status was successfuly created.</p>";
}
}
Basically what I am trying to do is upon a form submit create a directory with random digits and place the $file variable inside of the randomized directory
mkdir - return bool. Please read about mkdir
And rewrite you code something like this:
$file = 'post.php';
$root = '/' . $dir_auth1 . '/'. $file;
$folder = rand(10,10000);
mkdir($folder);
$folder5 = $folder . '/' . $file;
And check you if. You always true. (not empty string = true)

Can't add all files in the zip (php)

So I found this class on the internet that can put files into a zip.
I have a form where I can upload pictures into a folder, but when I try to add them into the zip I could add only the last file from that folder (loop).
zipper class
<?php
class zipper {
private $_files = array(),
$_zip;
public function __construct() {
$this->_zip = new ZipArchive;
}
public function add($input){
if(is_array($input)){
$this->_files = array_merge($this->_files, $input);
}else{
$this->_files[] = $input;
}
}
public function store($location = null){
if(count($this->_files) && $location){
foreach ($this->_files as $index => $file) {
if(!file_exists($file)){
unset($this->_files[$index]);
}
print_r($file . "<br>");// here gives me the exact path of the files.
}
if($this->_zip->open($location, file_exists($location) ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE)){
foreach ($this->_files as $file) {
$this->_zip->addFile($file, $file);
}
$this->_zip->close();
}
}
}
}
and this is my uploading file
> $uniqUser = uniqid(strtoupper($userName). "-" , true);
> $directory ='../upload/';
> $file_name is $files['name']
if(!is_dir("../upload/". $uniqUser ."/")) {
mkdir("../upload/". $uniqUser ."/");
}
if(move_uploaded_file($file_tmp, $directory . $uniqUser . "/" . $file_name)){
$uploaded[$position] = $directory . $uniqUser . "/" . $file_name;
$zipper = new zipper;
$zipper->add(BASE_URL . "/upload/" . $uniqUser . "/" . $file_name);
$zipper->store(BASE_URL . "/upload/" . $uniqUser . ".zip");
the last code is inside a foreach that loops into the files uploaded.
When I did a print_r("Added file:" . $file . "<br>"); to see if the all files are added, I get a positive response. But I always get the last file from the folder.
Thank you
EDIT
Well, Guess the problem is after each loop to add the files in the folder, the zip class adds the file into the zip, then after checks if the zip exists or no ... So after each loop the zip is overwritten and adds only the last file.
How can I make this better ?
The problem was kinda stupid ...
I had to create the class outside the foreach $zipper = new zipper; and $zipper-store("../upload/" . $uniqUser . ".zip");for unnecessary repeating (added it at the bottom).

Can't create zip file (php)

So I found this class on the internet that can put files into a zip.
I have a form where I can upload pictures into a folder, then I tried to loop into these files and store them into a zip file but seems I failed somewhere.
zipper class
<?php
class zipper {
private $_files = array(),
$_zip;
public function __construct() {
$this->_zip = new ZipArchive;
}
public function add($input){
if(is_array($input)){
$this->_files = array_merge($this->_files, $input);
}else{
$this->_files[] = $input;
}
}
public function store($location = null){
if(count($this->_files) && $location){
foreach ($this->_files as $index => $file) {
if(!file_exists($file)){
unset($this->_files[$index]);
}
print_r($file . "<br>");// here gives me the exact path of the files.
}
if($this->_zip->open($location, file_exists($location) ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE)){
foreach ($this->_files as $file) {
$this->_zip->addFile($file, $file);
}
$this->_zip->close();
}
}
}
}
and this is my uploading file
> $uniqUser = uniqid(strtoupper($userName). "-" , true);
> $directory ='../upload/';
> $file_name is $files['name']
if(!is_dir("../upload/". $uniqUser ."/")) {
mkdir("../upload/". $uniqUser ."/");
}
if(move_uploaded_file($file_tmp, $directory . $uniqUser . "/" . $file_name)){
$uploaded[$position] = $directory . $uniqUser . "/" . $file_name;
$zipper = new zipper;
$zipper->add(BASE_URL . "/upload/" . $uniqUser . "/" . $file_name);
$zipper->store(BASE_URL . "/upload/" . $uniqUser . ".zip");
the last code is inside a foreach that loops into the files uploaded.
I don't know why I fail in creating the archive at the end ...
Could be an easy way to turn these new created folders into a zip or add them into a zip ?
First problem was because I added BASE_URL I had to write ../upload/.
Second problem was kinda stupid ...
I had to create the class outside the foreach $zipper = new zipper; and $zipper-store("../upload/" . $uniqUser . ".zip");for unnecessary repeating (added it at the bottom).

How to delete all folders and files in a directory except a specific folder in PHP

How can I delete all folders and files except a specific folder?
uploaded->
. folder_A->
. . folder_A1 //empty folder
. . folder_A2 //full folder
. . img.png // a file
. .
. folder_B //empty
. .
. folder_c->
. . folder_c1 //empty folder
. . file.doc // a file
. .
I want remove all folders and file in it inside "uploaded" folder except a specific folder that I determined.
For example I want remove all folders and files except folder_c
you should try like this
function Delete($path)
{
if ((is_dir($path) === true) && ($path!='folder_c'))
{
$files = array_diff(scandir($path), array('.', '..'));
foreach ($files as $file)
{
Delete(realpath($path) . '/' . $file);
}
return rmdir($path);
}
else if (is_file($path) === true)
{
return unlink($path);
}
return false;
}
Hope this helps.

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();
}

Categories