unable to upload files widthout database entry [duplicate] - php

I have tried reading multiple tutorials, the PHP documentation and have no idea what I am doing.
Here is my form
<form action="beta_upload.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="20971520" /><!-- 20 Meg -->
<input type="file" name="file[]" />
<input type="file" name="file[]" />
<input type="file" name="file[]" />
<input type="submit" value="submit" name="submit" />
</form>
Now when I send that through here:
<?php
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$username = preg_replace('/[^(\x20-\x7F)]*/','', $username);
$password = preg_replace('/[^(\x20-\x7F)]*/','', $password);
$name = preg_replace('/[^(\x20-\x7F)]*/','', $name);
$email = preg_replace('/[^(\x20-\x7F)]*/','', $email);
$upload_dir = '/beta_images/';
print_r($_FILES);
foreach ($_FILES['files']['error'] as $key => $error) {
if($error == UPLOAD_ERR_OK) {
$check_name = $_FILES['files']['name'];
$filetype = checkfiletype($check_name, 'jpg,jpeg');
$temp_name = $_FILES['files']['tmp_name'][$key];
$image_name = 'image_' . $name . '1';
move_uploaded_file($tmp_name, $upload_dir . $image_name);
}
}
It brings back
Warning: Invalid argument supplied for foreach() in /blabla on line 18
I don't understand foreachs all too well, and when I print_r the array it dosen't help me one bit.
Would someone be so kind to help me out.
Thanks.

You'd better follow this tutorial: http://www.w3schools.com/php/php_file_upload.asp
foreach ($_FILES['file'] as $file) {
if($file['error'] == UPLOAD_ERR_OK) {
$check_name = $file['name'];
// I assume you have to use the file type here, not name
$filetype = checkfiletype($file['type'], 'jpg,jpeg');
$temp_name = $file['tmp_name'];
$image_name = 'image_' . $file['name'] . '1';
move_uploaded_file($tmp_name, $upload_dir . $image_name);
}
}
Your files are in $_FILES['files'] so using foreach you have to go over each element/file and take its data.

Related

