Warning: Invalid argument supplied for foreach() - uploading photos form - php

Hi I'm new to php and keep getting this error: "Warning: Invalid argument supplied for foreach() in /home/site/folder/upload.php on line 61."
I'm trying to build a form in which users can upload one or more photos automatically to a directory to then be displayed else where.
Whenever I use this form I created it functions properly on my website but unfortunately it keeps printing that error out and would like it to go away. Here is my code I'm working with:
<div>
<form action="upload.php" enctype="multipart/form-data" method="POST">
<input type="file" name="images[]" multiple="multiple"/>
<input type="submit" name="submit" value="upload images"/>
<form/>
<?php
// check if uploads directory exists
$dir = "images/";
if(!is_dir($dir))
{
echo "Directory not found, let's create the folder.";
mkdir($dir,"0777", true);
}
$countimg = 0;
$allimg = 0;
foreach($_FILES["images"]["name"] as $k=>$name)
{
$allimg++;
$imgname = $_FILES["images"]["name"][$k];
$sizeimg = $_FILES["images"]["size"][$k];
$tmpname = $_FILES["images"]["tmp_name"][$k];
//2.
$extension = strtolower(pathinfo($dir.$imgname, PATHINFO_EXTENSION));
if($extension=='png' || $extension=='jpg' ||$extension=='jpeg' ||$extension=='gif')
{
if($sizeimg < 2097152){
if(!file_exists($dir.$imgname)){
//1.
if(move_uploaded_file($tmpname,$dir.$imgname))
{
$countimg++;
}
}
}
}
}
echo "You are trying to upload $allimg images".'<br>';
echo "From $allimg image(s) - $countimg was/were uploaded with success".'<br>';
$z = $allimg - $countimg;
echo "$z image(s) were not uploaded: Not an image, over 2MB, or already uploaded.";
?>
</div>

Try
if (count($_FILES)) {
foreach($_FILES["images"]["name"] as $k=>$name) {
....
}
}

I tested your script, it works fine. The error message appears because you are not checking that a file got uploaded before starting the foreach. If I land on the page, the PHP code will still be triggered. To fix this, you may use the below:
<div>
<form action="upload.php" enctype="multipart/form-data" method="POST">
<input type="file" name="images[]" multiple="multiple"/>
<input type="submit" name="submit" value="upload images"/>
<form/>
<?php
if( $_POST['submit'] ) {
$dir = "images/";
if(!is_dir($dir))
{
echo "Directory not found, let's create the folder.";
mkdir($dir,"0777", true);
}
$countimg = 0;
$allimg = 0;
foreach($_FILES["images"]["name"] as $k=>$name)
{
$allimg++;
$imgname = $_FILES["images"]["name"][$k];
$sizeimg = $_FILES["images"]["size"][$k];
$tmpname = $_FILES["images"]["tmp_name"][$k];
//2.
$extension = strtolower(pathinfo($dir.$imgname, PATHINFO_EXTENSION));
if($extension=='png' || $extension=='jpg' ||$extension=='jpeg' ||$extension=='gif')
{
if($sizeimg < 2097152){
if(!file_exists($dir.$imgname)){
//1.
if(move_uploaded_file($tmpname,$dir.$imgname))
{
$countimg++;
}
}
}
}
}
echo "You are trying to upload $allimg images".'<br>';
echo "From $allimg image(s) - $countimg was/were uploaded with success".'<br>';
$z = $allimg - $countimg;
echo "$z image(s) were not uploaded: Not an image, over 2MB, or already uploaded.";
}
?>
</div>
if( $_POST['submit'] ) will ensure that the form is submitted prior to running the rest of the PHP code.

Related

Uploading Multiple Files to Location and Updated Database

