I am trying to upload multiple photos of a new user to a new directory on the server, assigning a directory name for that person based in their name and ID in the DB. A path to the new directory is added to a field in the DB, so that these photos can be referenced later. All other DB functionality is working except for this.
I haven't worked on this project for a good 6 months, and this feature was working at some stage. I am unsure what I have messed up. At present I get '0 files uploaded successfully', with no new directory or reference being created. DB connection must be fine as other info earlier in the code not included here is adding without an issue.
Please help. I am pulling at what little hair I have left!
$count = 0;
$valid_formats = array("jpg", "png");
$max_file_size = 1024*5000;
$lastID = $mysqli->insert_id;
$path = '../img/gallery/'.$lastID.'_'.$displayName.'/';
$path2 = './img/gallery/'.$lastID.'_'.$displayName.'/';
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to execute all files
foreach ($_FILES['photoUploader']['name'] as $f => $name) {
if ($_FILES['photoUploader']['error'][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES['photoUploader']['error'][$f] == 0) {
if ($_FILES['photoUploader']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($displayName, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
else { // No error found!
// Create new directory based on unique ID and display name
if (!is_dir($path)) {
mkdir($path, 0777, true);
}
// move temporary files to permanent location
if(move_uploaded_file($_FILES["photoUploader"]["tmp_name"][$f], $path.$name))
$count++; // Number of successfully uploaded file
// add image folder url to db for future use
$imageUrlQuery = "UPDATE models SET photoLocation=? WHERE id=$lastID";
$imageUrlstmt = $mysqli->prepare($imageUrlQuery);
$imageUrlstmt->bind_param('s', $path2);
$imageUrlstmt->execute();
}
}
}
echo $count . " file(s) uploaded successfully!";
Set form to:
multipart/form-data
Cluster upload items: photos[ ]
<input type="file" name="photos[]" multiple="multiple" id="multipic"/>
<label for="multipic"><btn> Select 3 Photos </btn></label>
Handle Files
foreach($_FILES['photos']['tmp_name'] as $key => $tmp_name ){
$file_name = $_FILES['photos']['name'][$key];
$file_tmp = $_FILES['photos']['tmp_name'][$key];
$file_size = $_FILES['photos']['size'][$key];
$photo1="dir/where/photos/go/";
$photo1=$photo1 . basename($_FILES['photos']['name'][0]);
$fz1=$_FILES['photos']['size'][0];
if(move_uploaded_file($_FILES['photos']['tmp_name'][0], $photo1)) {
/* do whatever you like here */ }
$photo2 ...
$photo3 ...
}
You can do this for each item: [0] [1] [2], etc.
this is going to seem stupid. It was a simple oversight.....
elseif( ! in_array(pathinfo($displayName, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
$displayName needed changing to $name. That was it. Sigh......
Related
I have some code running on my site which works well to upload single files from file input form elements - but I now need a multiple file input form element to accept more than 1 file and upload them all to the server and store the details of the filenames uploaded in a comma separated string... Any ideas on how to make this work with the code I am using below:
form field:
<input name="logoexamples[]" id="blogoexamples" type="file" class="textInput" value="notrelevant" multiple>
PHP code (that works to accept 1 file uploaded, but not more than 1....?):
<?php
// initialize output;
$output = true;
// valid extensions
$ext_array = array('pdf', 'txt', 'doc', 'docx', 'rtf', 'jpg', 'jpeg', 'png', 'eps', 'svg', 'gif', 'ai');
// create unique path for this form submission
//$uploadpath = 'assets/uploads/';
// you can create some logic to automatically
// generate some type of folder structure here.
// the path that you specify will automatically
// be created by the script if it doesn't already
// exist.
// UPLOAD TO FOLDER IN /ASSETS/UPLOADS/ WITH ID OF THE PARENT PROJECT FOLDER RESOURCE
// Get page ID
// $pageid = $modx->resource->get('id');
// $uploadpath = 'assets/uploads/'.$pageid.'/';
// Get parent page title
$parentObj = $modx->resource->getOne('Parent');
$parentpageid = $parentObj->get('pagetitle');
$uploadpath = 'assets/uploads/'.$parentpageid.'/';
// get full path to unique folder
$target_path = $modx->config['base_path'] . $uploadpath;
// get uploaded file names:
$submittedfiles = array_keys($_FILES);
// loop through files
foreach ($submittedfiles as $sf) {
// Get Filename and make sure its good.
$filename = basename( $_FILES[$sf]['name'] );
// Get file's extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$ext = mb_strtolower($ext); // case insensitive
// is the file name empty (no file uploaded)
if($filename != '') {
// is this the right type of file?
if(in_array($ext, $ext_array)) {
// clean up file name and make unique
$filename = mb_strtolower($filename); // to lowercase
$filename = str_replace(' ', '_', $filename); // spaces to underscores
$filename = date("Y-m-d_G-i-s_") . $filename; // add date & time
// full path to new file
$myTarget = $target_path . $filename;
// JWD - save uploaded filenames as a session var to get it on the redirect hook
$_SESSION['briefing_submittedfiles_' . $sf] = 'http://www.example.com/assets/uploads/'.$parentpageid.'/'.$filename;
// create directory to move file into if it doesn't exist
mkdir($target_path, 0755, true);
// is the file moved to the proper folder successfully?
if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
// set a new placeholder with the new full path (if you need it in subsequent hooks)
$modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
// set the permissions on the file
if (!chmod($myTarget, 0644)) { /*some debug function*/ }
} else {
// File not uploaded
$errorMsg = 'There was a problem uploading the file.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
} else {
// File type not allowed
$errorMsg = 'Type of file not allowed.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
// if no file, don't error, but return blank
} else {
$hook->setValue($sf, '');
}
}
return $output;
I had something similar coded for my website, this code is super old so don't judge or use it directly. Just an example.
if(isset($_POST['upload'])){
for($i=0; $i<count($_FILES['upload']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "../FOLDER NAME/" . $_FILES['upload']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
copy($newFilePath, $newFilePath1);
$filename = basename($_FILES['upload']['name'][$i]);
// add $filename to list or database here
$result = "The files were uploaded succesfully.";
}else{
$result = "There was an error adding the files, please try again!";
}
}
}
I'm working on a project but when testing the upload pictures function it gives me errors all the way. The site is on a Portal.website.com link (so not www, dunno if that matters)
Anyhow here is the message I get:
Warning: move_uploaded_file(img/uploads/IMG_20160402_244056496.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in /home/xxx/domains/website.com/public_html/portal/artikeltoevoegen.php on line 33
And
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpf277z2' to 'img/uploads/IMG_20160402_244056496.jpg' in /home/xxx/domains/website.com/public_html/portal/artikeltoevoegen.php on line 33
And here is the php part the form itself is pretty standard and works flawlessly
if (isset($_POST['uploadArticle']))
{
$title = $_POST['title'];
$article = $_POST['article'];
$files = $_FILES['files'];
$valid_formats = array("jpg", "png", "gif", "zip", "bmp");
$max_file_size = 1024*1000; //1000 kb
$count = 0;
foreach ((array) $_FILES['files']['name'] as $f => $name)
{
if ($_FILES['files']['error'][$f] == 4)
{
continue; // Skip file if any error found
}
if ($_FILES['files']['error'][$f] == 0)
{
if ($_FILES['files']['size'][$f] > $max_file_size)
{
$message[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) )
{
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
else
{
// No error found! Move uploaded files
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f],"img/uploads/".$name))
{
$count++; // Number of successfully uploaded file
echo $count;
}
}
}
}
}
Okay so it happened to be the server permissions for the folders I was trying to write too. I changed it from 755 to 777 now it works just fine.
Hope someone can use this info
As the error suggests the path you are passing to move_uploaded_file does not exist.
If the img folder is in the same directory as the php file you are calling move_uploaded_file from, try using a relative url:
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f],"./img/uploads/".$name))
by adding ./ in front of img
I've recently encountered some issues while trying to upload some images with PHP and the move_uploaded_file function.
The first move_uploaded_file works perfectly but not the second one.
I have put this on top of my page but it displaying anything:
ini_set('display_errors', 1);
error_reporting(E_ALL|E_STRICT);
Here is my code:
$folder = 'product/'.$savedProduct -> getId();
//First I create the list of my path, starting with my main picture
$imagePath[0] = '../uploaded_pics/'.$folder.'/'.$_FILES['main_image']['name'];
$thumbnailPath[0] = '../uploaded_pics/'.$folder.'/thumbnail/'.$_FILES['main_image']['name'];
$tmp_path[0] = $_FILES['main_image']['tmp_name'];
for ($cpt = 1; $cpt < 6; $cpt ++) { //Because I only want 5 pics and start at 1 so I won't erase the Main Image datas.
if (isset($_FILES['thumbnail_image_'.$cpt])) { //It refer to the HTML file input name thumbnail_image_someNumber
$imagePath[$cpt] = '../uploaded_pics/'.$folder.'/'.$_FILES['thumbnail_image_'.$cpt]['name'];
$thumbnailPath[$cpt] = '../uploaded_pics/'.$folder.'/thumbnail/'.$_FILES['thumbnail_image_'.$cpt]['name'];
$tmp_path[$cpt] = $_FILES['thumbnail_image_'.$cpt]['tmp_name'];
}
}
//Then I check-create my folders
if (!is_dir('../uploaded_pics/'.$folder)) {
mkdir('../uploaded_pics/'.$folder, 0777, true);
}
if (!is_dir('../uploaded_pics/'.$folder.'/thumbnail')) {
mkdir('../uploaded_pics/'.$folder.'/thumbnail', 0777, true);
}
//And Then I save my pictures
if (count($imagePath) > 1) { //If I have more than just the Main Image
for ($cpt = 0; $cpt < count($imagePath); $cpt ++) {
$image = new Image('', $imagePath[$cpt], $thumbnailPath[$cpt]);
saveImage($image, $bdd); //Save the path in MySQL database, this works fine
move_uploaded_file($tmp_path[$cpt], $imagePath[$cpt]);
move_uploaded_file($tmp_path[$cpt], $thumbnailPath[$cpt]);
//And Here happened the problem
}
}
Only the first move_uploaded_file is working, the next one doesn't make anything. I tried to var_dumped the arrays and they all contains the proper datas. I also tried to invert the two move_uploaded_file and so they works well separatly, just not when they are both "actived".
EDIT/SOLUTION:
Just need to replace the second move_uploaded_file by:
copy($imagePath[$cpt], $thumbnailPath[$cpt]);
I'll try to resize the images later, thanks guys.
This moves the file from $tmp_path[$cpt] to $imagePath[$cpt]
move_uploaded_file($tmp_path[$cpt], $imagePath[$cpt]);
This attempts to move the file from $tmp_path[$cpt] to $thumbnailPath[$cpt]
move_uploaded_file($tmp_path[$cpt], $thumbnailPath[$cpt]);
But you've already moved it in the first line, so there's nothing to move! Instead you have to copy it from its new location:
copy($imagePath[$cpt], $thumbnailPath[$cpt]);
TRY IT
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Multiple File Ppload with PHP</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="files[]" multiple="multiple" accept="image/*" />
<input type="submit" value="Upload!" />
</form>
</body>
</html>
<?php
$valid_formats = array("jpg", "png");
$max_file_size = 1280*1024;
$path = "uploads/"; // Upload directory
$count = 0;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute all files
foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
else{ // No error found! Move uploaded files
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name))
$count++; // Number of successfully uploaded file
}
}
}
}
?>
move_uploaded_file() works like "cut" and "paste". Your first call has already moved the original file.
It's working perfectly with this combo:
move_uploaded_file($tmp_path[$cpt], $imagePath[$cpt]);
copy($imagePath[$cpt], $thumbnailPath[$cpt]);
the following piece of code recognizes the image through getimagesize() but then when i try to move the file to an uploaded folder it moves the file there but says it's an array? im confused because im not setting any variables as an array?
<?php
//simple image check using getimagesize() instead of extensions
if($_FILES){
$empty_check = getimagesize($_FILES['file']['tmp_name']);
if(empty($empty_check)){
echo 'this is not an image';
}
else{
echo 'you have uploaded ' . explode('.',$_FILES['file']['name'])[0].'
and it is a ' . explode('.',$_FILES['file']['name'])[1].'.';
//an example of how i would extract the extension
$target = "C:\\xampp\\htdocs";
move_uploaded_file($_FILES['file']['tmp_name'], $target.'\\'.$_FILES['file']);
}
}
?>
$_FILES['file']
is an array, you're trying to use it as the target filename;
comment of deceze.
Echo the file you want to move/save, then you should see what he mentioned..
When using move_uploaded_file you get to pick the filename, so you can pick anything you want.
When you upload the file, its put into a temporary directory with a temporary name, move_uploaded_file() allows you to move that file and in that you need to set the name of the file as well.
Use this coding for multiple file uploading....
//For Multiple file uploading
if (isset($_FILES['photo']) != "") {
$errors = array();
foreach($_FILES['photo']['tmp_name'] as $key = > $tmp_name) {
$file_name = $_FILES['photo']['name'][$key];
$file_size = $_FILES['photo']['size'][$key];
$file_tmp = $_FILES['photo']['tmp_name'][$key];
$file_type = $_FILES['photo']['type'][$key];
//change the image extension as png
$fileExt = "png";
$photorename[$key] = strtolower($property_code.
'_'.$key.
'.'.$fileExt);
if ($file_size > 2097152) {
$errors[] = 'File size must be less than 2 MB';
}
//Path of Uploading file
$target = "images_property";
if (empty($errors) == true) {
if (is_dir($target) == false) {
mkdir("$target", 0700); // Create directory if it does not exist
}
if (file_exists("$target/".$photorename[$key])) {
unlink("$target/".$photorename[$key]);
}
move_uploaded_file($file_tmp, "$target/".$photorename[$key]);
} else {
print_r($errors);
}
}
if (empty($errors)) {
echo "Success";
}
}
I found this code, to upload multiple files
http://www.w3bees.com/2013/02/multiple-file-upload-with-php.html?showComment=1390161630156#c8075663254636569559
I modified a little bit the code for obtain a upload/subdirectories folder with unique id for each one of the sets uploads ;so the files also gets a unique id.
$dir=substr(uniqid(),-7); // Uniqid for subdirectory
$path = "uploads/$dir/"; // uploads/subdirectory/
mkdir($path, 0700); // Make directory
$valid_formats = array("jpg", "png", "jpeg", "kml");
$max_file_size = 2097152;
$count = 0;
// Loop $_FILES to exeicute all files
foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
else{ // No error found! Move uploaded files
$ext = pathinfo($_FILES['files']['name'][$f], PATHINFO_EXTENSION);
$uniq_name = substr(uniqid(),-5) . '.' .$ext;
$dest = $path . $uniq_name;
move_uploaded_file($_FILES["files"]["tmp_name"][$f], $dest);
mysqli_query($dbc, "INSERT INTO files (code, name, path, type) VALUES ('$dir','$uniq_name','$dest','$ext')" );
$count++; //Number of successfully uploaded file
}
}
}
}
This process is carried out correctly.
I want after move_upload_file, get all paths(url) of files uploads.
But I get inserted on the database only path first file selected... the other paths files are upload correctly, but not inserted on the database.
Sorry for my bad english, it's not my first language. I hope you can help me.
Try something as
$sql_error = ''; // add this before you start the loop
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $dest)){
$qry = "INSERT INTO files (code, name, path, type) VALUES ('$dir','$uniq_name','$dest','$ext')" ;
$result = mysqli_query($dbc, $qry);
if ( false===$result ) {
$sql_error .= 'Error in the query '.$qry.' Error Desc :'.mysqli_error($dbc).'<br /><br />' ;
}
}
Finally add
echo $sql_error ;
At the end of the file , so if there is any error it will show you the error in the query.
Also by adding the query inside
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $dest)){}
means you are adding only if the files are getting uploaded.