Multiple File Upload using array - javascript

I have a website where people can upload an image file. Now i would like to allow users to upload multiple image files. I find it a bit confusing to make my functions accept arrays. Here is what I have :
The UI part of it:
<input type="file" id="imagefile" name="imagefile[]" multiple>
The handler function and used for logging to a txt file:
if(getPostPutField('imagefilename',$imagefilename))
$count=1;
foreach ($_FILES['imagefilename']['tmp_name'] as $file)
{
$imagefilename = urldecode($imagefilename);
$uploaded = handleUploadedImageFile($KBID, $_FILES['imagefile'], $imagefilename);
if ($uploaded)
{
$changesForEveryone[] .= "Image File Uploaded: " . $imagefilename."<br>";
$extraMsg .= "<br>Image File Uploaded: " . $imagefilename."<br>";
}
$count++;
}
The part where the file is really uploaded:
function handleUploadedImageFile($KBID,$file,$imagefilename=null)
{
$result = '';
if(empty($imagefilename))
$imagefilename = $file['name'];
if($file['size'] > 0)
{
$dir = PROBLEMIMAGES."/".sprintf("%05d",$KBID)."/";
$result = getUploadedFile($file['tmp_name'],$dir,$imagefilename);
}
else
{
$result = false;
}
return $result;
}
How do i do this properly?

If you have to upload all the files in a single request you can look at this answer here
but in order to create a better user experience it will be better to upload the files one by one using ajax take a look at the "jQuery File Upload Demo" (you can find there also the server side code in php)

Related

PHP - Create a directory listing of specified folder

I've got small piece of code which I'm using to scan a certain directory on my server for all the files and folders inside. But there's a catch... It can only scan the specified folder, and no sub-directories. Let's say share/ is the root directory for this scan, if there are files in any sub-directory like share/folder/file.png they won't be listed, where the entire purpose of my project is to create an HTML file explorer.
This is the code I'm using to receive the list of files from the server to later display it in the browser using JavaScript:
<?php
$listFiles = array();
if ($handle = opendir('./share')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$listFiles[] = $entry;
}
}
closedir($handle);
}
$FS_files = json_encode($listFiles);
?>
And then I "push" it rude to my actual JavaScript code like this:
let FS_files = <?php echo $FS_files ?>
The code I above basically generates an array of file names from scanned directory. What I wanna know is how can I get an entire JSON tree of files in this directory and all folders inside it, or possibly change my code so it works that way?
<?php
function scanFolder($dir) {
$result = array();
$cdir = scandir($dir);
foreach ($cdir as $key => $value) {
if (!in_array($value,array(".",".."))) {
if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) {
$result[$value] = scanFolder($dir . DIRECTORY_SEPARATOR . $value);
} else {
$result[] = $value;
}
}
}
return $result;
}
$FS_files = json_encode(scanFolder("./share"));
?>
The function scans the folder and checks each entry with is_dir. If its true, this folder is scanned with the same function.

Uploading capture image and store it in a folder changing it's filename to be unique using the userID

I have this code from this reference https://github.com/jhuckaby/webcamjs/blob/master/DOCS.md?fbclid=IwAR0Q3W5mw8qWlJEdiabmyZJiw7wGJ5YDPRl2Ej0IKF3GCt_78HXeqAEjI6Y
it will display the webcam and take snapshots and make it to an image element using the data_uri but the problem is I want to get that file and store it with a declared filename into a folder here's the script I use
<script src="webcam.js"></script> <!--source code script from github for webcam config-->
<div id="my_camera" style="width:320px; height:240px;"></div>
<div id="my_result"></div>
<script type=text/javascript>
Webcam.attach( '#my_camera' );
function take_snapshot() {
Webcam.snap( function(data_uri) {
document.getElementById('my_result').innerHTML = '<img src="'+data_uri+'"/>';
} );
}
</script>
Take Snapshot
I have a button called register that functions like get all information being input and store it into the database like username first name etc together with the image taken by snapshot, here's my upload script in uploading images from a folder and I want to use it as getting the image data_uri and store it in a folder when I click the register button
<?php
session_start();
include_once'database.php';
$uid = $_SESSION['u_id'];
if (isset($_POST['submit'])){
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
//check if ang uploaded file allowed i upload//
if (in_array($fileActualExt, $allowed)){
if ($fileError == 0){
if ($fileSize < 1000000){
$fileNameNew = "profile".$uid.".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
$sql = "UPDATE profileimg SET status=0 WHERE userID ='$uid';";
$result = mysqli_query($conn, $sql);
header("location:../pages/userpage.php");
}
else {
echo "Your file is too big";
}
} else {
echo "There was an error uploading you file!";
}
} else {
echo "You cannot upload files of this type";
}
}
I'm going to use this function as stated in the documentation
Webcam.upload( data_uri, 'myscript.php', function(code, text) {
// Upload complete!
// 'code' will be the HTTP response code from the server, e.g. 200
// 'text' will be the raw response content
} );
} );
and have this in my php script
move_uploaded_file($_FILES['webcam']['tmp_name'], 'webcam.jpg');
any idea how should I turn this script into the one I use above in my upload.php? thanks in advance
You need to create image first by image src and then need to save that in a specific folder. You can follow below code:
file_put_contents("fileNameWithLocation.png",file_get_contents($imageSrc));
Here fileNameWithLocation.png will be $fileNameNew = "profile".$uid.".".$fileActualExt; $fileDestination = 'uploads/'.$fileNameNew; You need to make modification accordingly. And $imageSrc will be the image src which you can post via Ajax or form submission.
Hope it helps you.

