cannot upload file using uploadify - php

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.

Related

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.

What is the best way to get the parameters in PHP?

I will completely clarify my question, sorry to everybody.
I have code writed in files from a website that now is not working, the html code is on pages with php extension, in a folder of a Virtual Host in my PC using Wampserever. C:\wamp\1VH\PRU1, when the site was online there was a folder where was a file called image.php. This file was called from other pages inside the site like this: (a little code of a file, C:\wamp\1VH\PRU1\example.php)
"<div><img src="https://www.example.com/img/image.php?f=images&folder=foods&type=salads&desc=green&dim=50&id=23" alt="green salad 23"></div>"
And the result was that the images was showed correctly.
Now, like i have this proyect in local, and i HAVE NOT the code of that image.php file i must to write it myself, this way the images will be showed the same way that when the site was online.
When the site was online and i open a image returned by that image.php file the URL was, following the example, https://example.com/images/foods/salads/green_50/23.png.
Now how the site is only local and i have not that image.php file writed because i'm bot sure how to write it, the images obviously are not showed.
In C:\wamp\1VH\PRU1\example.php the code of files was changed deleting "https://www.example.com/img/image.php?" for a local path "img/image.php?".
And in the same folder there is anothers: "img" folder (here must be allocated the image.php file), and "images" folder, inside it /foods/salads/green_50/23.png, 24.png.25.png..............
So i have exactly the same folder architecture that the online site and i changed the code that i could only, for example replacing with Jquery "https://www.example.com/img/image.php?" for "img/image.php?" but wich i can not do is replace all the code after the image.php file to obtain a image file.
So i think that the easiest way to can obtain the images normally is creating that IMAGE.PHP file that i have not here in my virtual host.
I'd like to know how to obtain the parameters and return the correct URL in the image,php file.
The image of the DIV EXAMPLE must be C:/wamp/1VH/PRU1/images/foods/salads/green_50/23.png
I have in my PC the correct folders and the images, i only need to write the image.php file.
Note that there are "&" and i must to unite the values of "desc=green&dim=50&" being the result: green_50 (a folder in my PC).
TVM.
You probably want something like this.
image.php
$id = intval($_GET['id']);
echo '<div><img src="images/foods/salads/green_50/'.$id.'.png" alt="green salad '.$id.'"></div>';
Then you would call this page
www.example.com/image.php?id=23
So you can see here in the url we have id=23 in the query part of the url. And we access this in PHP using $_GET['id']. Pretty simple. In this case it equals 23 if it was id=52 it would be that number instead.
Now the intval part is very important for security reasons you should never put user input directly into file paths. I won't get into the details of Directory Transversal attacks. But if you just allow anything in there that's what you would be vulnerable to. It's often overlooked, so you wouldn't be the first.
https://en.wikipedia.org/wiki/Directory_traversal_attack
Now granted the Server should have user permissions setup properly, but I say why gamble when we can be safe with 1 line of code.
This should get you started. For the rest of them I would setup a white list like this:
For
folder=foods
You would make an array with the permissible values,
$allowedFolders = [
'food',
'clothes'
'kids'
];
etc...
Then you would check it like this
///set a default
$folder = '';
if(!empty($_GET['folder'])){
if(in_array($_GET['folder'], $allowedFolders)){
$folder = $_GET['folder'].'/';
}else{
throw new Exception('Invalid value for "folder"');
}
}
etc...
Then at the end you would stitch all the "cleaned" values together. As I said before a lot of people simply neglect this and just put the stuff right in the path. But, it's not the right way to do it.
Anyway hope that helps.
You essentially just need to parse the $_GET parameters, then do a few checks that the file is found, a real image and then just serve the file by setting the appropriate content type header and then outputting the files contents.
This should do the trick:
<?php
// define expected GET parameters
$params = ['f', 'folder', 'type', 'desc', 'dim', 'id'];
// loop over parameters in order to build path: /imagenes/foods/salads/green_50/23.png
$path = null;
foreach ($params as $key => $param) {
if (isset($_GET[$param])) {
$path .= ($param == 'dim' ? '_' : '/').basename($_GET[$param]);
unset($params[$key]);
}
}
$path .= '.png';
// check all params were passed
if (!empty($params)) {
die('Invalid request');
}
// check file exists
if (!file_exists($path)) {
die('File does not exist');
}
// check file is image
if (!getimagesize($path)) {
die('Invalid image');
}
// all good serve file
header("Content-Type: image/png");
header('Content-Length: '.filesize($path));
readfile($path);
https://3v4l.org/tTALQ
use $_GET[];
<?php
$yourParam = $_GET['param_name'];
?>
I can obtain the values of parameters in the image.php file tis way:
<?php
$f = $_GET['f'];
$folder = $_GET['folder'];
$type = $_GET['type'];
$desc = $_GET['desc'];
$dim = $_GET['dim'];
$id = $_GET['id'];
?>
But what must i do for the image:
C:/wamp/1VH/PRU1/images/foods/salads/green_50/23.png
can be showed correctly in the DIV with IMG SRC atribute?

