Jump to content

[SOLVED] Invalid argument supplied for foreach()


bluebyyou

Recommended Posts

I dont know why i am getting this error "Warning: Invalid argument supplied for foreach() in /home/content/w/i/u/wiuartinny/html/upload_action.php on line 6" for the following:

 

Here is a form where a user can specify how many uploads they would like to perform...

 

<form action="upload_action.php" method="post" enctype="multipart/form-data" name="uploader">

<?php  for($i = 1; $i <= $_POST['numupload']; $i++) {?>
<input name="upload[]" type="file" size="50"><br />
<?php  }?><br />

<input type="submit" name="Submit" value="Submit"><br />
</form>
<?php 

 

Then I have the upload_action.php inside of this..

 

<?php
foreach($_FILES['upload']['size'] as $key => $size) 
{
	if ($size > 0)
{
        //Do all the upload stuff here
        }
}
?>

Link to comment
Share on other sites

Would you mid explaining what is going on there a little bit?

 

I ask because I was using this $_FILES['upload']['tmp_name'][$key] to get the info to upload my files...

 

This thing was working fine for weeks, but all of a sudden today it stopped.

Link to comment
Share on other sites

<?php
// for testing set $b to the file size.
$b=$_FILES['upload']['size']="0";

//loop with for loop count $b.
for($a=0; $a < count($b); $a++) {

//if  varable $b[array of b is set to o] more then or equal to $b
if ($b[$a]>=1){

// if condition correct echo       
		echo hello;
// elseif check the condition agin but les then 1
       }elseif($b[$a]<1){
       	
// if cindition works
       	echo hi;
       }
}
?>

Link to comment
Share on other sites

I do know php operators, that is not the trouble. What i did not understand was what the code you gave me to try was doing, perhaps I was unclear about what my problem or goal is. I would love to just use some code you gave me to fix my problem, but I would like to know why I was using it as well. I wouldn't learn anything from copy and pasting. I dont think what you have posted is addressing my foreach problem.

 

 

Here is my entire code to perhaps better illustrate my problem. Which is again that I have a multiple upload form that users can specify how many files they would like to upload on this form here:

 

<form action="upload_action.php" method="post" enctype="multipart/form-data" name="uploader">

<?php  for($i = 1; $i <= $_POST['numupload']; $i++) {?>
<input name="upload[]" type="file" size="50"><br />
<?php  }?><br />

<input type="submit" name="Submit" value="Submit"><br />
</form>
<?php 

 

Here is the code that uploads the files.

 

<?php session_start(); ?>
<?php
include ('db_connect.php');

foreach($_FILES['upload']['size'] as $key => $size) 
{ // Beginning of foreach
if ($size > 0)
{

	$submit = $_POST['Submit'];
	$temp_file_name = trim($_FILES['upload']['tmp_name'][$key]);
	$file_name = trim($_FILES['upload']['name'][$key]);


	if (($submit) AND ($temp_file_name)) 
	{
		$upload_dir = "uploads/";										//Directory where file is to be uploaded (end with back slash)
		$upload_data_dir = "uploads/upload_data/";						//Directory where log is( make sure to end with back slash
		$max_file_size = 2097152;			//2MB						//The max file upload size in bytes. (ie. .5MB = 524288)
		$banned_array = array("");										//See above
		$ext_array = array(".jpg",".gif",".jpeg");						//The array of file extensions you wish to accept uploads for.

		//Get User Passed Variables
		$temp_file_name = trim($temp_file_name);						//Trim Temp File Name
		$upload_dir = trim($upload_dir);								//Trim Upload Directory
		$upload_data_dir = trim($upload_data_dir);						//Trim Upload Log Directory
		$max_file_size = trim($max_file_size);							//Trim Max File Size

		//Validate the extension array
		foreach ($ext_array as $key => $value) 
		{									
			$first_char = substr($value,0,1);										
			if ($first_char <> ".") 
			{																	//If not a period,
				$extensions[] = ".".strtolower($value);							//Write value with a period to a new array
			} 
			else 
			{																	//Else
				$extensions[] = strtolower($value);								//Write the value to a new array
			}
		}

		//Count the number of extensions
		$ext_count = count($extensions);											

		//Get The File's Extension
		$extension = strtolower(strrchr($file_name,"."));	

		//Validate Extension
		foreach ($extensions as $key => $value) 
		{																		
			if ($value == $extension) 
			{												
				$valid_extension = "TRUE";										
			}
			$all_ext .= $value.", ";												
		}

		//Validate the file's size
		$size = filesize($temp_file_name);											
		if ($size > $max_file_size) 
		{											
			$over_limit = "TRUE";												
		}

		//Start the validation process
		if (!$valid_extension) 
		{
			$file_error = "Invalid Extension!";
			echo "What the fuck?";
		}
		elseif ($over_limit) 
		{
			$file_error = "File is too large!";
		}
	}
	else 
	{


		if (is_uploaded_file($temp_file_name)) 
		{

			//Get and Update counter
			$fp = fopen($upload_data_dir."count.txt","rb") or problem("Can't open count.txt for reading!");
			$count=fread($fp,100);
			$size=filesize($upload_data_dir."count.txt");

			fclose($fp);
			$count++;
			$fp = fopen($upload_data_dir."count.txt","wb") or problem("Can't open count.txt for writing!");
			fputs($fp,$count);
			fclose($fp); 

			$file_name = $count . $extension;									//create new filename
			$year = date("Y");

			if (move_uploaded_file($temp_file_name,$upload_dir . $file_name)) 
			{

				$query = sprintf("INSERT INTO pic (pictureid,pictureuserid,picturefile,pictureyear) 
    	              VALUES ('%s','%s','%s','%s')",
				  $count,$_SESSION['user'],$file_name,$year);

				query_db($query); // <-- database connection function located on includes.php

				$photo_array[] = $count;


			} 
			else 
			{
				$result =  "Your file could not be uploaded, please try again.";
				$file_error = "Failure!";
			}

		}
		else 
		{
			$result =  "Your file could not be uploaded, please try again.";
			$file_error = "Failure!";
		}
	}
}	
else
{
echo "BLAH!";
}

$_SESSION['photo_array'] = $photo_array;
header("location:photo_info.php");	

} // end of foreach


