Uploadify JQuery & PHP/MySQL - Change file name on upload - php

I'm using Uploadify as part of a form. Let me give you a bit of background, it may help. I have a form where a user can add "projects" to a website. First they type in the name of the project and a description. On submit, this updates a PHP/MySQL database table named "project" and is given an ID.
The user can then upload files to a location on the server. I wish to add the project name onto the start of the file name for upload AND the project ID (which I need to add to the database) before upload begins, then when upload completes add the file details to a database table "image" - linked to "project" via the project ID.
I know I'm kinda bouncing back and forth a lot, I need to know how to do this. Two database tables to update, one on form submit and one on file-upload. I need to pass the project name and ID to the uploadify upload script.
SOLUTION:
I had to use the below uploadify method to send the Project ID to the uploadify script, having previously filled variable pid with the mysql_insert_id result:
'onSelectOnce': function(event,data) {
$('#file_upload').uploadifySettings('scriptData', {'pid': pid});
}
I could then receive the pid variable in the PHP uploadify script using a simple post:
$pid = $_POST['pid'];
It was then a matter of running a select within this script to get the data I needed for the database (the project alias) and adding it to the filename before upload:
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/' . $alias . '-';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
Hopefully this will help people in the future.

I had to use the below uploadify method to send the Project ID to the uploadify script, having previously filled variable pid with the mysql_insert_id result:
'onSelectOnce': function(event,data) {
$('#file_upload').uploadifySettings('scriptData', {'pid': pid});
}
I could then receive the pid variable in the PHP uploadify script using a simple post:
$pid = $_POST['pid'];
It was then a matter of running a select within this script to get the data I needed for the database (the project alias) and adding it to the filename before upload:
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/' . $alias . '-';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
Hopefully this will help people in the future.

In the uploadify script there is part that gives the syntax for the file being handled by the upload form. I don't have the script on hand, but uplodify hs a onbefore complete callback and an on complete call back features.
use the before complete and append the name to an ajax request that will save it to your database, from there just perform 2 queries, upload the name of the image and set user_id to the ID of the user thats probably from ur session.
var = file_before_upload_name: filename // here use the sytax that Uploadify uses to capture the name of the file
var = file_after_upload_name: filename // here use the sytax that Uploadify uses to capture the name of the file
then on the aftercomplete callback use an ajax request and set
uid : uid //from a session
before: file_before_upload_name,
after : file_after_upload_name
in the ajax your queries would look like
mysql_queries("INSERT INTO `tbl-projects` SET `user_id` = {$_POST['uid']}, `file` = {$_POST['after']}");
//another query here to set the data to your other table that relates to tbl-projects

Try this
http://programmintalk.blogspot.com/2011/02/jquery-uploadify-rename-uploaded-file.html

Related

Prevent users to download other files by changing the path in a url query

i have a download function receiving the filename by $_GET and i want to prevent users of downloading other files changing the path and accessing other files in the system.
method:
function actionDownload($arquivo) {
try {
$filepath = \Yii::getAlias('#webroot') . '/files/coordenadas/'. $arquivo;
if (file_exists($filepath)){
return \Yii::$app->getResponse()->sendFile(\Yii::getAlias('#webroot') . '/files/coordenadas/'. $arquivo, $arquivo);
}
}
catch (\Exception $exception) {
throw new NotFoundHttpException("Arquivo não encontrado");
}
}
the route to download the method:
http://example.com/converter-coordenadas/download?arquivo=geografica-utm-20200830171051.xlsx
if someone change the arquivo variable to another valid path it will be able to download other files. How prevent that, but keeping the function receiving the file name in a url param?
the situation that i have is:
the user upload a file through ajax
i convert this file and return the filename
create a download button with the link to the new file.
I don't have any other information to make a relation with the file, like an user id.
As #GetSet explained in the comments, the biggest problem is procedural. One way to do this correctly is as follows:
Upload the file to your server and save the reference in database (you already doing) and generate an unique ID for this file (or for this download). This ID will be saved in a database field, for example with the name: "donwload_id"
Then in the view (when you are creating the link for the download):
Html::a('Download', [Url::to('donwload-action'), 'download_id' => $model- >download_id]);
In your controller, You will know how to find the file by its unique identifier (download_id).
No one knows how you have generated this ID and therefore it is more difficult for anyone to be able to generate it again. Also you can limit the time available to download the file by setting an expiration date to the link.

Image uploader working perfectly for an insert form but not for an update form