PHP link/request to download file then delete it immediately

I face a case I never did, and I dont know how to properly do it.
I have a php script which generate files for clients. At the end of the script, I echo the path for them to download the file, simply.
How can I do to provide the file - or the path or any what - for downloading it, and be sure to delete the file once downloaded.
Widely, I'd like to make the file available for one/unique download only. How to ?
EDIT
I cannot use headers
There are a few components to getting this to work. Without knowing which framework you use, I'll use comments as placeholders.
There is no way to do it without using the header function, though.
Here is the source for a file that outlines the process:
<?php
$fileid = $_GET['fileid'];
$key = $_GET['key'];
// find the file in the database, and store it in $file
if ($keyMatches) {
// it is important for security to only use file paths from the database
$actualPath = $file->getPathOnDisk();
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($fileInfo, $actualPath);
$fp = fopen($actualPath, 'rb');
header("Content-Type: " . $mime);
header("Content-Length: " . filesize($actualPath));
fpassthru($fp);
}
else
{
http_response_code(403); // forbidden
}
You'll use this by linking to download.php?fileid=1234&key=foobar, and generating the URL at the same time you generate the key and store it in the database.
For security, you'll keep the files outside of the web root, meaning they cannot be accessed through the web server without going through a script.
fpassthru is reasonably fast, and will not likely have a performance impact.
You must do a download file gateway, like download.php?id=XXX
Where XXX is the unique ID of each file you will store in DB. And of course, the file to be downloaded.
Then, each time a user will visit the page, you can :
- Check if he has already downloaded the file
- If no, redirect it to the real path of file
- If yes, display 403 message.
When a user download a file, update the DB, generate or copy the file to a new name, you play with headers, and delete file upon download or after a small timeout.

PHP Script is not Properly Uploading Images

I'm working on a small, user-maintained online store, and am trying to allow my end user (the store administrator) to upload graphics for products. When I run this script, however, it doesn't actually store the image. I built this script from various tips here and a tutorial, and have gotten everything but the image upload portion to work.
// Set the image target directory here
$target = "itemImages/";
$target = $target . basename($_FILES["image"]["name"]);
// Variables get POSTed here - just tack new ones on at the end.
// Various POSTs omitted for brevity
$pic=($_FILES["image"]["name"]);
// Places the picture in the folder
if(move_uploaded_file($_FILES["image"]['tmp_name'], "itemImages/"))
{
echo "The file " . basename($_FILES['uploadedfile']["name"]) . " has been uploaded.<br />";
}else {
echo "There was an issue adding this item. Please try again.<br />";
}
// Writes variables to the database
mysql_query("INSERT INTO tbl_item (itemNAME,itemDESC,itemCOST,itemHCOL,itemHSIZ,itemIMG)
VALUES ('$itemName','$itemDesc','$itemCost','$hasColor','$hasSize','$pic')");
mysql_close($con);
?>
Any help, tips, advice, insight, etc. would be very much appreciated.
move_uploaded_files requires a filename as its target. It does not blindly move to a directory, so
move_uploaded_files($_FILES..., 'somedir/somefile.txt');
works, but
move_uploaded_file($_FILES..., 'somedir/');
will not.
Plus, note that your database operation is vulnerable to SQL injection attacks. You're blindly inserting the uploaded file's remote name (['name'] via $pic), and that name is fully under the remote user's control.
Make sure the itemImages folder has write permission by the user your web server (e.g. Apache) is running as (e.g. www-data)
make sure the .php file and the folder you are writing to have the same "owner". Or try setting permissions on the itemImages folder to 777 (This is not recommended, just a debug tactic)

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

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

Categories