?>

Link to comment
Share on other sites

If you used the following code:

 

<?php
echo '<pre>';
print_r($_FILES);
echo '</pre>';
?>

 

You would probably see your problem. Basically, there is another dimension in your multidimensional array between ['upload'] and ['size']. This is because you have made upload an array as well, as you are accepting multiple uploads from the same form. Im pretty sre your foreach should read something like:

 

<?php
foreach($_FILES['upload'] as $key => $value){
$size = $_FILES['upload'][$key]['size'];
//etc
}
?>

 

Im finding it a little hard to explain. But hopefully you might follow.

Link to comment
Share on other sites

I tried using the print_r()($_FILES)

 

to see what was going on...

 

when I only try one file upload I get

 

Array
(
    [upload] => Array
        (
            [name] => Array
                (
                    [1] => DSC00292.JPG
                )

            [type] => Array
                (
                    [1] => image/jpeg
                )

            [tmp_name] => Array
                (
                    [1] => /tmp/php8jkefl
                )

            [error] => Array
                (
                    [1] => 0
                )

            [size] => Array
                (
                    [1] => 2929784
                )

        )

)

When I try multiple uploads all I get is..

Array
(

)

 

I really don't get what happened, this was working fine up until today.

Link to comment
Share on other sites

<form action="upload_action.php" method="post" enctype="multipart/form-data" name="uploader">

<?php  for($i = 1; $i <= $_POST['numupload']; $i++) {?>
<input name="upload[]" type="file" size="50"><br />
<?php  }?><br />

<input type="submit" name="submit" value="Submit"><br />
</form>

Link to comment
Share on other sites

<?php

$b=$_FILES['upload']['size']="0";

for($a=0; $a < count($b); $a++) {

if ($b[$a]>=1){
       
		echo hello;
       }elseif($b[$a]<1){
       	
       	echo hi;
       }
}
?>

I dont know why i am getting this error "Warning: Invalid argument supplied for foreach() in /home/content/w/i/u/wiuartinny/html/upload_action.php on line 6" for the following:

 

Here is a form where a user can specify how many uploads they would like to perform...

 

<form action="upload_action.php" method="post" enctype="multipart/form-data" name="uploader">

<?php  for($i = 1; $i <= $_POST['numupload']; $i++) {?>
<input name="upload[]" type="file" size="50"><br />
<?php  }?><br />

<input type="submit" name="Submit" value="Submit"><br />
</form>
<?php 

 

Then I have the upload_action.php inside of this..

 

<?php
foreach($_FILES['upload']['size'] as $key => $size) 
{
	if ($size > 0)
{
        //Do all the upload stuff here
        }
}
?>

 

for each is for array???

once the variable is echo and the result is some value not array its not array

 

???

this is no longer an array $_FILES['upload']['size']  but a piece of an array

 

