PHP Loop mkdir failing - php

Sorry to bother you with this. I'm running mkdir to replicate directories that I have stored in a DB.
If I display the data on a php page the directories look like this:
element1/Content/EPAC/PROD
element1/Content/EPAC/TEST
element1/Content/EPAC_SG/PROD
element1/Content/EU/PROD
element1/Content/EU/TEST
The above is a subset of the data. What is happening with the above subset when I loop through it, it creates the directory element1/Content/EPAC/PROD but ignores element1/Content/EPAC/TEST and element1/Content/EPAC_SG/PROD, Then it creates element1/Content/EU/PROD but ignores element1/Content/EU/TEST etc and continues through the loop like that. The code I'm using is:
foreach($NSRarray as $value)
{
mkdir("ftpfolders/$value", 0700, true);
}
*the $value variable above is the 'element1/Content/EPAC/PROD' record taken from the DB.
Any ideas? Thanks in advance, Ste

I would split this into generating directories one at a time.
Transform your array into sth. like
$dics=array(
'element1' => array(
'Content' => array(
'EPAC' => array('PROD', 'TEST'),
'EPAC_SG' => array('PROD')
'EU' => array('PROD', 'TEST')
)
)
);
Then loop over it, starting with array_keys($dics) and create the directory if not existing.
Continue with array_keys($dics['element1']) and then repeat it until your reach the inner childs.
Hope this helps.

use this code, this will gives you proper folder structure as per your requirement
<?php
$NSRarray = array('element1/Content/EPAC/PROD', 'element1/Content/EPAC/TEST', 'element1/Content/EPAC_SG/PROD','element1/Content/EU/PROD','element1/Content/EU/TEST');
foreach($NSRarray as $value)
{
$getFolders = explode('/' , $value);
$mainFoldername = "ftpfolders";
$countfolder = 0;
$countfolder = count($getFolders);
$tempName = "";
$i = 0;
for($i == 0; $i < $countfolder; $i++){
$tempName .= $getFolders[$i];
if (!file_exists("$mainFoldername/$tempName")) {
mkdir("$mainFoldername/$tempName", 0700, true);
}
$tempName .= '/';
}
}
?>

Related

Is this the correct way to hide a file or folder in PHP

I am just learning more about using classes in PHP. I know the code below is crap has I need help. Can someone just let me know if I am going in the right direction?
while($entryName=readdir($myDirectory)) {
$type = array("index.php", "style.css", "sorttable.js", "host-img");
if($entryName != $type[0]){
if($entryName != $type[1]){
if($entryName != $type[2]){
if($entryName != $type[3]){
$dirArray[]=$entryName;
}
}
}
}
}
What you seem to want is a list of all the files in your directory that do not have one of four specific names.
The code that most resembles yours that would do it more efficiently is
$exclude = array("index.php", "style.css", "sorttable.js", "host-img");
$dirArray = [];
while ($entryName = readdir($myDirectory)) {
if (!in_array($entryName, $exclude)) {
$dirArray[] = $entryName;
}
}
Alternately, you can dispense with the loop (as written, will include both files and directories in the directory you supply)
$exclude = array("index.php", "style.css", "sorttable.js", "host-img");
$contents = scandir($myDirectory);
$dirArray = array_diff($contents, $exclude);
Edit to add for posterity:
#arkascha had an answer that used array_filter, and while that example was just an implementation of array_diff, the motivation for that pattern is a good one: There may be times when you want to exclude more than just a simple list. It is entirely reasonable, for instance, to imagine you want to exclude specific files and all directories. So you have to filter directories from your list. And just for fun, let's also not return any file whose name begins with ..
$exclude = ["index.php", "style.css", "sorttable.js", "host-img"];
$contents = scandir($myDirectory); // myDirectory is a valid path to the directory
$dirArray = array_filter($contents, function($fileName) use ($myDirectory, $exclude) {
if (!in_array($fileName, $exclude) && strpos('.', $fileName) !== 0) {
return !is_dir($myDirectory.$fileName));
} else {
return false;
}
}
You actually want to filter your input:
<?php
$input = [".", "..", "folderA", "folderB", "file1", "file2", "file3"];
$blacklist = [".", "..", "folderA", "file1"];
$output = array_filter($input, function($entry) use ($blacklist) {
return !in_array($entry, $blacklist);
});
print_r($output);
The output is:
Array
(
[3] => folderB
[5] => file2
[6] => file3
)
Such approach allows to implement more complex filter conditions without having to pass over the input data multiple times. For example if you want to add another filter condition based on file name extensions or file creation time, even on file content.

Php gunzip and get name

Good morning!
I unzipped the archive using php, but after that I need to get the name of the files and perform another action, but I can not figure out how to do it.
Is it possible to do this with php? If so, tell me how and, if possible, an example, even a light one.
Thanks
$filelist = glob("/emp/*.gz");
$filedirtxt = glob("/emp/*.txt");
foreach ($filelist as $key => $value) {
$filename = pathinfo($value);
$gzname = $filename['basename'];
$gunzip = shell_exec("gunzip "."/emp/".$gzname);
foreach ($filedirtxt as $keytxt => $valuetxt) {
$filename_txt = pathinfo($valuetxt);
$name_txt = $filename_txt['basename'];
echo $name_txt."\n";
}
}

