multiple file upload foreach error - php

I have used the following code several times before, and have recently found it to try and use again. There now seems to be an error which I cannot fix, can anyone see what I am doing wrong?
foreach ($_FILES['image']['name'] as $i => $name) {
$uploadfile = $uploaddir . basename($name);
if (!move_uploaded_file($file_post["tmp_name"][$i],$uploadfile))
{
echo set_e('error','Image ['.$i.'] not uploaded','');
}
}
The error I get is
Warning: Invalid argument supplied for foreach() in /sitefolder/functions.php on line 1096
line 1096 is the first line in the first code box

First, never use array keys without checking that they exist. Wrap you code in
if (array_key_exists('image', $_FILES))
{
// ...
}
else
{
// error handling
}
Second, even if the key exists, $_FILES['image']['name'] is supposed to be a string, you cannot feed this to foreach anyway. Better:
foreach ($_FILES as $file)
{
$uploadfile = $uploaddir . basename($file['name']);
if (!move_uploaded_file($file["tmp_name"], $uploadfile))
{
echo set_e('error','Image ['.$i.'] not uploaded','');
}
}

Related

Fatal error when trying to Parse a XML file to CSV in PHP

I am stuck on a bit of code for my program, where I am attempting to convert a XML document to CSV using a function in PHP. The code for the function is:
function createCsv($xml, $f)
{
foreach ($xml->children() as $item)
{
$hasChild = (count($item->children()) > 0) ? true : false;
if (!$hasChild)
{
$put_arr = array($item->getName(), $item);
fputcsv($f, $put_arr, ',', '"');
}
else
{
createCsv($item, $f);
}
}
}
And I am calling it in the main script here:
if (file_exists($FilePath))
{
echo "Converting, please stand by /n";
$xml = $_FILES;
$f = fopen('.csv', 'w');
createCsv($xml, $f);
fclose($f);
//calling function to convert the xml file to csv
$UploadDirectory = $UploadDirectory . basename($_FILES["fileToUpload"]["tmp_name"]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $UploadDirectory))
{
echo "The file has been uploaded and converted. Please click the link below to download it";
echo ''.$File.'';
//giving link to click and download converted CSV file
}
else
{
echo "There was a problem uploading and converting the file. Please refresh the page and try again.";
}
}
the error message I get when running the script through XAMPP is:
Fatal error: Uncaught Error: Call to a member function children() on array in C:\xampp\htdocs\XMLtoCSV\convert.php:4 Stack trace: #0 C:\xampp\htdocs\XMLtoCSV\convert.php(73): createCsv(Array, Resource id #3) #1 {main} thrown in C:\xampp\htdocs\XMLtoCSV\convert.php on line 4
Line 4 that it is referencing is the foreach statement in the createCSV function. I am really at a loss, and very new to PHP. I have had to teach myself PHP with mixed results, and any assistance would be highly appreciated.
You are considering $_FILES as the xml file, which is incorrect.
$_FILES is an associative array of uploaded files. You need to open the file and read the data. To do so you can use simplexml_load_file:
$xml = simplexml_load_file($_FILES["fileToUpload"]["tmp_name"]);
createCsv($xml, $f);

scandir() display file found/not found error messge

I have 100 files and I am scanning them and picking the correct file out of them.
I am using the following code:
$dir = 'myDir';
$files1 = scandir($dir);
$scanned_directory = array_diff($files1, array('..', '.'));
foreach ($scanned_directory as $key => $value) {
$onlyname=explode(".", $value);
if($onlyname[0]== $name){
// echo "file found";
break;
}else{
//echo "<h2>Not Found. Please Try Later</h2>";
}
}
The problem with this is that if the file is the 10th file I get 9x not found, before I get the file found message.
What is the proper way to display error message if no file is found?
I simplified your code a bit.
First of all I get all files from your directory into an array with glob(). Then I simply grab all files which have the name $name with preg_grep() and check with count() if there is at least 1 file with that specific name.
<?php
$dir = "myDir";
$files = glob($dir . "/*.*");
if(count(preg_grep("/^$name\..*$/", array_map("basename", $files))) > 0)
echo "file found";
else
echo "<h2>Not Found. Please Try Later</h2>";
?>

Using rename() which works but giving warning at the same time