Active PHP code using JavaScript and URL

I have a self destruct PHP code that would delete all files and folders in my domain's directory.
<?Php
$dir = 'C:\wamp64\www\FileDirectory' . DIRECTORY_SEPARATOR . 'Files';
$it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
foreach($files as $file) {
if ($file->isDir()){
rmdir($file->getRealPath());
} else {
unlink($file->getRealPath());
}
}
rmdir($dir);
$filename = 'C:\wamp64\www\FileDirectory\Files';
if (file_exists($filename)) {
echo "The Directory has not been deleted";
} else {
echo "All Files And Folders Are Deleted";
}
?>
I need a way to only activate this code when I type in extra code to the end of my URL. I thought you could do that with JavaScript but I'm not too certain. Please let me know if I can do this. If I have to use a different code to do so, it's not a big deal.
Use $_GET['parameter'] to get parameter from get method:
http://example.com/index.php?doClean=1
if (isset($_GET['doClean'])) {
// Your code goes here
}

Need Help Handling a XML HTTP File Upload Request

So, I looked up a tutorial for uploading and sending files to a server with an XML HTTP Request. I followed the tutorial, however, I think I must be missing something. While the file appears to be uploaded and sent, nothing in the "handler" file is ever accessed. Is there a PHP function I need to write to process it? For context, here is what I wrote:
$(document).ready(function()
{
$('#upload-button').click(function(event)
{
$('#upload-button').removeClass("btn-danger");
});
$( "#report-form" ).submit(function( event )
{
var form = document.getElementById('report-form');
var fileSelect = document.getElementById('file-select');
var uploadButton = document.getElementById('upload-button');
event.preventDefault(); // Stop the event from sending the way it usually does.
uploadButton.value = 'Submitting...'; // Change text.
var files = fileSelect.files;
var maxfiles = <?php echo $config['Report_MaxFiles'] ?>;
var mfs = <?php echo $config['Report_MaxFileSize'] ?>;
if(files.length > maxfiles) // Make sure it's not uploading too many.
{
uploadButton.value = 'You uploaded too many files. The limit is ' + maxfiles + '.'; // Update button text.
$('#upload-button').addClass('btn-danger'); // Make the button red, if so.
return;
}
var formData = new FormData(); // Make a "form data" variable.
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Add the file to the request.
if(file.size / 1000 > mfs)
{
uploadButton.value = 'One of the files is too big. The file size limit is ' + (mfs) + 'kb (' + (mfs / 1000) + 'mb).';
$('#upload-button').addClass('btn-danger');
return;
}
formData.append('files[]', file, file.name); // Not really sure what this does, to be honest,
// but I think it makes a file array.
}
var xhr = new XMLHttpRequest(); // Construct an XML HTTP Request
xhr.open('POST', 'assets/class/FileHandler.php', true); // Open a connection with my handler PHP file.
xhr.onload = function ()
{
if (xhr.status === 200)
{
uploadButton.value = 'Files Submitted!'; // NOTE: I do get this message.
}
else
{
uploadButton.value = 'An error occurred.';
$('#upload-button').addClass("btn-danger");
}
};
xhr.send(formData); // I think this is where it dies.
});
});
At the "send(formData)" line, I'm not actually sure if it's sending. Do I set up some sort of listener in FileHandler.php that is activated when the files are sent via XML HTTP request? Or more specifically, how to I save the uploaded files to the server using my FileHandler.php file?
EDIT: I haven't been able to come up with any other PHP code in the FileHandler.php file than this, which I thought might be called when the form is sent (but it isn't):
EDIT 2: Okay, now I have something, but it isn't working (didn't expect it to). I think I may be using the variables wrong:
<?php
$uploaddir = 'data/reports/uploads/' . $_POST['id'] . "/";
$uploadfile = $uploaddir . basename($_FILES['files']['name']);
echo "<script>console.log('RECEIVED');</script>";
echo '<pre>';
if (move_uploaded_file($_FILES['files']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
It's not saving the file to the directory, nor is it printing the script message. How do I get my report.php file to execute these things in FileHandler.php?
Thanks to the help and patience of #Florian Lefèvre, I got it fixed. :)
The problem was with the path. It wasn't locating the path to the folder data/uploads/ and wasn't making the directory. Here is what I did:
$uploaddir = '../../data/reports/uploads/' . $_POST['id'] . "/";
echo "NAME: " . $_FILES['files']['name'][0] . "\n";
foreach($_FILES['files']['name'] as $filenumber => $filename)
{
$uploadfile = $uploaddir . basename ($filename);
echo "UploadDir " . $uploaddir . "\n";
echo "UploadFile " . $uploadfile . "\n";
echo '<pre>';
echo "MKDir for UploadDir which is: ". $uploaddir . "\n";
mkdir ($uploaddir);
if (move_uploaded_file ($_FILES['files']['tmp_name'][$filenumber], $uploadfile))
{
echo "File is valid, and was successfully uploaded.\n";
}
else
{
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print "</pre>";
}
var_dump ($_FILES);
I haven't gotten rid of some of the debug stuff yet, but that's the general solution.

Angularjs - File upload with php

I have spent days looking for a fairly simple integration of angularjs file upload method that includes a basic php server side script..
I need a simple form one field and file upload upload.
All examples I find are either heavily relying of jQuery or if they seem like something I could use their "examples" are completely unclear and messy.
These two examples (if I could figure out how to incorporate with PHP) would solve my puzzle..
Example 5 on this page
http://ng-upload.eu01.aws.af.cm/
And the example on this page is one I really like a lot..
http://angular-file-upload.appspot.com/
Could someone bring more light into this for me.. I would really like to see a one input filed and one file upload with as simple as possible angular and php code if such thing exists somewhere.
I would be happy to implement this http://twilson63.github.io/ngUpload/ or http://angular-file-upload.appspot.com/
If this is my PHP
$fname = $_POST["fname"];
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$extensions = array("jpeg","jpg","png");
if(in_array($file_ext,$extensions )=== false){
$errors[]="image extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size cannot exceed 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo $fname . " uploaded file: " . "images/" . $file_name;
}else{
print_r($errors);
}
}
?>
and this my basic html
<form action="" method="POST" enctype="multipart/form-data">
<input type="text" name="fname" />
<input type="file" name="image" />
<input type="submit"/>
</form>
How could I approach this (cleanly)? What should my controller and adjusted html look like?
If you use ng-file-upload
You can do most of those pre-validation on the client side like checking the file size or type with ngf-max-size or ngf-pattern directives.
Upload.upload() will send a POST multipart/form-data request to the server so $_FILES['file'] should contain the uploaded file.
HTML
<div ng-controller="MyCtrl">
<input type="text" name="username" ng-model="username"/>
<input type="file" ngf-select="onFileSelect($file)" ngf-pattern="'image/*'" ngf-max-size="2M">
</div>
JS:
//inject angular file upload directives and service.
angular.module('myApp', ['ngFileUpload']);
var MyCtrl = [ '$scope', 'Upload', function($scope, Upload) {
$scope.onFileSelect = function(file) {
if (!file) return;
Upload.upload({
url: '/upload.php',
data: {file: file, username: $scope.username}
}).then(function(resp) {
// file is uploaded successfully
console.log(resp.data);
});
};
}];
upload.php
$fname = $_POST["fname"];
if(isset($_FILES['image'])){
//The error validation could be done on the javascript client side.
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$extensions = array("jpeg","jpg","png");
if(in_array($file_ext,$extensions )=== false){
$errors[]="image extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size cannot exceed 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo $fname . " uploaded file: " . "images/" . $file_name;
}else{
print_r($errors);
}
}
?>
I was also battling with $files being undefined - I'll take a wild guess that you are writing the html code from php and haven't escaped the $ in $files. That was my problem anyway - should be \$files.
Dan

Categories