I have been working on a multi-image upload function that I can't seem to make work. It currently will only work if I have a single image uploaded. I can't figure out what is going wrong with this script.
This is the function to upload images:
if(isset($_POST["btnSubmit"])){
$errors = array();
$extension = array("jpeg","jpg","png","gif");
$bytes = 1000000;
$allowedKB = 10485760000;
$totalBytes = $allowedKB * $bytes;
$imgDir = "assets/users/".$userLoggedIn."/images/";
if(isset($_FILES["files"])==false)
{
echo "<b>Please, Select the files to upload!!!</b>";
return;
}
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name)
{
$uploadThisFile = true;
$file_name=$_FILES["files"]["name"][$key];
$file_tmp=$_FILES["files"]["tmp_name"][$key];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(!in_array(strtolower($ext),$extension))
{
array_push($errors, "File type is invalid. Name:- ".$file_name);
$uploadThisFile = false;
}
if($_FILES["files"]["size"][$key] > $totalBytes){
array_push($errors, "File size is too big. Name:- ".$file_name);
$uploadThisFile = false;
}
if($uploadThisFile){
$filename = basename($file_name,$ext);
$newFileName = uniqid().$filename.$ext;
move_uploaded_file($_FILES["files"]["tmp_name"][$key],$imgDir.$newFileName);
// current date and time
$date_added = date("Y-m-d H:i:s");
$imagePath = $imgDir.$newFileName;
$query = "INSERT INTO images(date_added, added_by, image, deleted) VALUES('$date_added', '$userLoggedIn','$imagePath', 'no')";
mysqli_query($con, $query);
}
}
header("Location: edit-images.php");
$count = count($errors);
if($count != 0){
foreach($errors as $error){
echo $error."<br/>";
}
}
}
?>
I thought the issue might be with size but I cut the condition to prevent it from uploading with no luck. I feel like I might be missing something in the foreach but I am completely stuck. I appreciate your help!
Here is the form I am using to upload:
<form method="post" enctype="multipart/form-data" name="formUploadFile" id="uploadForm" action="edit-images.php">
<div class="form-group">
<label for="exampleInputFile">Select file to upload:</label>
<input type="file" id="exampleInputFile" name="files[]" multiple="multiple">
<p class="help-block"><span class="label label-info">Note:</span> Please, Select the only images (.jpg, .jpeg, .png, .gif)</p>
</div>
<button type="submit" class="btn btn-primary" name="btnSubmit" >Start Upload</button>
</form>

uploading video file not working

I want to upload video files in php for that i am using following code
PHP
$newUploadDir = "c://video";
$idx = "file";
if (isset($_FILES[$idx]) && is_array($_FILES[$idx])) {
echo "file set";
foreach ($_FILES[$idx]["error"] as $key => $error) {
echo "loop";
if ($error == UPLOAD_ERR_OK) {
echo "<br/>dd2";
$tmp_name = $_FILES[$idx]["tmp_name"][$key];
$name = $_FILES[$idx]["name"][$key];
$ext1 = explode(".", $name);
$extension = end($ext1);
$newfilename = "test".".".$extension;
$video_types = array('mp4', 'avi','webm');
if (in_array($extension, $video_types)) {
if (move_uploaded_file($tmp_name, $newUploadDir.$newfilename)) {
echo "uploaded to folder";
} else {
echo "Not uploaded to folder";
}
}
} else {
echo "not uploaded $error";
}
}
}
echo "ok";
HTML
<form action="http://localhost/fileupload/video.php" enctype="multipart/form-data" method="post">
<input id="file1" name="file[]" type="file"/>
<input name="userId" type="text" value="2"/>
<input id="Submit" name="submit" type="submit" value="Submit" />
</form>
Output
file setloopnot uploaded 1ok
Video file is not uploading. How to resolve this?
Actually, if you try to upload very large (video) files, probably the upload file size limit will not let you do that. Instead of regular file upload, there are other possibities. For the begining, look at this, this or this.
An other aproach would be to use third party services like Amazon S3, Microsoft Azure, etc.

Validating empty $_FILES

I have a simple register form where the user can upload a profile picture, if the user doesn't it, it should take the default picture name called person-icon.png.
When I register an user and upload a picture it works but if i leave it blank don't do anything and that column is inserted into the DB empty
if(isset($_FILES['image'])){
$img = $_FILES['image']['name'];
}
else if(empty($_FILES['image']['name'])){
$img = 'person-icon.png';
}
I already have tried these options:
Option 1:
if (empty($_FILES['image'])){
$img = 'person-icon.png';
}
else{
$img = $_FILES['image']['name'];
}
Option 2:
if($_FILES["image"]["error"] == 4)
Option 3:
if($_FILES["image"]["name"] == "")
You could check for $_FILE['image']['name'] not equal "" this work;
See code:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="image" id="image">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
<?php
//var_dump($_FILES);
$default_pic =" pic.png";
if (isset($_FILES['image'])){
if($_FILES['image']['name'] != ""){
echo "has pic";
}
else{
$_FILES['image']['name'] = $default_pic;
echo "has no pic";
}
}
?>
In order to check if a file has been uploaded you have to look for the tmp_name, because that is what contains the actual copy of your file content on the server.
I would do something like this:
$file = $_FILES['file']['tmp_name'];
if (!file_exists($file)){
//no image
}
else{
//image
}
You can also check $_FILES as long you don't upload other files in that form:
if(empty($_FILES)){
//no image
}
else{
//image
}
For further information check the official manual of file uploads.
I hope this helped you :)