I know there are already many similar questions like this and I apologize in advance for adding to the file, but I am a little short on time to do research and I need quick help. I am trying to finish an overdue assignment and my image upload function is working perfectly when I add a product, but not when I update it. I have no idea why. My code to update the image is here:
require_once 'file-util.php'
// Check if the file exists before setting it
if (isset($_FILES['imageFile1'])) {
// Retrieve the name of the file based on what it was called on the client computer
$filename = $codeInput . '.png';
// Make sure the filename exists
if (!empty($filename)) {
// Store the temporary location of where the file was stored on the server
$sourceLocation = $_FILES['imageFile1']['tmp_name'];
// Build the path to the images folder and use the same filename as before
$targetPath = $image_dir_path . DIRECTORY_SEPARATOR . $filename;
// Move file from temp directory to images folder
move_uploaded_file($sourceLocation, $targetPath);
}
}
This is the exact same code that I have in my insert_product file.
And my file_util is here:
$image_dir = 'images';
$image_dir_path = getcwd() . DIRECTORY_SEPARATOR . $image_dir;
Everything else works perfectly, but it is just this little thing that isn't seeming to do anything, so it seems to me like there's a little detail I'm missing for this to work in update_product. Is there something else I need to do to get this to work, or is it something else I'm unaware of?
Edit: Turns out that I just forgot to set the encryption type in my add_product_form. If anyone else has this silly issue, double check your forms for this near the top of the body:
<form action="insert_product.php" method="post"
id="add_product_form"
enctype="multipart/form-data">
You need to check if your updating form tag has the proper enctype attribute value...
and please be aware to use more validation on the uploaded file, your checking for file name exists or not will always be true as you are setting a value for it in the previous line.
Apparently, my code was right but I just forgot to go "enctype="multipart/form-data" in update_product_form.php.

Switch/select default directory as store folder

Since I'm using dropzone.js to store images to a directory I would like to know if there is a possibilty within PHP or other to first SELECT the destination or store folder before the file is dropped. Normally, there is a default path to the folder defined in PHP such as:
// upload.inc.php
<?php
include("../inc/config.inc.php");
$ds = DIRECTORY_SEPARATOR;
$storeFolder = '../../gallery/samples';
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
}
?>
Now, the store folder is predefined. What I have in mind is to first move the file into the dropzone field and then secondly select, either by Jquery, html or somehow, the folder to which the file is dropped off to. I don't want to change the path manually constantly on the upload script. How can I establish this? JStree for instance looks pretty well to have it done, idk.
Assuming you have a name stored in JavaScript that you want to use as the folder to store the uploads, you'll need to create a hidden HTML form element that gets populated with JavaScript:
HTML:
<input type="hidden" id="storefolder" name="storefolder">
JS:
var storefolder = document.getElementById["storefolder"];
storefolder.value = [VARIABLE]; // Whatever changes the folder needs to pass through here
PHP:
$storeFolder = $_POST["storefolder"];
Now your JavaScript variable will become your PHP variable, without the user ever seeing it outputted in the form. Note that you could also make the input field visible (with type=text), and simply use its value to pass directly through to the PHP if need be, bypassing the need for any JavaScript.
Hope this helps!

PHP methods for Implementing a pseudo cache system for files