Like Star half pyramid pattern with URL Path

I guarante this Different than normally Store to Array.
I dont know how to name it in Tittle about what im asked !!
First : sorry for Bad English.
So just see this below ...
Second :
a. im use build in server : php artisan serve
b. framework is Laravel 5.4
I have url http://127.0.0.1:8000/file/999090/img/img-2as
host : 127.0.0.1:8000 etc
main-folder : {/file} Where i store my image
folder-id : {/990909} This is just id for each folder
sub-folder : {/img} Each id has many sub folder [example]
filde-name : {/img2-as} Just file name [example]
So this is question :
I wanna have array like this in PHP :
$array = [
0 => '/file',
1 => '/file/990909',
2 => '/file/990909/img',
3 => '/file/990909/img/img-2as'
];
try this
$root = '/'; // !!! CHANGE THIS WITH YOUR OWN FOLDER!!!
$iter = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($root, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD // Ignore "Permission denied"
);
$paths = array($root);
foreach ($iter as $path => $dir) {
if ($dir->isDir()) {
$paths[] = $path;
}
}
print_r($paths);
I already manage just like this :
$parts = "assets/theme/dist/img//img/user2-160x160.jpg";
$path = explode('/', $parts);
for($i=0;$i<count($path);$i++){
for($j=0;$j<$i;$j++){
echo "/".$path[$j];
}
echo "\n";
}
And result is :
/assets
/assets/
/assets/theme/dist
/assets/theme/dist/img
/assets/theme/dist/img/
/assets/theme/dist/img/img
That is what i want have in array and i already try use array_push, but the result is worse.
Im already found it. Just copy in your php file.
$path = "assets/adminlte/dist/img/user2-160x160";
$asd = explode( '/', $path );
$num = count($asd)-1;
$arr = [];
for($i=0;$i<count($asd);$i++) {
for($j=0;$j<=$i;$j++){
#$arr[$i] .= "/".$asd[$j];
}
}
echo "\n";
print_r($arr);

Searching for a specific string from all PHP files in the parent directory (Updated)

A while ago I made a post (Searching for a specific string from all PHP files in the parent directory) that was about me finding the position of the file path in an array, only if the file had a specific keyword.
However, that was in my old website, which I have now lost. So I am currently recreating it. However, for some reason this function does not work.
public function build_active_theme() {
$dir = CONPATH . '/themes/' . $this->get_active_theme() . '/';
$theme_files = array();
foreach(glob($dir . '*.php') as $file) {
$theme_files[] = $file;
}
$count = null;
foreach($theme_files as $file) {
$file_contents = file_get_contents($file);
if(strpos($file_contents, 'Main')) {
$array_pos = $count;
$main_file = $theme_files[$array_pos];
echo $main_file;
}
$count++;
}
}
This function causes the following error:
Notice: Undefined index: in /home/u841326920/public_html/includes/class.themes.php on line 30
I have narrowed the problem down the something wrong with the $count variable. Whenever I try and echo the $count value once the script has found the correct file, nothing is shown.
But after spending nearly an hour on such a simple problem, it is obviously starting to frustrate me, so I am now seeking help.
(Note: I directly copied the function directly from the old post into my code, and made the appropriate changes to variables to 'work' in the new site, so it's is pretty much exactly the same as the solution that fixed my previous problem - which funnily enough was also caused by the $count variable).
Thanks,
Kieron
You can use the foreach $key instead of a separate count variable, try the code below:
foreach($theme_files as $key => $file) {
$file_contents = file_get_contents($file);
if(strpos($file_contents, 'Main') !== false) {
$main_file = $theme_files[$key];
echo $main_file;
}
}
You are setting
$count = null;
, try to ++ it before the
$array_pos = $count;

Generating unique filenames with tempnam

I looked at a few other questions mentioning tempnam() in the context of unique file naming.
I was left a bit unclear on whether the file names will be truly unique.
Let's say that we have a file upload script, that moves and renames the files to a permanent directory.
What I want to ask, is: Will the file name always be unique, when used like this:
$tmp_name = tempnam($dir, '');
unlink($tmp_name);
copy($uploaded_file, "$tmp_name.$ext");
As cantsay suggested, I made a php script to look for identical values.
function tempnam_tst() {
for ($i=0; $i < 250000 ; $i++) {
$tmp_name = tempnam('/tmp/', '');
unlink($tmp_name);
$arr[$i] = $tmp_name;
}
return array_intersect($arr, array_unique(array_diff_key($arr, array_unique($arr))));
}
$arr = array();
do {
$arr = tempnam_tst();
} while ( empty($arr) );
echo 'Matching items (case-sensitive):<br>';
echo '<pre>';
print_r($arr);
echo '</pre>';
Result:
Matching items (case-sensitive):
Array
(
[59996] => /tmp/8wB6RI
[92722] => /tmp/KnFtJa
[130990] => /tmp/KnFtJa
[173696] => /tmp/8wB6RI
)
From what I can see, tempnam() does not always generate an unique name.
Try this->
$uploadPath = "/upload/";
$fileName = time().$_FILES['file_name']['name'];
$tempName = $_FILES['file_name']['tmp_name'];
move_uploaded_file($tempName,$uploadPath.$fileName);
This will upload unique file in upload folder.

Categories