Multiple File Upload PHP

I use the Following code to upload a single file .With This code I can Upload a single file to the database .I want to make multiple files uploaded by selecting multiple files in a single input type file.What Changes should i make in the code to make it upload multiple files?
<?PHP
INCLUDE ("DB_Config.php");
$id=$_POST['id'];
$fileTypes = array('txt','doc','docx','ppt','pptx','pdf');
$fileParts = pathinfo($_FILES['uploaded_file']['name']);
if(in_array($fileParts['extension'],$fileTypes))
{
$filename = $_FILES["uploaded_file"]["name"];
$location = "E:\\test_TrainingMaterial/";
$file_size = $_FILES["uploaded_file"]["size"];
$path = $location . basename( $_FILES['uploaded_file']['name']);
if(file_exists($path))
{
echo "File Already Exists.<br/>";
echo "Please Rename and Try Again";
}
else
{
if($file_size < 209715200)
{
$move = move_uploaded_file( $_FILES["uploaded_file"]["tmp_name"], $location . $_FILES['uploaded_file']['name']);
$result = $mysqli->multi_query("call sp_upload_file('".$id."','" . $filename . "','".$path."')");
if ($result)
{
do {
if ($temp_resource = $mysqli->use_result())
{
while ($row = $temp_resource->fetch_array(MYSQLI_ASSOC)) {
array_push($rows, $row);
}
$temp_resource->free_result();
}
} while ($mysqli->next_result());
}
if($move)
{
echo "Successfully Uploaded";
}
else
{
echo "File not Moved";
}
}
else
{
echo "File Size Exceeded";
}
}
}
else
{
echo " Invalid File Type";
}
?>
The Html That is used is
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file" id="uploaded_file" style="color:black" /><br/>
</form>
Basically you need to add to input name [] brackets and attribute "multiple"
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file[]" multiple="true" id="uploaded_file" style="color:black" /><br/>
</form>
Now all uploaded file will be available via
$_FILES['uploaded_file']['name'][0]
$_FILES['uploaded_file']['name'][1]
and so on
More info at
http://www.php.net/manual/en/features.file-upload.multiple.php

How can I save an image from a file input field using PHP & MySQL?

How can I save an image safely from a file input field using PHP & MySQL?
Here is the input file field.
<input type="file" name="pic" id="pic" size="25" />
This is a simple example, it should work.
Although you probably want to add checking for image types, file sizes, etc.
<?php
$image = $_POST['pic'];
//Stores the filename as it was on the client computer.
$imagename = $_FILES['pic']['name'];
//Stores the filetype e.g image/jpeg
$imagetype = $_FILES['pic']['type'];
//Stores any error codes from the upload.
$imageerror = $_FILES['pic']['error'];
//Stores the tempname as it is given by the host when uploaded.
$imagetemp = $_FILES['pic']['tmp_name'];
//The path you wish to upload the image to
$imagePath = "images/";
if(is_uploaded_file($imagetemp)) {
if(move_uploaded_file($imagetemp, $imagePath . $imagename)) {
echo "Sussecfully uploaded your image.";
}
else {
echo "Failed to move your image.";
}
}
else {
echo "Failed to upload your image.";
}
?>
http://php.net/file_upload covers just about everything you need to know.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$tmpFile = $_FILES['pic']['tmp_name'];
$newFile = '/new_location/to/file/'.$_FILES['pic']['name'];
$result = move_uploaded_file($tmpFile, $newFile);
echo $_FILES['pic']['name'];
if ($result) {
echo ' was uploaded<br />';
} else {
echo ' failed to upload<br />';
}
}
?>
<form action="" enctype="multipart/form-data" method="POST>
<input type="file" name="pic" />
<input type="submit" value="Upload" />
</form>

Categories