Uploadify Success but No Files Uploaded? - javascript

I am attempting to implement uploadify on a site.
It says the files are uploaded but when I look in the upload folder nothing is there.
I have read other post similar to this without luck.
I did read this answer to another question:
I had similar problems on a Linux machine. It turned out that the PHP configuration on my server was the cuplrit. PHP was running in SAFE MODE. As I had uploaded the Uploadify scripts via FTP, so script files were stored in the file system with my FTP user details. Since PHP's temp folder was owned by the server root, I had a UID mismatch, i.e. the temporary upload file was attributed to root while the upload script that tried to move it was owned by the FTP user. That fragged it.
To resolve this I changed the ownership of the uploadify php script to root and from there on it worked.
I know little about server side coding as I am more a front end person. How do I change permissions? I am using 1&1 Hosting.
Here is a screenshot of the files on the server in FileZilla:
EDIT
I tried to upload a ZIP file and it said the upload was successful but did not upload. However, I wonder if there is an error with my script because I should not have been allowed to upload a ZIP File because of this line in the PHP Script:
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
Shouldn't the script reject the zip file?
Below is my code I am using in case there is an error with the scripts and not my server:
JS
$(function() {
$('#file_upload').uploadify({
'swf' : 'uploadify.swf',
'uploader' : 'uploadify.php',
'onUploadSuccess' : function(file, data, response) {
alert('The file ' + file.name + ' was successfully uploaded with a response of ' + response + ':' + data);
}
});
});
PHP
<?php
$targetFolder = '/uploads/'; // Relative to the root
$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo '1';
} else {
echo 'Invalid file type.';
}
}
?>

It looks as though the token verification code is the problem. If you remove that functionality, the upload should go through :)
Can you remove that if() comparison by commenting it out?
if (!empty($_FILES) && $_POST['token'] == $verifyToken) { line changes to:
if (!empty($_FILES) /* && $_POST['token'] == $verifyToken */) {

It seems that the $fileTypes is case sensitive on my Linux PHP install.
'image.jpg' uploads but 'image.JPG' does not.
Change
$fileTypes = array('jpg','jpeg','gif','png');
To
$fileTypes = array('jpg','JPG','jpeg','JPEG','gif','GIF','png','PNG');

Related

Laravel with Resumable.js failed uploading large file and slow server response

From the start:
I'm using XAMPP as a server stack for testing project which is something like google drive.
What I wanted to achieve is that User can upload any size and type of file.
I'm using for it Resumable.js which divides file into the chunks(1024KB) and sends it onto the server (Apache). I assume this will exclude changes in php.ini file (upload_max_filesize, post_max_size) ?
For testing I've used 9,6GB Linux image. There were two problems:
File was uploading 4,5 hours (TTFB increases every minute from 300ms to 10s close to the end of upload). What fix is possible?
While upload "finishes" it sends Error 500 and it not merge the files together. Is it possible to change something in Apache config? Probably response error?
When I've tested which are less than ~1GB it works. That was stress test. XAMPP is the blank install, nothing changed in any config file.
JS function handling uploading:
let resumable = new Resumable({
target: '{{ route('upload.large') }}',
query:{_token:'{{ csrf_token() }}'} ,// CSRF token
fileType: [],
headers: {
'Accept' : 'application/json'
},
testChunks: false,
throttleProgressCallbacks: 1,
});
Upload function in Controller:
public function upload(Request $request)
{
$receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
if (!$receiver->isUploaded()) {
// file not uploaded
}
$fileReceived = $receiver->receive(); // receive file
if ($fileReceived->isFinished()) { // file uploading is complete / all chunks are uploaded
$file = $fileReceived->getFile(); // get file
$extension = $file->getClientOriginalExtension();
$fileName = $file->getClientOriginalName(); //file name without extenstion
$disk = Storage::disk(config('filesystems.default'));
$path = $disk->putFileAs('videos', $file, $fileName);
// delete chunked file
unlink($file->getPathname());
return [
'path' => asset('storage/' . $path),
'filename' => $fileName
];
}
// otherwise return percentage informatoin
$handler = $fileReceived->handler();
return [
'done' => $handler->getPercentageDone(),
'status' => true
];
}
I'm getting close to solving this problem (which I'm having myself). It seems that the failure occurs when the chunks are being merged together to recreate the original file. I'm getting a "Failed to open input stream" once the file size hits 4.4GB. I'm suspecting the file append is limited or the memory isn't getting released. Hopefully this helps narrow it down.

Creating PHP backend for file upload using filepond

I am creating a form on a website, where files (images and pdfs) need to be uploaded too. Until now, I have used a simple input type="file" element, coupled to a PHP file on the backend (snippet follows):
$allowed = array('jpg', 'jpeg', 'pdf', 'png');
if(isset($_FILES['uploadctl']) && $_FILES['uploadctl']['error'] == 0){
$extension = pathinfo($_FILES['uploadctl']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"not_allowed"}';
exit;
}
// create folder to upload files to
$id = session_id();
$user_folder = 'user_data/' . $id;
if( is_dir($user_folder) === false ){
mkdir($user_folder);
}
if(move_uploaded_file($_FILES['uploadctl']['tmp_name'], $user_folder . "/" . $_FILES['uploadctl']['name'])){
echo '{"status":"success"}';
exit;
}
echo '{"status":"error"}';
}
This works well. However, I would like more functionality for the upload form and have looked into filepond. I created the filepond object as per the documentation and copied the boilerplate code to ./file-pond-assets, which I plan to adapt to my needs later:
<input type="file" name="uploadctl" multiple accept=".pdf,.png,.jpg,.jpeg">
<script>
const inputElement = document.querySelector('input[type="file"]');
const pond = FilePond.create( inputElement );
pond.setOptions({
server: './file-pond-assets'
});
</script>
which is showing when displaying the website. When trying to upload a file, the front-end looks fine, as an upload complete message appears. However, I cannot find the uploaded files in the tmp and uploads folder inside ./file-pond-assets. I tried changing permissions of the folders and also checked the console, but cannot find an error message. The config.php file also points to the right folders. What do I miss that makes my files not appear on my server? I would like to keep the upload as a multipart/form-data.
Here is a link to my sample file-pond PHP server implementation repository on gihtub
Repo Link: https://github.com/Onihani/filepond-php-server-example
Live Preview: http://www.ics-courses.co.uk/natbongo/filepond-php-server-example/