how can uploaded multi images in this class [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i want to upload multi images in my database just url images the code is work fine but i can upload just one image i need to upload 3 images i have in database table e_img - e_img2 - e_img3 how can upload images url in 3 columns
this my class upload :
<?php
class Upload {
private $allowedExts = array('doc','docx','pdf','txt','jpg','png');
private $maxSize;
private $file;
private $uploadsDirecotry;
private $fileUrl;
private $filenames = array();
function __construct($file,$allowedExts,$uploadsDirecotry,$maxSize){
if(is_array($allowedExts) AND is_int($maxSize)){
$this->file = $file;
$this->allowedExts = $allowedExts;
$this->maxSize = $maxSize;
$this->uploadsDirecotry = $uploadsDirecotry;
}else{
throw new Exception("File extension must be in an array and max size value must be intger value.");
}
}
function uploadFiles(){
$file = $this->file;
$allowedExts = $this->allowedExts;
$maxsize = $this->maxSize;
$uploadsDir = $this->uploadsDirecotry;
for($i = 0; $i < count($file['name']); $i++){
$errors = array();
// print_r($_FILES);
$filename = $file['name'][$i];
$fileext = strtolower(end(explode('.',$filename)));
$filesize = $file['size'][$i];
$filetmpname = $file['tmp_name'][$i];
if(in_array($fileext, $allowedExts) === FALSE){
$errors[] = "Extension in sot allowed";
}
if($filesize > $maxsize){
$errors[] = "File size must be less than {$maxsize} KB !";
}
if(empty($errors)){
$random = rand(0,199);
$this->fileUrl = $random . "_" . date("d-m-Y") . "_" . $filename;
$destination = $uploadsDir. $random."_".date("d-m-Y") . "_" . $filename;
move_uploaded_file($filetmpname, $destination);
$this->filenames[] = $this->fileUrl;
}else{
foreach($errors as $error){
throw new Exception($error);
}
}
} // end for
return TRUE;
}
function getFileUrl()
{
return $this->fileUrl;
}
function getFilesNames()
{
return $this->filenames;
}
}
?>
and this html php file
<?php include 'header.php';
if(isset($_POST['add']))
{
$e_title = $_POST['e_title'];
$e_user = $userRow['user_name'];
try{
include 'models/Upload.php';
$file = $_FILES['e_img'];
$allowedExts = array('jpg','png','gif','jpeg');
$uploadsDirectory = "imgupload/";
$maxSize = 4000000;
$upload = new Upload($file, $allowedExts, $uploadsDirectory, $maxSize);
$upload->uploadFiles();
$e_img = $uploadsDirectory.$upload->getFileUrl();
}catch(Exception $exc){
echo'<div class="alert alert-block alert-danger">fail image uploaded</div>';
exit;}
$insert = $user->insert($e_title,$e_img,$e_user);
echo"<div class='alert alert-block alert-success'>Save success</div>";
exit;
}
?>
<form action='newads.php' method="POST" enctype="multipart/form-data">
<p>إضافة صور </p>
<input type="file" name='e_img[]' id="exampleInputFile">
<input type="submit" name='add' class='btn btn-primary' value='add' />
</form>
<?php include 'footer.php'; ?>
i try this but But it did not succeed
<form action='newads.php' method="POST" enctype="multipart/form-data">
<p>إضافة صور </p>
<input type="file" name='e_img[]' id="exampleInputFile">
<input type="file" name='e_img2[]' id="exampleInputFile">
<input type="file" name='e_img3[]' id="exampleInputFile">
<input type="submit" name='add' class='btn btn-primary' value='add' />
</form>
You do not need to increment the field names in your file fields. That will break the array when PHP receives it. Change to this: (they should all be e_img[]
<input type="file" name='e_img[]' id="exampleInputFile">
<input type="file" name='e_img[]' id="exampleInputFile">
<input type="file" name='e_img[]' id="exampleInputFile">

Error uploading multiple images at the same time

I am trying to upload multiple photos at the same time but there seems to be an error with my script. If for example, I select 10 different photos, one particular image is uploaded 10 times (ignoring the other 9 images). This is the script:
for ($i = 0; $i < count($_FILES["_photo"]["name"]); $i++) {
if (!empty($_FILES['_photo']['name'][$i])) {
if (($_FILES['_photo']['type'][$i] == 'image/jpeg') OR ($_FILES['_photo']['type'][$i] == 'image/png') OR ($_FILES['_photo']['type'][$i] =='image/gif')) {
$upload_folder = "./profile_pix/";
$pic_name = time() . ".jpg";
$pic_path = $upload_folder . $pic_name;
require_once "include/resize.php";
if (move_uploaded_file($_FILES['_photo']['tmp_name'][$i], $pic_path)) {
$image = new Resize($pic_path);
$image->resizeImage(180, 180, 'crop');
$image->saveImage($pic_path);
}
$sql2 = "INSERT INTO photos
(photo, member_id, photo_id)
VALUES
('$pic_name', :session_id, :offer_count)";
$db -> query($sql2, array('session_id' => $_SESSION['id'], 'offer_count' => $offer_count));
}else {
header ("Location: submitoffer.php?err=03");
}
}
HTML:
<input type="file" id="_photo" name="_photo[]" multiple="multiple">
File upload is working fine.
The line
$pic_name = time() . ".jpg";
is always evaluating to same value.
As logically all files are getting uploaded on same time().
Instead use:
$pic_name = $i . '_'. time() . ".jpg";
To add uniqueness.
try this, and you will see what is happening:
<?php
echo "<pre>";
print_r($_FILES);
echo "</pre>";
?>
And in your HTML, make sure you use different names, like this:
<input name="userfile[]" type="file" />
<input name="userfile[]" type="file" />
<input name="userfile[]" type="file" />
Then pick them up by each name. Just inspect the content of $_FILES to understand the structure.
I also advice you serious do some error checking.
100% working and tested code:
upload.php:
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST') {
if(isset($_FILES['files'])){
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if($file_type == "image/jpg" || $file_type == "image/png" || $file_type == "image/jpeg" || $file_type == "image/gif" ) {
move_uploaded_file($file_tmp,"uploads/".$file_name);
}
}
header('location:uploads.html');
}
}
else { header('location:404.html'); }
?>
upload.html
<form id="upload_images" action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" id="file" multiple="true" />
<input type="submit" id="btn_upload" value="U P L O A D" />
</form>

Simple PHP video upload system

Below is a php function of my post method. I am not receiving any errors but however it is not uploading into the folder I have assigned to.
I am using a localhost and there are no errors regarding the database!
<div id="box">
<form method='post' enctype="multipart/form-data">
<?php
if(isset($_FILES['video'])){
$name = $_FILES['video']['name'];
$type = explode('.', $name);
$type = end($type);
$size = $_FILES['video']['name'];
$random_name = rand();
$tmp = $_FILES['video']['tmp_name'];
if($type != 'mp4' && $type != 'mp4' && $type != 'flv'){
$message = "Video Format Not Supported!";
}
else {
move_uploaded_file($tmp, 'videos/'.$random_name.'.'.$type);
mysql_query("INSERT INTO videos VALUES('.' '$name'; 'videos/$random_name.$type')");
$message = "Successfully Uploaded!";
}
echo "$message";
}
?>
Select Video : <br/>
<input type='file' name="video" />
<br/><br/>
<input type="submit" value="Upload" />
</form>

Multiple image upload

i have a problem in multiple image upload, when i upload, there's only 1 image which go to the targeted directory and database. i need two images to go directory and database...any help please?
this is my form
<form action="test.php" method="post" enctype="multipart/form-data">
Keywords: <input style="margin-left:35px;" type="text" name="keyword" /><br />
Name: <input style="margin-left:60px;" type="text" name="name" /><br />
Name2: <input style="margin-left:60px;" type="text" name="name2" /><br />
Categorie: <input style="margin-left:40px;" type="text" name="categorie" /><br />
Lieu: <input style="margin-left:70px;" type="text" name="lieu" /><br /><br />
<input type="file" name="file[]" multiple="multiple" /><input type="file" name="file_2[]" multiple="multiple"/><input type="submit" name="submit" value="Upload" />
</form>
<?php
$connect = mysql_connect("localhost", "root", "");
$select_db = mysql_select_db("yakatrouver_test", $connect);
if(#$_POST['submit']){
$keywords = $_POST['keyword'];
$name = $_POST['name'];
$name2 = $_POST['name2'];
$categorie = $_POST['categorie'];
$lieu = $_POST['lieu'];
$file = $_FILES['file'];
$file_name = $file['name'];
$file_type = $file['type'];
$file_size = $file['size'];
$file_path = $file['tmp_name'];
$file_2 = $FILES['file_2'];
$file_name_2 = $file['name'];
$file_type_2 = $file['type'];
$file_size_2 = $file['size'];
$file_path_2 = $file['tmp_name'];
if($file_name!="" && ($file_type="image/jpeg"||$file_type="image/png"||$file_type="image/gif") && $file_size<=2000000)
if(move_uploaded_file ($file_path, 'pictures_uploaded/' .$file_name))
$query = mysql_query("INSERT INTO `user_input`(keyword, name, categorie, lieu) VALUES ('$keywords', '$name', '$categorie', ' $lieu')");
$query = mysql_query("UPDATE `user_input` set image='pictures_uploaded/$file_name' WHERE `name`='$name'");
if($query == true)
{
echo "file Uploaded";
}
}
$result = mysql_query("SELECT * FROM `user_input` WHERE `image`=''") or die(mysql_error());
while($row = mysql_fetch_array($result))
?>
Try:-
HTML:
<input type="file" name="file[]"/>
<input type="file" name="file[]"/>
<input type="file" name="file[]"/>
PHP:
$file_count = count($_FILES['file']['name']);
for($i=0;$i<$file_count;$i++) {
$file_name = $_FILES['file']['name'][$i];
$file_type = $_FILES['file']['type'][$i];
$file_size = $_FILES['file']['size'][$i];
$file_path = $_FILES['file']['path'][$i];
if($file_name!="" && ($file_type="image/jpeg"||$file_type="image/png"||$file_type="image/gif") && $file_size<=2000000)
if(move_uploaded_file ($file_path, 'pictures_uploaded/' .$file_name))
$query = mysql_query("INSERT INTO `user_input`(keyword, name, categorie, lieu) VALUES ('$keywords', '$name', '$categorie', ' $lieu')");
$query = mysql_query("UPDATE `user_input` set image='pictures_uploaded/$file_name' WHERE `name`='$name'");
if($query == true)
{
echo "file Uploaded";
}
}
} //close the braces accordingly, some seem to be missing in your code
I think it's self-explanatory. It's just looping through your file input array, fetching each file information and processing one at at time.

