PHP foreach() define 2 things? - php

I'm trying to define both ['name'] and ['tmp_name'], but i'm having no idea how to do so?
Here is my code:
foreach ($_FILES['uploads']['name'] as $filename) {
// Do stuff
}
But inorder to complete and move the file, I need the $_FILES['uploads']['tmp_name'] aswell. How do I define both? I tried looking it up, but found nothing.

Get the index from the foreach and access the associated entries:
foreach ($_FILES['uploads']['name'] as $i => $filename) {
$tmp_name = $_FILES["uploads"]["tmp_name"][$i];
}
Note: Do not use the unfiltered name for the target filename. That's a client-supplied value and can contain anything.

Related

How to manually iterate over array/object without `foreach` and without `for` with PHP

There is this library https://github.com/halaxa/json-machine (PHP) that allows me to read huge JSON files without loading the entire file to memory. It works great and the way I read the JSON is like this:
$temp = \JsonMachine\JsonMachine::fromFile("teste.json");
foreach ($temp as $key => $value) {
echo $value;
}
The problem is that I cant use foreach, I need to only read the JSON as I need. For example, I tried the code below everytime I need to retrieve an element from the array:
echo next($temp);
However it returns and empty string. If I use var_dump(current($temp)) it returns this:
object(JsonMachine\StreamBytes)#2 (1) { ["stream":"JsonMachine\StreamBytes":private]=> resource(10) of type (stream) }
Using the foreach loop works perfectly, but I cant use it, I need to retrieve the elements as I need. How can I do that?
This class already provides a generator, you should be able to do something like this:
$temp = \JsonMachine\JsonMachine::fromFile("teste.json");
$iterator = $temp->getIterator();
$firstItem = $iterator->current();
$iterator->next();
$secondItem = $iterator->current();
$iterator->next();
$thirdItem = $iterator->current();
[Edit] Looks like JsonMachine::getIterator() returns a chained generator, so just change that second line to this:
$iterator = $temp->getIterator()->getIterator();

Laravel file extension for the array values

I am trying to get the file extension of the files from the multiple file input array.
I tried to use File::extension() but it expects a string and I have an array.
I don't need this value for the validation so I can't use Laravel validation. Thanks
I am trying to get the file extension of the files from the multiple
file input array.
Then loop over the $_FILES array.
foreach ($_FILES as $key => $file) {
$extensions[$key] = \File::extension($file['name']);
}
The above presumes no fancy/opinionated $_FILES structure mutations ;p
The best way I use,
foreach ( $request->file ( 'attachment' ) as $attachment ) {
$orignalName = $attachment->getClientOriginalName ();
$mimeType = $attachment->getMimeType () ;
}
If you are using Laravel's default file upload.

creating array of directories in php

Hello here's what I'm trying to achieve. I have this code to scan specific directory and store all sub-directories within array. But when I output it with foreach, only one value is outputted.My code:
foreach(glob($directories.'*', GLOB_ONLYDIR) as $sloz) {
$dirname = array (basename($sloz)); }
<?php foreach ($dirname as $slozka) {
echo <<<dir
$("a[rel='$slozka']").colorbox({maxWidth: "90%", maxHeight: "90%", opacity: ".5"}).;
dir;
} ?>
<?php echo '}'.PHP_EOL ?>
The output is always just one line with sub-directory
Any ideas?
This loop appears incorrect:
foreach(glob($directories.'*', GLOB_ONLYDIR) as $sloz) {
$dirname = array (basename($sloz));
}
I assume you are trying to build an array of matches. But in this loop you are just assigning the value to variable $dirname in each case.
You are then trying to iterate over a non-iterable value, which triggers a PHP Warning: Invalid argument supplied for foreach()..., although I assume you do not have warnings enabled since you did not mention this.
Try the following:
$dirname = [];
foreach (glob($directories.'*', GLOB_ONLYDIR) as $sloz) {
$dirname[] = basename($sloz);
}
Then you can foreach over your array of $dirname values.

Using scandir on array of directories