Unable to upload pdf file: Php

The issue I'm facing is, I get the following error while trying to upload some pdfs your upload file is not PDF file. However, this error doesn't show up for all pdfs, it's only for some pdf files I get this error.
<?php
$error = $_FILES['fileToUpload']['error'];
//get upload file type
$type = $_FILES['fileToUpload']['type'];
$action = "upload";
//get file name
$picname = $_FILES['fileToUpload']['name'];
$nameArray = explode(".", $picname);
if {
//check files
//filetoUpload code
}
?>
The issue is that, in the url: '../controller/uploadFile.php' even if the file is PDF, $type = $_FILES['fileToUpload']['type']; will return empty and then it will go into the condition else if($type !="application/pdf" ) and pop up the alert your upload file is not PDF file.. Like I said, this issue is with most of the pdf file. However, some pdf files manage to get uploaded without any issue and if a pdf file gets uploaded, then $type will be application/pdf.
Your input will be highly appriciated.
---UPDATE---
The issue is with $_FILES, it's not fetching the pdf file details for some reason
The issue has been resolved. I checked '$error= $_FILES['fileToUpload']['error']; and the value was returning 1
Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.```
You could better check the extension, this also prevents malicious users to upload exe or zip files when they provide the header Content-Type: application/pdf. Also not all browsers/api libraries specify a Content-Type.
If your filename does not contain a path, check it with a regex so people cannot upload files to directories they shouldn't (ex ../../cache/exe). use for example
preg_match("/^[a-zA-Z0-9_+\\- ]+\\.pdf$/", $filename) to check if it is a pdf.
Do never do unlink('files/' . $filename); when $filename could be anything submitted by the user. Delete ../index.php could destroy your server.

How to rename a file which already stored in the server using laravel?

I am using Laravel 5. I have a form which has an upload file inside it. If I want to edit the data and edit the file(upload new file), it's works. But if I want to edit the data without uploading a new file (example the mail's name, because the file's name depends on the mail's name), it works just change the file name in the database without rename a file which stored in the server, so when I click view file, I have got an error the file is not found. Do you know how to replace a file name?
$destination = 'files';
if($request->hasFile('ubah_upload_file')) {
$file = $request->file('ubah_upload_file');
$extension = $file->getClientOriginalExtension();
$file_name = str_replace('/','_',$request['ubah_nomor_surat']) . '.' . $extension;
$file->move($destination, $file_name );
} else {
$file_name = str_replace('/','_',$request['ubah_nomor_surat']) . '.' . "pdf";
}
Use the rename() function to rename a file
Ps: update the name in the db too if you rename it permanently

php create file in directory

The below code checks for a directory 'dat'; if it ins't there, it creates one. That part works just fine; what I need is for it to write a file to said directory where AJAX can read it from.
Here's the php...
//checks for 'dat' directory; if false, creates it, if true, does nothing.
$dir = 'c:\wamp\www\dat';
if(file_exists($dir)){
return;
}
else{
mkdir ('C:\wamp\www\dat',0700);
}
//writes chats to file
$data = fopen($dir. "/chatlog". date('d'). '.txt', 'a+');
fwrite($data, $speak);
fclose($data);
}
And here's the AJAX; I don't need as much help here as I do above, but I won't complain if you provide the help for the AJAX below, mainly in getting it to read from the file within the 'dat' directory...
xhr.open("GET","chatlog<?php /*stamps the chatlog file with date (numerical day only)*/ echo date("d");?>.txt",true);
Your PHP script is running inside www, then, your file you be created there.
If you want to create the file inside the directory www/dat, just change this line
$file = "chatlog". date('d'). ".txt";
for this one
$file = 'dat\chatlog'. date('d'). '.txt';

Categories