This question is more about methodology than actual code - lines
I would like to know how to implement a pseudo caching (for lack of a better name) for FILES in php . I have tried to read some articles, but most of them refer to the internal caching system of PHP , and not to what I need which is a FILE cache.
I have several scenarios where I needed such a system applied :
Scenario 1 :
While accessing a post and clicking a link, all the post attachments are collected and added to a zip file for download.
Scenario 2 :
Accessing a post , the script will scan all the content , extract all links, download some matching images for each link (or dynamically prepare one) and then serve those to browser . (but not after checing expiration period ?? )
( Those example uses "post" and "attachment" because i use wordpress and it is wordpress terminology, both currently work for me fine, except they generate the file over and over again. )
My doubts regarding the two scenarios (especially No.2) - How do I prevent the script to do the operation EVERY time the page is accessed ? (in other words , if the file exists , just serve it without looping the whole creating operation again)
My first instinct was call the file with some distinctive (but not load - unique like uniqueid() ) name and then check if it is already on the server , but that presents several problems (like it can already exists as naming , but of another post ..) and also - that should be very resource intensive for a server with 20,000 images .
The second thing I thought was to somehow associate a meta data for those files, but then again, How to implement it ? How to knwo which link is of what image ??
Also, in a case where I check for the file existence on the server , how can I know if the file SHOULD be changed (and therefor recreated ) ?
Since I am refering to wordpress, I thought about storing those images as base64 from binary directly to the DB with the transien_API - but it feels quite clumsy.
To sum up the question . How to generate a file, but also know if it exists and call it directly when needed ?? does my only option is store the file-name in DB and associate it somehow with the post ?? that seems so non efficient ..
EDIT I
I decided to include some example code , as it can help people to understand my dilemma .
function o99_wbss_prepare_with_callback($content,$width='250'){
$content = preg_replace_callback( '/(http[s]?:[^\s]*)/i', 'o99_wbss_prepare_cb', $content );
return $content;
}
function o99_wbss_prepare_cb($match){
$url = $match[1];
$url = esc_url_raw( $url );//someone said not need ??
$url_name = parse_url($url);
$url_name = $url_name['host'];// get rid of http://..
$param = '660';
$url = 'http://somescript/' . urlencode($url) . '?w=' . $param ;
$uploads = wp_upload_dir();
//$uniqid = uniqid();
$img = $uploads['basedir'] . '/tmp/' . $url_name .'.jpg' ; // was with $uniqid...
if(! # file_get_contents($url)){
$url = 'path ' .$url. ' doesn"t exist or unreachable';
return $url;
} else {
$file = file_get_contents( $url );
}
// here I will need to make some chck if the file already was generated , and
// if so - just serve it ..
if ( $file) {
file_put_contents( $img, $file );
// Do some other operations on the file and prepare a new one ...
// this produces a NEW file in the wp-uploads folder with the same name...
unlink($img);
}
return $url;
}
For Scenario 1:
Wordpress stored all post attachments as posts in the posts table. When a post is accessed run a function either in a created plugin or your themes functions.php. Use the pre_get_posts hook check if you have already created the zip file with function file_exists() using a unique name for each zip archive you create, post ID or permalink would be a good idea. Although you would need to make sure there was no user specific content. You can use filemtime() to check the time the file was created and if it is still relevant. If zip file does not exist create it, pre_get_posts will pass the query object which has the the post ID, just grab all the post attachments using get_posts and the parent ID being set to the ID passed in the query object. The GUID field contains the URL for each attachment then just generate a zip archive using ZipArchive() following this tutorial at.
For Scenario 2:
If your wordpress templates are set up to use the wordpress functions then replace the attachment functions to return their url and map that to the new url you have the cached content. For example the_post_thumbnail() would go to wp_get_attachment_thumb_url() copy the file to your cache and use the cache url as output. If you wanted to cache the DOM for the page as well use ob_start(). Now just run a check at the start of the template using file_exists and filetime(), if both are valid read in the cached DOM instead of loading the page.

cannot upload file using uploadify

i have problem with uploadify.
on client it's working very nice
(all features like button,progress,etc. and file can be uploaded on client)
but on the hosting (server), the file cannot be uploaded.
on server, the another (button,progress,script for upload) is working,
only file that i want to upload cannot be uploaded.
otherwise i have some process to insert to database (the path of file), i put the insert sql query on script for uploading process, the query is working but file cannot be uploaded
my script (upload_file.php):
<?php
$file_id = $_POST['file_id'];
if (!empty($_FILES))
{
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
$destinationFile = "files/". $_FILES['Filedata']['name'];
move_uploaded_file($tempFile,$targetFile);
//additional - query to insert the path
include("database_connection.php");
$query = "insert into file (file_id,path) values ('$file_id','$destinationFile')";
$result = mysql_query($query);
mysql_close();
} ?>
and the javascript:
$('#file').uploadify
({
'uploader' : '/myweb/shockwaves/uploadify.swf',
'script' : '/myweb/process/upload_file.php',
'cancelImg' : '/myweb/images/uploadify/cancel.png',
'folder' : '/myweb/files',
'auto' : true,
'buttonText' : 'Upload',
'scriptData' : {'file_id':'001'}
});
thanks :)
We need more information, but the possibilities that come to mind:
Your form HTML is incorrect.
The file is too large.
The filename is too long.
File write permissions issue on server.
Ensure your HTML form has "enctype"
Ensure your HTML form on the page has enctype="multipart/form-data" e.g.
<form action="" method="POST" enctype="multipart/form-data">
Diagnosing PHP error / file write error
If it's a file / permissions issue, you might be able to spot a PHP error, so try enabling error reporting on the page as below:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>
Change file_id to be automatically generated
You should also change your database so that it is generating your file_id (i.e. auto-incrementing primary key / identity), rather than passing one in. If you don't have it auto-generate, you run the risk of duplicate file_id entries (or a failed query if the file_id column is a Primary Key as it should be).
Presumably you are also not actually using 'scriptData' : {'file_id':'001'} as this would mean you are inserting the file_id of 001 for every record. However, even client-size generation of this runs the risk of a) people picking their own file_id and corrupting your data, b) errors when JS is disabled (uploadify won't work, but file will probably still work) and c) duplicate file_id generation.
Your sample is vulnerable to SQL Injection
Your current sample is particularly vulnerable to SQL Injection, as you are not escaping your parameters. You might dismiss this as "oh it's okay it's an internal app so there's no security risk" but even accidental SQL Injection can cause issues. If this is a public facing website you've just exposed your database. I'm going to assume this is a reduced sample, but even then it's ill-advised to post unescaped SQL (at least without a comment), as it just leads to other less experienced developers copy/pasting it into an app somewhere.

Categories