OK I'm confused. This code is showing me an error but at same time is doing what I actually needed.
$dir = new DirectoryIterator('./');
foreach ($dir as $filename) {
if (mimes_content_type($filename) == 'txt') {
rename($filename, './txt/'.$filename);
}
}
Warning: rename(txt,./txt/txt.txt): Invalid argument in ./www/session/test.php on line 78
Some advices what i did wrong ?

Issues with Uploading Multiple files with PHP

I can see this question has been asked a million times before. I have been through many of the responses and can't seem to get it right:-
I am simply trying to upload multiple files. I'm certain that the form is correct. The issue I get is that if I use a foreach loop, PHP cycles through 5 times (I guess once for each key in $_FILES).
I have read that you should count the uploaded files in the $_FILE['file_upload'] array, then use a for loop, and include an index on the end, such as:-
$_FILES['file_upload']['name'][$1]
however, when I try to access those values I only get the first letter of the value (I think I understand why this is).
The only thing I can think is to use
for($i ; $i<$size ; $i++){...}
and then nest a foreach loop inside it, however, this seems inefficient and I've seen no other suggestions to this end.
I would therefore be eternally grateful if someone could set me straight once and for all. My code is here:-
foreach ($_FILES['file_upload'] as $key => $value){
$tmp_file = $_FILES['file_upload']['tmp_name'];
$target_file = basename($_FILES['file_upload']['name']);
if(move_uploaded_file($tmp_file,$upload_location."/".$target_file)){
$message = "File uploaded successfully";
} else {
$error = $_FILES['file_upload']['error']; // get the error
$_SESSION['errors'][] = $error_msg[$error];// return the error that matches
}// end if
} // end for
So just to clarify - The above code works and uploads the image, but where the loop cycles through 5 times (I'm assuming once per $_FILES attribute), I am getting 5 error messages.I hope this makes sense.
Many thanks in advance for any pointers
Phill
The following was taken from: PHP Manual
<?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>
Which in turn you should be able to modify to something like this:
<?php
$uploads_dir = '/uploads';
foreach ($_FILES["file_upload"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["file_upload"]["tmp_name"][$key];
$name = $_FILES["file_upload"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>
change your foreach to this
foreach ($_FILES['file_upload']['tmp_name'] as $key => $value){
$tmp_file = $_FILES['file_upload']['tmp_name'][$key];
$target_file = basename($_FILES['file_upload']['name'][$key]);
if(move_uploaded_file($tmp_file,$upload_location."/".$target_file)){
$message = "File uploaded successfully";
} else {
$error = $_FILES['file_upload']['error'][$key]; // get the error
$_SESSION['errors'][] = $error_msg[$error];// return the error that matches
}// end if
} // end for
I dont think I understand you completely. If you are uploading multiple files, you should use foreach (no counter required).
The only counter you should use is to count the numbers of files that were successfuly uploaded.
Try this:
$success = 0;
foreach ($_FILES['files']['name'] as $file => $name){
$tmp_file = $_FILES["files"]["tmp_name"][$file];
$target_file = $name;
if(move_uploaded_file($tmp_file,$upload_location."/".$target_file)){
$message = "File uploaded successfully";
$success++;
} else {
$error = $_FILES['file_upload']['error']; // get the error
$_SESSION['errors'][] = $error_msg[$error];// return the error that matches
}// end if
} // end for
echo $success.' files were uploaded';

get_meta_tags works for URLs, but not local files

I'm trying to create a script that will read the meta tags from all other files in a directory and display information on each. When I try to do this referring to the local file name, it doesn't work. But for some reason, when I reference the complete URL, it works, but is too slow to be useful.
When I turn on error reporting, I get this error each time through the loop:
Undefined index: description in /path/to/my/script/index.php on line 83
Anybody know why remote files would work and local ones would not?
Here's the code that fails:
$dir = '.';
$files = scandir($dir);
foreach ($files as &$value) {
$tags = get_meta_tags($value);
echo $tags['description'] . "<br>";
}
But for some reason, this code works:
$dir = '.';
$files = scandir($dir);
foreach ($files as &$value) {
$tags = get_meta_tags('http://mydomain.com/path/' . $value);
echo $tags['description'] . "<br>";
}

Categories