I would like to pass in an array that contains a list of directories to scan. I want to iterate over each directory and push its content into another array that I will print out, but for some reason my code is not working. The directories exist and the path is correct. I think it has something to do with how I'm using foreach.
These are the errors I'm getting:
Notice: Undefined index: C:\Users\john\Desktop\files\images\ in
C:\xampp\htdocs\test.php on line 6
Warning: scandir(): Directory name cannot be empty in
C:\xampp\htdocs\test.php on line 6
This is the code:
function test($dir = []) {
foreach($dir as $bar) {
$list = [];
array_push($list, scandir($dir[$bar]));
}
print_r($list);
}
test(["C:\Users\john\Desktop\files\images\\", "C:\Users\john\Desktop\files\images\autumn\\"]);
If anyone can think of a simpler way to do this, please don't hesitate to tell me.
You're on the right track. There are a few changes you need to make though.
function test($dir = []) {
$list = [];
foreach($dir as $bar) {
$list[] = scandir($bar);
}
print_r($list);
}
As noted by #BrianPoole you need to move the $list out of the foreach loop. By having it in the loop, the array is reset with each iteration, resulting in the final array having one element.
In addition, the foreach loop as explained above by #TimCooper does not operate the same as in JavaScript. If you really want to access the keys, you can use the following syntax:
foreach($dir as $key => $bar)
You would then use either $dir[$key] or $bar to access the directory value.
Finally, array_push is an additional function call that in your case is not needed. By simply adding [] PHP will push the new value onto the end of the array.
function test($dir) {
// DEFINE LIST OUT SIDE OF LOOP
$list = array();
// Run checks
if(count($dir) > 0) {
// Loop Through Directory
foreach($dir as $directory) {
// Push into list
array_push($list, array("scanned"=>$directory, "contents" => scandir($directory)));
}
}else {
// If no directories are passed return array with error
$list = array(
"error" => 1,
"message" => "No directories where passed into test()",
);
}
print_r($list);
}
This is how I would do it. It provides a couple checks and sets up the data so you can se it a bit more clear.

Find directory structure in CodeIgniter

This is my CodeIgniter code to find the directory structure of a folder in my own server, but it is only going one level deep. I want to list all the subdirectories in the given $path. What is the error in this code?
function finddir($path)
{
$this->load->helper('directory');
$dir=directory_map($path,1);
//echo"$path";
foreach ($dir as $key => $subdir)
{
//echo $subdir."<br/>";
if(is_dir($subdir))
{
echo "<h3>$subdir</h3>";
$this->finddir($subdir);
}
else
{
echo "$subdir<br>";
}
}
}
The output goes only one level deep. Since I'm using recursion, I want it to go into deeper levels.
Try the RecursiveDirectoryIterator for this
function finddir($path)
{
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
echo "$name\n";
}
}
It makes more sense to make two functions so that you're not regenerating the array within a recursive function. This way it's generated once, and you are recursively getting values from just that one array. Unless the directory class is broken, you shouldn't need to check if it's a directory. If it's an array, it's a directory:
function finddir($path){
$this->load->helper('directory');
$dir=directory_map($path);
$this->recursive($dir);
}
function recursive($arr) {
foreach ($arr as $key => $val) {
if (is_array($val)){
echo "<h3>$key</h3>";
echo "<ul>\n";
$this->recursive($val);
echo "</ul>\n";
} else {
echo "<li>".$val."</li>\n";
}
}
}
Your break tags <br/> don't show the structure well, so I changed it to use nested lists.
I just noticed that you are pasing a value of 1 to the directory_map() function. That limits it to just one level, so you probably want to leave that out if you want to goes all the way with the recursion:
$dir=directory_map($path);
Why are you doint it this way?
The directory_map('source directory') returns you an array with sub-arrays (and sub-sub-arrays if applicable based on path).
You get the complete tree - just loop over array and print/use as needed, Use is_array($subdir) to test if its directory or file leaf.
instead of $dir=directory_map($path,1) remove number 1 so it displays this way $dir=directory_map($path) since that number will only return the first level directory only.

Categories