Link to comment
Share on other sites

Alright well first a user can select the number of uploads they would like to perform....Then they are taken to the upload.php page below

 

<?php
session_start();
include("header.php");

if ($_SESSION['auth'] == "yes")
{
echo $file_error;
?>
<form action="upload_action.php" method="post" enctype="multipart/form-data" name="uploader">

<?php  for($i = 1; $i <= $_POST['numupload']; $i++) {?>
<input name="upload[]" type="file" size="50"><br />
<?php  }?><br />

<input type="submit" name="submit" value="Submit"><br />
</form>
<?php 
}
else
{
echo "you must be logged in";
}
include("footer.php"); ?>

 

Next they submit thier uploads and the upload_action page takes over. This page is supposed to take the array from the upload form on upload.php and then upload the ndividual files. While it is doing that it is checking if the size is not over the limit, if the extension is valid and allowed. Also I have  file with a counter in it(jsut a plain text file) For each photo uploaded the new file name comes from that counter, and then it is incremented. The extension for the saved file comes from the original file. While this is happening each new file name is stored to an array. Then that array will be passed on to another page where the user can tag the details into the photo like title, location etc...  I hope this has made sense

 

Here is the upload_action.php file as I have it now. I am echoing some variables in it to test what is going on as well)

 

<?php session_start(); ?>
<?php

include ('db_connect.php');

echo '<pre>';
print_r($_FILES['upload']);
echo '</pre>';


foreach($_FILES['upload']['size'] as $key => $size) 

{ // Beginning of foreach
echo $_FILES['upload']['name'][$key];
echo "<br />";
if ($size > 0)
{

	$submit = $_POST['Submit'];
	$temp_file_name = $_FILES['upload']['tmp_name'][$key];
	$file_name = $_FILES['upload']['name'][$key];


	if (($submit) && ($temp_file_name)) 
	{
		$upload_dir = "uploads/";										//Directory where log is( make sure to end with back slash
		$max_file_size = 2097152;			//2MB						//The max file upload size in bytes. (ie. .5MB = 524288)
		$banned_array = array("");										//See above
		$ext_array = array(".jpg",".gif",".jpeg");						//The array of file extensions you wish to accept uploads for.

		//Get User Passed Variables
		$temp_file_name = trim($temp_file_name);						//Trim Temp File Name
		$file_name = trim($file_name);						//Trim Temp File Name
		$upload_dir = trim($upload_dir);								//Trim Upload Directory
		$upload_data_dir = trim($upload_data_dir);						//Trim Upload Log Directory
		$max_file_size = trim($max_file_size);							//Trim Max File Size

		//Validate the extension array
		foreach ($ext_array as $key => $value) 
		{									
			$first_char = substr($value,0,1);										
			if ($first_char <> ".") 
			{																	//If not a period,
				$extensions[] = ".".strtolower($value);							//Write value with a period to a new array
			} 
			else 
			{																	//Else
				$extensions[] = strtolower($value);								//Write the value to a new array
			}
		}

		//Count the number of extensions
		$ext_count = count($extensions);											

		//Get The File's Extension
		$extension = strtolower(strrchr($file_name,"."));	
		echo "Extension: <br />";
		echo $extension;
		echo "<br />";

		//Validate Extension
		foreach ($extensions as $key => $value) 
		{																		
			if ($value == $extension) 
			{												
				$valid_extension = "TRUE";										
			}
			$all_ext .= $value.", ";												
		} */

		//Validate the file's size
		$size = filesize($temp_file_name);											
		if ($size > $max_file_size) 
		{											
			$over_limit = "TRUE";												
		}



		//Start the validation process
		if (!$valid_extension) 
		{
			$file_error = "Invalid Extension!";
			echo "What the fuck?";
		}
		elseif ($over_limit) 
		{
			$file_error = "File is too large!";
		}

	}
	if (is_uploaded_file($temp_file_name)) 
	{

		//Get and Update counter
		$fp = fopen("uploads/upload_data/count.txt","rb") or problem("Can't open count.txt for reading!");
		$count=fread($fp,100);
		$size=filesize("uploads/upload_data/count.txt");

		fclose($fp);
		$count++;
		$fp = fopen("uploads/upload_data/count.txt","wb") or problem("Can't open count.txt for writing!");
		fputs($fp,$count);
		fclose($fp); 

		$file_name = $count . $extension;	
		echo "Filename: <br />";
		echo $file_name;		
		echo "<br />";						//create new filename
		$year = date("Y");

		if (move_uploaded_file($temp_file_name,$upload_dir . $file_name)) 
		{

			$query = sprintf("INSERT INTO pic (pictureid,pictureuserid,picturefile,pictureyear) 
    	             VALUES ('%s','% s','%s','%s')",
			$count,$_SESSION['user'],$file_name,$year);
			query_db($query); // <-- database connection function located on includes.php

			$photo_array[] = $count; // Keep track of files uploaded


			} 
			else 
			{
				echo "Your file could not be uploaded, please try again 1.";
			}

		}
	else 
	{
		echo "Your file could not be uploaded, please try again 2.";	
	}

}	
else
{
echo "BLAH!";
}



} // end of foreach