PHP get names of multiple uploaded files

Hi im trying to create a script to upload multiple files.
everythings works so far and all files are being uploaded.
My problem now is that i need to grap each file name of the uploaded files, so i can insert them in to a datebase.
Here is my html:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image[]" multiple />
<input type="submit" value="upload" />
And here is the php:
if (!empty($_FILES['image'])) {
$files = $_FILES['image'];
for($x = 0; $x < count($files['name']); $x++) {
$name = $files['name'][$x];
$tmp_name = $files['tmp_name'][$x];
$size = $files['size'][$x];
if (move_uploaded_file($tmp_name, "../folder/" .$name)) {
echo $name, ' <progress id="bar" value="100" max="100"> </progress> done <br />';
}
}
}
Really hope someone can help me with this.
/JL
You have your indexes backwards. $_FILES is an array, with an element for each uploaded file. Each of these elements is an associative array with the info for that file. So count($files['name']) should be count($files), and $files['name'][$x] should be $files[$x]['name'] (and similarly for the other attributes. You can also use a foreach loop:
foreach ($_FILES as $file) {
$name = basename($file['name']);
$tmp_name = $file['tmp_name'];
$size = $file['size'];
if (move_uploaded_file($tmp_name, "../folder/" .$name)) {
echo $name, ' <progress id="bar" value="100" max="100"> </progress> done <br />';
}
}
I think the glob() function can help:
<?php
foreach(glob("*.jpg") as $picture)
{
echo $picture.'<br />';
}
?>
demo result:
pic1.jpg
pic2.jpg
pic3.jpg
pic4.jpg
...
be sure to change the file path and extension(s) where necessary.
Thanks for the help, i got it to work by simply creating variables:
$image_1 = (print_r($files['name'][0], true));
$image_2 = (print_r($files['name'][1], true));
$image_3 = (print_r($files['name'][2], true));

Categories