EDIT: got it working, but could still use help. Please see below in edit section.
I've searched all over, but this is really confusing me.
I have a form that allows for multiple file uploads. Each file input is named "track[]" so that way it can get associated into an array. When the form is submitted, I set the file information into an array here:
private $tracks = [];
public function setTracks () {
$length = count($_FILES['track']['name']);
for ($i=0; $i < $length; $i++) {
$this->tracks[$i] = ["file_temp" => $_FILES['track']['tmp_name'][$i],
"file_name" => $_FILES['track']['name'][$i],
"file_size" => $_FILES['track']['size'][$i],
"file_type" => $_FILES['track']['type'][$i],
"target_path" => "tracks/" . $_FILES['track']['name'][$i],
"file_error" => $_FILES['track']['error'][$i]];
}
}
This creates the array just fine, but I'm finding it difficult trying to actually save the file by getting the information I need from this array.
This is my rather basic method for uploading images. How can I adapt this for uploading tracks?
public function uploadImg () {
if ($this->file_size > $this->img_max_size) {
echo "The file size is too large. Please compress it and try again.";
}
if (move_uploaded_file($this->file_temp, "../../" . $this->target_path)) {
echo "The image ". $this->file_name . " has been uploaded successfully!";
}
else {
echo $this->file_error . "There was an error uploading the image, please try again!";
}
}
By the way, I think a foreach loop would be better in both my setTracks and my new uploadTracks methods I'm trying to make, rather than the for loop I am currently implementing, but I wasn't able to figure out how to use one in this case.
EDIT: I'm not sure exactly what I did, but I got this to work. Still, if somebody could help me change my for loop to a foreach it would be greatly appreciated. Here's my method that handles the upload:
public function uploadTrack () {
$length = count($this->tracks);
for ($i=0; $i < $length; $i++) {
if ($this->file_size > $this->track_max_size) {
echo "The file size is too large. Please compress it and try again.";
}
else if (move_uploaded_file($this->tracks[$i]["file_temp"], "../../" . $this->tracks[$i]['target_path'])) {
echo "The image ". $this->file_name . " has been uploaded successfully!";
}
else {
echo $this->file_error . "There was an error uploading the image, please try again!";
}
}
}
Related
On a PHP page, I call an upload function that contains the standard PHP upload procedure. After I call the function, I do a redirect (tried with either window. location or header ()).
The strange thing is that everything works fine a couple of times, then it would not upload anymore (uploadOK won't be 0 either). It would just not move the file onto the server.
Then, I would take out the redirect and the upload would start working again. I put the redirect back in, the upload will still work a couple of times then stop again... Do you have any idea why?
Another strange thing is that, even when it doesn't work, the upload function still returns the correct path+filename, but it would not echo "File ... was uploaded".
I suspect that the problem might be in the move_uploaded_file() function... but it would not return 0, because "Error..." would not be echoed.
Without calling the redirect after the upload, it uploads fine every time.
PHP page:
$_SESSION["temp_file_name"]="../".UploadFisier($_FILES["fileToUpload"], $_SESSION["ID_CLASA"]."_".$id_item."_temp_".UserIdLogat($dbocr)."_", "../teme/", "");
header("Location: trimite_tema_script.php");
The Upload function:
function UploadFisier($file, $sufix, $target_dir, $maxsize)
{
if ($maxsize=="") { $maxsize=3000000; }
if ($target_dir=="") { $target_dir="../upload/"; }
$target_empty_file=$target_dir.$sufix;
$target_file = $target_empty_file.basename($file["name"]);
$uploadOk = 1;
if ($target_file != $target_empty_file)
{
if ($file["size"] > $maxsize)
{
echo "file too large";
$uploadOk = 0;
}
}
else
{
echo "no file selectec.";
$uploadOk = 0;
}
if ($uploadOk == 1)
{
//we overwrite
if (file_exists($target_file))
{
unlink($target_file);
}
if (move_uploaded_file($file["tmp_name"], $target_file))
{
echo "File ". basename( $file["name"]). " was uploaded.";
//we output the path and filename without the "../" at the beginning
$linksave=substr($target_file, 3);
}
else
{
echo "Error....";
}
}
echo "uploadOk ".$uploadOk;
return $linksave;
}
Check the file_uploads value in PHP.ini and confirm that is something like this
file_uploads = On
Wrap a try/catch in your code. maybe you will find out more about the error.
function UploadFisier($file, $sufix, $target_dir, $maxsize)
{
try {
// your code
} catch (\Exception $e) {
echo $e->getMessage();
die();
}
}
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.
I've noticed when uploading multiple files using php, that the array contains data for all input fields from the form.
Suppose I have a from with 3 input fields, and a user were to upload only 2 files, how can I pick out only those two files from the array, maybe using some array function or anything else, so I can only loop thru those files.
I was trying using array_filer on tmp_name but cannot figure how to proceed.
if($_FILES && isset($_POST['handle'])) {
$numFiles = count(array_filter($_FILES['file']['tmp_name']));
if( $numFiles <= 2 ) {
// files that were uploaded will not have a blank value
$filesUploaded = array_filter($_FILES['file']['tmp_name']);
print_r($filesUploaded);// for testing
// loop through the above array
foreach($filesUploaded as $key) {// stuck
//echo each files attributes
echo $_FILES['file']['tmp_name'][$key].'<br>';
echo $_FILES['file']['name'][$key].'<br>';
echo $_FILES['file']['type'][$key].'<br>';
echo $_FILES['file']['size'][$key].'<br>';
echo $_FILES['file']['error'][$key].'<br>';
// proceed with the rest of the processing
}
} else {
echo 'Too may files uploaded';
}
} else {
echo 'Error A';
}
you are expecting like this?
To check whether the file uploaded or not:
if(is_uploaded_file($_FILES['image']['tmp_name'])) {}
Edited:
$fileUploads=$_FILES['file']['tmp_name'];
$countUpload=0;
foreach($fileUploads as $fileUpload){
if($countUpload>2) {
echo $_FILES['file']['tmp_name'];
//move_upload_file
}
$countUpload=$countUpload+1;
}
Check error status:
if ($_FILES['file']['error'][$key] == 0) {
echo $_FILES['file']['tmp_name'][$key];
}
Sry for asking so much [ 3rd in 2 days ]
this time I want to make it so when ftp_put uploads a file it wont show the result each time it uploads , like "Success Success" but I want it to say only when it finishes to upload all the files.
My current code:
foreach (glob("black/*") as $filename)
if(ftp_put($conn, $ftpFolder . basename($filename) , $filename, FTP_BINARY)) {
echo "sall goodman"; }
else { echo "not goot bruh"; }
}
[ dont look at the answers right now, its just for duh lulz and testing ]
Thanks in advance guys, You are really helping me out :)
Just comment the statement , echo "sall goodman" and you are good to go such that you won't get the repeated success message.
I have extended your example a bit, If all files are uploaded successfully you get the message All files have been successfully uploaded , else say if some 2 files failed on upload then you will get 2 file(s) have been failed during upload.
$totFiles = 0;
$successUploadFiles=0;
foreach (glob("black/*") as $filename)
if(ftp_put($conn, $ftpFolder . basename($filename) , $filename, FTP_BINARY)) {
//echo "sall goodman";
$successUploadFiles++;
}
else { echo "not goot bruh"; }
$totFiles++;
}
if($totFiles == $successUploadFiles)
{
echo "All files have been successfully uploaded";
}
else
{
echo $totFiles-$successUploadFiles." file(s) have been failed during upload";
}
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;
}
}