Upload image file errror after 19 images in php - php

I am using a php to upload multiple images around 30 or so. I have compressed the image to 100kb before uploading. When I try to upload images via Android then I don't get any error. Only 19 images are transferred to the server but not the rest. I am using cPanel shared hosting account and it's not a website only php.
How can I upload more than 19 images?
/////// images
if (!empty($images_names_str)) {
if( get_magic_quotes_gpc() ) {
$images_names_str = stripslashes( $images_names_str );
}
$newstr = json_decode( $images_names_str,true );
$i = -1;
foreach($newstr as $item) { //foreach element in $arr
$i++;
$name = $item['name']; //etc
$path = $item['path'];
$file_path1 = "/home/public_html/images/";
// Use
if ($_FILES['image'.$i]['error'] === UPLOAD_ERR_OK) {
//uploading successfully done
$moveResult = move_uploaded_file($_FILES['image'.$i]['tmp_name'], $file_path1.$name);
fputs($fp,"File has been moved from to" . $file_path1.$name. "\n");
} else {
fputs($fp,$_FILES['image'.$i]['error'].$i." ERROR: File not moved correctly".$file_path1.$name. "\n");
}
}
echo "done";
}

Related

Upload fails "move uploaded file"

First off, the upload folder is given 777, and my old upload script works, so the server accepts files. How ever this is a new destination.
I use krajee bootstrap upload to send the files. And I receive a Jason response. The error seems to be around move uploaded file. I bet it's a simple error from my side, but I can't see it.
<?php
if (empty($_FILES['filer42'])) {
echo json_encode(['error'=>'No files found for upload.']);
// or you can throw an exception
return; // terminate
}
// get the files posted
$images = $_FILES['filer42'];
// a flag to see if everything is ok
$success = null;
// file paths to store
$paths= [];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
$ext = explode('.', basename($filenames[$i]));
$target = "uploads" . DIRECTORY_SEPARATOR . md5(uniqid()) . "." . array_pop($ext);
if(move_uploaded_file($_FILES["filer42"]["tmp_name"][$i], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
}
// check and process based on successful status
if ($success === true) {.
$output = [];
$output = ['uploaded' => $paths];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
// delete any uploaded files
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
// return a json encoded response for plugin to process successfully
echo json_encode($output);
?>
I think field name is the issue. Because you are getting image name with filer42 and upload time, you are using pictures.
Please change
$_FILES["pictures"]["tmp_name"][$i]
to
$_FILES["filer42"]["tmp_name"][$i]
And check now, Hope it will work. Let me know if you still get issue.
The error is not in this script but in the post.
I was using <input id="filer42" name="filer42" type="file">
but it have to be <input id="filer42" name="filer42[]" type="file" multiple>
as the script seems to need an arrey.
It works just fine now.

memory limit and slow upload using class upload php

i am creating upload image using class upload from https://www.verot.net/
my problem: output image 2 (real photo and edit-resize photo).
all work but it wasting time while processing upload.
and when i check size real photo before and after upload, size not same.
$counter=1;
foreach ($files as $file) {
$handle = new Upload($file);
if ($handle->uploaded)
{
$handle->Process("real");
$handle->dir_chmod = 0777;
//$handle->jpeg_quality = 85;
//jenis file yang diijinkan
$handle->allowed = array('image/*');//VALIDASI UPLOAD GAMBAR
//$handle->image_resize = false;
/*----first-START----*/
if ($handle->processed) {
${'pathPhotoReal'.$counter} = 'real/'.$handle->file_dst_name;
echo ${'pathPhotoReal'.$counter}."<br>";
${'namaFoto'.$counter} = $_POST['text'.$counter];
echo ${'namaFoto'.$counter}."<br>";
}
else {
// one error occured
echo ' Error: ' . $handle->error . '';
}
/*----first-FINISH----*/
// we now process the image a second time, with some other settings
//$handle->allowed = array('image/*');
$handle->image_ratio = true;
$handle->image_ratio_fill = true;
$handle->image_resize = true;
$handle->image_x = 300;
$handle->image_y = 300;
$handle->Process('edit');
/*----second-START----*/
if ($handle->processed) {
${'pathFotoEdit'.$counter} = 'edit/'.$handle->file_dst_name;
echo ${'pathFotoEdit'.$counter}."<br>";
}
else {
// one error occured
echo ' Error: ' . $handle->error . '';
}
/*----second-FINISH----*/
$counter = $counter + 1;
//$handle->clean();
else {
// if we're here, the upload file failed for some reasons
// i.e. the server didn't receive the file
echo ' File not upload ' . $handle->error . '';
echo($handle->log);
}
}
in my last code using else{echo ' File not upload ' . $handle->error . '';}
it always show, inside folder pathPhoto have saved photo inside. i think upload success.
try changing the folder permissions from filezilla.
With this you can know if the server allows you to make those persmisos

bootstrap fileinput, show uploaded files and delete them

how can i show and delete previously uploaded files with the great bootstrap-fileinput plugin from krajee, my code is:
html:
<script>
$("#images").fileinput({
uploadAsync: true,
uploadUrl: "upload.php"
}).on("filebatchselected", function(event, files) {
$("#images").fileinput("upload");
});
</script>
upload.php:
<?php
if (empty($_FILES['images'])) {
echo json_encode(['error'=>'No files found for upload.']);
return;
}
$images = $_FILES['images'];
$success = null;
$paths= [];
$filenames = $images['name'];
for($i=0; $i < count($filenames); $i++){
$ext = explode('.', basename($filenames[$i]));
$target = "uploads" . DIRECTORY_SEPARATOR . basename($filenames[$i]);
if(move_uploaded_file($images['tmp_name'][$i], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
}
if ($success === true) {
$output = ['uploaded' => $paths];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
echo json_encode($output);
?>
Has anyone an idea ? i think i have to scan the uploads dir and send it back with json or use $output, but i dont know how to this ?
Since you are using json to upload files, you can use it to delete them too. Make another ajax call to the server by sending an array of the image URLs that you want to remove. Then with PHP you can simply unlink them.
So for example: http://jsfiddle.net/fdzsLa0k/1/
var paths = []; // A place to store all the URLs
// Loop through all images
// You can do it for a single image by using an id selector and skipping the looping part
$('.uploaded-img').each(function(i, v) {
paths.push(this.src); // Save found image paths
})
console.log(paths); // Preview the selection in console
// Send the URLs to the server for deletion
$.ajax({
method: 'post',
data: { images: paths },
url: 'ajax.php' // Replace with your ajax-processing file
}).success(function(response) {
console.log(response); // Do fun stuff: notify user, remove images from the loaded HTML
});
uuuhh, the fileinput script need php version higher than 5.3.3, because the plesk panel of my hosting provider supports only 5.3.3 i have the problems, since 11.5 plesk supports multiple php version for each domain on the server, now with php 5.6 everything works great !

can't upload multiple images iin zend freamework on server

i have a problem with upload mutilply files using zend framework on server
actually my code works correctly on localhost but on remote server it gives me application error message
my host is ipage.com
$upload = new Zend_File_Transfer_Adapter_Http();
$upload->setDestination('projects\\'.$_pId);
// $_pid is my project folder where all files related to it uploded
$files = $upload->getFileInfo();
$i = 1;$g = 1;
foreach ($files as $file => $info)
{
// i have three kinds of images
// innerfinishingphotos_ images which can be more than 1 file eg :innerfinishingphotos_1, innerfinishingphotos_2, innerfinishingphotos_3.
// outerfinishingphotos_ images which can be more than 1 file eg :outerfinishingphotos_1, outerfinishingphotos_2, outerfinishingphotos_3.
// _main_photo image an image.
// here i made if statements to determine which file came from which input file
if( $info == $files["innerfinishingphotos_".$i] && $info["name"] == $files["innerfinishingphotos_".$i]["name"] && !empty( $info["name"] ) )
{
$filename = "inner_finishing".$_pId.uniqid().$files["innerfinishingphotos_".$i]["name"];
$upload->addFilter('Rename', $filename, $files["innerfinishingphotos_".$i]);
$photodata = Array ("project_id"=> $_pId, "photo_link"=> "/projects/".$_pId."/".$filename, "photo_name"=> "inner_finishing");
$projectModel->addInProjectGalary($photodata);
$i++;
}
else if( $info == $files["outerfinishingphotos_".$g] && $info["name"] == $files["outerfinishingphotos_".$g]["name"] &&!empty( $info["name"] ) )
{
$filename = "outer_finishing".$_pId.uniqid().$files["outerfinishingphotos_".$g]["name"];
$upload->addFilter('Rename', $filename, $files["outerfinishingphotos_".$g]);
$photodata = Array ("project_id"=> $_pId, "photo_link"=> "/projects/".$_pId."/".$filename, "photo_name"=> "outer_finishing");
$projectModel->addInProjectGalary($photodata);
$g++;
}
else if ($info == $files["_main_photo"] && !empty( $info["name"] ))
{
$filename = "main_photo".$_pId.uniqid().$files["_main_photo"]["name"];
$upload->addFilter('Rename', $filename, $files["_main_photo"]);
$photodata = Array ("project_id"=> $_pId, "photo_link"=> "/projects/".$_pId."/".$filename, "photo_name"=> "project_photo");
$projectModel->addInProjectGalary($photodata);
}
//then i receive the image
if($upload->isValid($file))
{
try {
$upload->receive($file);
}
catch (Exception $e) {
echo "upload exteption";
}
}
}
i tested this code and i works correctly on localhost and all images uploaded and their data entered my database
but on my remote host 'ipage.com' not work.
please guys help me
after many hours trying, i solved the problem , it wase in this line
$upload->setDestination('projects\\'.$_pId);
changing it to
$upload->setDestination('projects/'.$_pId);
thank you mr. Tim Fountain

Passing uploaded files to another part of the script for onward processing

I have searched the forum but the closest question which is about the control stream did not help or I did not understand so I want to ask a different question.
I have an html form which uploads multiples files to a directory. The upload manager that handles the upload resides in the same script with a different code which I need to pass the file names to for processing.
The problem is that the files get uploaded but they don't get processed by the the other code. I am not sure about the right way to pass the $_FILES['uploadedFile']['tmp_name']) in the adjoining code so the files can be processed with the remaining code. Please find below the script.
More specif explanation:
this script does specifically 2 things. the first part handles file uploads and the second part starting from the italised comment extracts data from the numerous uploaded files. This part has a variable $_infile which is array which is suppose to get the uploaded files. I need to pass the files into this array. so far I struggled and did this: $inFiles = ($_FILES['uploadedFile']['tmp_name']); which is not working. You can see it also in the full code sample below. there is no error but the files are not passed and they are not processed after uploading.
<?php
// This part uploads text files
if (isset($_POST['uploadfiles'])) {
if (isset($_POST['uploadfiles'])) {
$number_of_uploaded_files = 0;
$number_of_moved_files = 0;
$uploaded_files = array();
$upload_directory = dirname(__file__) . '/Uploads/';
for ($i = 0; $i < count($_FILES['uploadedFile']['name']); $i++) {
//$number_of_file_fields++;
if ($_FILES['uploadedFile']['name'][$i] != '') { //check if file field empty or not
$number_of_uploaded_files++;
$uploaded_files[] = $_FILES['uploadedFile']['name'][$i];
//if (is_uploaded_file($_FILES['uploadedFile']['name'])){
if (move_uploaded_file($_FILES['uploadedFile']['tmp_name'][$i], $upload_directory . $_FILES['uploadedFile']['name'][$i])) {
$number_of_moved_files++;
}
}
}
}
echo "Files successfully uploaded . <br/>" ;
echo "Number of files submitted $number_of_uploaded_files . <br/>";
echo "Number of successfully moved files $number_of_moved_files . <br/>";
echo "File Names are <br/>" . implode(',', $uploaded_files);
*/* This is the start of a script to accept the uploaded into another array of it own for* processing.*/
$searchCriteria = array('$GPRMC');
//creating a reference for multiple text files in an array
**$inFiles = ($_FILES['uploadedFile']['tmp_name']);**
$outFile = fopen("outputRMC.txt", "w");
$outFile2 = fopen("outputGGA.txt", "w");
//processing individual files in the array called $inFiles via foreach loop
if (is_array($inFiles)) {
foreach($inFiles as $inFileName) {
$numLines = 1;
//opening the input file
$inFiles = fopen($inFileName,"r");
//This line below initially was used to obtain the the output of each textfile processed.
//dirname($inFileName).basename($inFileName,'.txt').'_out.txt',"w");
//reading the inFile line by line and outputting the line if searchCriteria is met
while(!feof($inFiles)) {
$line = fgets($inFiles);
$lineTokens = explode(',',$line);
if(in_array($lineTokens[0],$searchCriteria)) {
if (fwrite($outFile,$line)===FALSE){
echo "Problem w*riting to file\n";
}
$numLines++;
}
// Defining search criteria for $GPGGA
$lineTokens = explode(',',$line);
$searchCriteria2 = array('$GPGGA');
if(in_array($lineTokens[0],$searchCriteria2)) {
if (fwrite($outFile2,$line)===FALSE){
echo "Problem writing to file\n";
}
}
}
}
echo "<p>For the file ".$inFileName." read ".$numLines;
//close the in files
fclose($_FILES['uploadedFile']['tmp_name']);
fflush($outFile);
fflush($outFile2);
}
fclose($outFile);
fclose($outFile2);
}
?>
Try this upload class instead and see if it helps:
To use it simply Upload::files('/to/this/directory/');
It returns an array of file names that where uploaded. (it may rename the file if it already exists in the upload directory)
class Upload {
public static function file($file, $directory) {
if (!is_dir($directory)) {
if (!#mkdir($directory)) {
throw new Exception('Upload directory does not exists and could not be created');
}
if (!#chmod($directory, 0777)) {
throw new Exception('Could not modify upload directory permissions');
}
}
if ($file['error'] != 0) {
throw new Exception('Error uploading file: '.$file['error']);
}
$file_name = $directory.$file['name'];
$i = 2;
while (file_exists($file_name)) {
$parts = explode('.', $file['name']);
$parts[0] .= '('.$i.')';
$new_file_name = $directory.implode('.', $parts);
if (!file_exists($new_file_name)) {
$file_name = $new_file_name;
}
$i++;
}
if (!#move_uploaded_file($file['tmp_name'], $file_name)) {
throw new Exception('Could not move uploaded file ('.$file['tmp_name'].') to: '.$file_name);
}
if (!#chmod($file_name, 0777)) {
throw new Exception('Could not modify uploaded file ('.$file_name.') permissions');
}
return $file_name;
}
public static function files($directory) {
if (sizeof($_FILES) > 0) {
$uploads = array();
foreach ($_FILES as $file) {
if (!is_uploaded_file($file['tmp_name'])) {
continue;
}
$file_name = static::file($file, $directory);
array_push($uploads, $file_name);
}
return $uploads;
}
return null;
}
}

Categories