//PASS FILES UPLOADED TO NEXT PAGE
$_SESSION['photo_array'] = $photo_array;
// header("location:photo_info.php");	disable until this works



?>

Link to comment
Share on other sites

your idea on for each seems like in effective try this imlazy of coding long for you

but its reaaly good and it will work just ask to clarify

 

<?php  for($i = 1; $i <= 2; $i++) {?>

<input name="upload<?=$i?>" type="file" size="50"><br />

<?php  }?>

<input name="ctrvalue" type="hidden" value='<?=$i?>'>

 

now do the loop

 

for ($ctr=0;$ctr<=$_POST['ctrvalue'];$ctr++)

{

do the stuff here

now you have diff name of file you can have

$_FILES['upload'.$ctr]['name']

 

}

thats how it should not exact but its the idea

Link to comment
Share on other sites

I tried that teng84, but this part "$_FILES['upload'.$ctr]" didn't want to work for me. So since then I have re written the entire thing how I originally intended it to work. So thank you to everyone who helped out, I definitely learned some new things even if we didn't get it to work. Here is the new and working code if anyone is interested. There is no error checking however.

 

Form to choose how many files to upload

<form name="addphotos" method="post" action="upload.php">
Add <select name="numupload">
<option value="1">1</option>
<option value="5">5</option>
<option value="10">10</option> 
</select> Photo(s) 
<input type="submit" name="submit" value="Go" />

 

Form to upload files

<form action="upload_action.php" method="post" enctype="multipart/form-data" name="uploader">
<?php  for($i = 1; $i <= $_POST['numupload']; $i++) {?>
<input name="upload[]" type="file" size="50"><br />
<?php  }?><br />
<input type="hidden" name="ctrvalue" value="<?php echo $i;?>" />
<input type="submit" name="submit" value="Submit"><br />
</form>

 

upload_action.php

<?php session_start(); ?>
<?php
include ('db_connect.php');
foreach($_FILES['upload']['size'] as $key => $size)  
{// START foreach #1

if ($size > 0)															//Check if a file was submitted (if its not do nothing)
{ //START if #1

$file_name = trim($_FILES['upload']['name'][$key]);						//Get the file name
$temp_file_name =  trim($_FILES['upload']['tmp_name'][$key]);				//Get the temporary file name
$extension = strtolower(strrchr($file_name,"."));						//Get the file extension

//Read counter file
$fp = fopen("uploads/upload_data/count.txt","rb") 
	  or problem("Can't open count.txt for reading!");		
$count=fread($fp,100);

$upload_dir = "uploads/";												//Upload directory (Be sure to	end with /)	
$new_file_name = $count . $extension;									//Create new filename
$year = date("Y");														//Current Year

	if (is_uploaded_file($temp_file_name)) 
	{//START if #2
		if (move_uploaded_file($temp_file_name,$upload_dir . $new_file_name)) 
		{//START if #3

		$query = sprintf("INSERT INTO pic (pictureid,pictureuserid,picturefile,pictureyear) VALUES ('%s','% s','%s','%s')",
						$count, 
						$_SESSION['user'],
						$new_file_name,
						$year);
		query_db($query);												//Insert Photo into DB
		$photo_array[] = $count; 											// Keep track of files uploaded

		//Increment counter file
		fclose($fp);
		$count++;
		$fp = fopen("uploads/upload_data/count.txt","wb") 
			  or problem("Can't open count.txt for writing!");
		fputs($fp,$count);
		fclose($fp); 
		}//END if #3
		else
		{//START else #2
		echo "your file could not be saved.";
		}//END else #2
	}//END if #2
	else
	{//START else #1
	echo "your file could not be uploaded.";
	}//END else #1

} //END if #1

}// END foreach #1

echo "Photos Uploaded: <br />";
foreach ($photo_array as $id)
{
echo "$id <br />";
}

?>

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.