Creating PHP backend for file upload using filepond - javascript

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/

Related

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.

Getting the file path of an uploaded file

I am currently doing a PHP project that requires me to make a logs of all the imported excels in the database.
I was able to get the tmp_name from the $_FILES global variable but not able to get the exact file path.
Here is my code snippet.
index.php
<form role="form" method="post" action="post_data.php" enctype="multipart/form-data">
<input type="file" name="file" required>
<button>Submit</button>
</form>
post_data.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//var_dump($_FILES['file']);
//var_dump($_FILES['file']['name']); #gets the file name
var_dump($_FILES['file']['tmp_name']); #gets the temp file path and name
}
?>
Any help would be much appreciated. I can also work with javascript if there are any available solutions for this problem. Thanks
You'll not get the file path. The File Upload in PHP works such that when you upload a file, it'll be uploaded to a temporary location and then your form will be posted. The path of the temporary location will be provided in tmp_name option in $_FILES array.
By using the move_uploaded_file function, this file will be moved from the temporary location to the location of your choice. But you'll have to provide the location (including the filename) where you want to move the file from temporary location.
So if you are looking for a path where you want to move the file from then it'll be present in tmp_name.
Hope this helps.
<?php
//variable containing path of Server's folder where you want to upload your file
$path;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//var_dump($_FILES['file']);
//var_dump($_FILES['file']['name']); #gets the file name
var_dump($_FILES['file']['tmp_name']); #gets the temp file path and name
if (move_uploaded_file($_FILES['file']['tmp_name'], $path . DS . $_FILES['file']['name'])) {
//file uploaded successfully
//your file is uploaded at $path . DS . $_FILES['file']
}
else {
//error in uploading file
}
}
?>
$image=$_FILES['file'];
$base=$_SERVER['DOCUMENT_ROOT']; $filename=$_FILES['file']['name'];
$path=$base."/trial/Uploads/Original_folder/signature/".$filename."";
if(file_put_contents($path,$image)!=false)
{
echo $path;
}

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';

Uploadify Success but No Files Uploaded?

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');

Remove XML Node With jQuery

I wonder whether someone may be able yo help me please.
I've put together this page which allows users to view a gallery of their uploaded images.
Upon initial upload, the physical images are saved in the following file structure:
UploadedFiles/userid/locationid/image and the details of the image i.e. description etc are saved in an xml file called files.xml which is in the same directory as the physical images.
I'm now working on allowing the user to be able to delete these images.
By way of a deletion icon under each image, I've, admitedly with some help, put together the following which successfully deletes the physical image.
'Deletion Icon Onclick Event'
<script type="text/javascript">
Galleria.ready(function() {
this.$('thumblink').click();
$(".galleria-image").append(
"<span class='btn-delete ui-icon ui-icon-trash'></span>");
$(".btn-delete").live("click", function(){
var img = $(this).closest(".galleria-image").find("img");
// send the AJAX request
$.ajax({
url : 'delete.php',
type : 'post',
data : { image : img.attr('src') },
success : function(){
alert('Deleting image... ');
img.parent().fadeOut('slow');
}
});
return false;
});
});
</script>
Original 'delete.php'
<?php
if (!empty($_POST)) {
$image = $_POST['image'];
if (file_exists($image)) {
unlink($image);
}
}
?>
Updated 'delete.php'
<?php
if (!empty($_POST)) {
$image = $_POST['image'];
if (file_exists($image)) {
unlink($image);
}
}
$doc = new DOMDocument;
$doc->load('files.xml');
$thedocument = $doc->documentElement;
$list = $thedocument->getElementsByTagName('files');
$nodeToRemove = null;
foreach ($list as $domElement){
$attrValue = $domElement->getAttribute('file_name');
if ($attrValue == 'image') {
$nodeToRemove = $domElement;
}
}
if ($nodeToRemove != null)
$thedocument->removeChild($nodeToRemove);
echo $doc->saveXML();
?>
The problem I'm having is deleting the xml node form the xml file. I've provided an extract of the XML file below.
<?xml version="1.0" encoding="utf-8" ?>
- <files>
<file name="stag.jpg" source="stag.jpg" size="21341" originalname="stag.jpg" description="No description provided" userid="1" locationid="1" />
</files>
I've done quite a bit of research about how to go about this and found that jQuery had it's own command i.e. jQuery.remove which I thought would be able to delete the node. Following the brief tutorial I added the following to the end of my 'Onclick Event' script:
var doc = $(files.xml);
doc.find('file_name:src').remove();
Unfortunately, although I don't receive a specific error, the node isn't being deleted from the file. I'm a complete beginner when it comes to XML so perhaps I'm looking at this too simplistically.
I just wondered wheteher someone could perhaps have a look at this please and let me know where I'm going wrong.
Many thanks and regards
This is because JavaScript(JQuery) loads the XML DOM in memory and then when you delete a node,
it gets deleted from the in-memory xml doc(the object).
It wont be removed from the physical XML file.
JS runs in a sandbox Browser environment and cannot alter local files on the system.
and if you are trying to load xml from a remote server then its a very bad idea.
the XML file from remote server is downloaded as temp file and then when you load XML again an in-memory DOM is created and the node is deleted from it.
So in case you want the actual file to be changed,
you will need to use AJAX and send some HTTP request to your server to do the same to the physical file.
UPDATE:
Check this tutorial
http://www.phpeveryday.com/articles/PHP-XML-Removing-Node-P415.html
and try to load the xml file in your delete.php and remove the corresponding node from it and then save this xml back to the original file which will be overwritten.

Categories