Hy , i was looking at uploadify.php and did'n understand a thing.
I have a form like this :
<form id="formid" name="upload_pic" action="upload.php">
<select name="product_id">
<option value="1">Apples</option>
<option value="2">Oranges</option>
... etc
</select>
<input id="file_upload" name="file_upload" />
</form>
and my uploadify settings are :
<script type="text/javascript">
$(document).ready(function() {
$('#file_upload').uploadify({
'uploader' : 'uploadify/uploadify.swf',
'script' : 'uploadify/uploadify.php',
'cancelImg' : 'uploadify/cancel.png',
'folder' : '../images/level3/tabv_all/tab_header/',
'auto' : false,
'multi' : true,
'fileExt' : '*.jpg',
'fileDesc' : 'ONLY JPG (.JPG)',
'removeCompleted' : false
});
});
</script>
What i want to do is that if the user select Apples wich has the id=1 and browse for a file like Tasty_apples.jpg -> the uploaded file to be renames to product#1#Tasty_apples.jpg and then to be inserted in mysql like that?
The main question is how to add the extra product#id# to a file based on a <select><option> value ?
Thank you very much
The uploadify.php is this :
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
move_uploaded_file($tempFile,$targetFile);
echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile);
}
I think i have solved this...try this in your upload.php file
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$newName = $_FILES['Filedata']['name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_GET['folder'];
if(file_exists($targetPath."/".$newName))
{
//echo "test";exit;
$part=explode("." , $newName);
$name1=$part[0];
$ext=$part[1];
$newName=$name1."_".rand().".".$ext;
}
$Path = $targetPath . '/';
$targetFile = str_replace('//','/',$Path) . $newName;
move_uploaded_file($tempFile,$targetFile);
}
You can send additional data to your backend script with scriptData option:
http://www.uploadify.com/documentation/options/scriptdata/
Example
var selectedID = $("select[name=product_id]").val()
'scriptData' : {'pid': selectedID}
// uplodify.php
$targetFile = str_replace('//','/',$targetPath) . 'product#' . $_POST['pid'] . '#' . $_FILES['Filedata']['name'];
it would be good if you could provide your actual 'uploadify.php' file, to help with the actual PHP. But as an example of how you would go about changing the name it would be something along the lines of this:
$tmp_name = #$_FILES['Filedata']['tmp_name'];
$name = #$_FILES['Filedata']['name'];
$filesize = #$_FILES['Filedata']['size'];
$extension = strtolower(pathinfo($name,PATHINFO_EXTENSION));
$newname = 'apples&'.$name . "." . $extension ;
This is just an example, if I had your code I could point it out better; but hope that's understandable!
//your categories array, example
$cats = array(1=>'apples',2=>'oranges');
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] .'/'. trim($_REQUEST['folder'], '/') . '/';
$name = pathinfo($_FILES['Filedata']['name'], PATHINFO_FILENAME);
$extension = strtolower(pathinfo($_FILES['Filedata']['name'], PATHINFO_EXTENSION));
$newname = (isset($cats[$_REQUEST["product_id"]]) ? $cats[$_REQUEST["product_id"]] : 'category_not_exist' ).'#'. (int)$_REQUEST["product_id"].'#'. $name '.' . $extension;
$targetFile = str_replace('//','/',$targetPath) . $newname;
move_uploaded_file($tempFile, $targetFile);
echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile);
}
Related
I am using Uploadify and when a person uploads the file I want the file name to be a random generated file name. Numbers would be fine.
Here is the current PHP I am using:
<?php
$targetFolder = '/uploads';
$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES)) {
$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','doc','docx','pdf','xlsx','pptx','tiff','tif','odt','flv','mpg','mp4','avi','mp3','wav','html','htm','psd','bmp','ai','pns','eps'); // 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.';
}
}
?>
I tried replacing this:
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
with this (per this answer):
$fileParts = pathinfo($_FILES['Filedata']['name']);
$targetFile = rtrim($targetPath,'/') . '/' .rand_string(20).'.'.$fileParts['extension'];
but that did not work, in fact, it stopped the file from uploading at all.
How do I modify the script to create random file names? Note: I know almost no PHP, please make any answer clear for a beginner.
I'd use uniqid() as I have no idea what rand_string is or where it comes from, eg
$fileParts = pathinfo($_FILES['Filedata']['name']);
$targetFile = sprintf('%s/%s.%s', $targetPath, uniqid(), $fileParts['extension']);
Another thing I never do is rely on DOCUMENT_ROOT. Instead, use a path relative from the current script. For example, say your script is in the document root
$targetPath = __DIR__ . '/uploads';
I am having problems when trying to upload files onto my server. I am using the uploadify plugin to upload files onto my server then store the filename in a database.
the problem is that uplodify acts like the file has been uploaded with no error but nothing is being uploaded.
I am runing PHP on a Windows 2008 R2 Server
the following is my php code that handle the actual upload.
<?php
require("../requires/LDAP_connection.php");
require("../requires/APP_configuration.php");
require("../requires/PHP_generic_functions.php");
//Include connection class
require('../classes/connection.php');
require('../requires/user_authentication.php'); //this file must be placed under the connection class NOT before
define('ROOT_SYS', dirname(__FILE__).'/');
// Define a destination
$targetFolder = '';
$verifyToken = '100';
$actualToken = '';
$fileTypes = array('jpg','jpeg','gif','png');
if(isset($_POST['upload_path'])){
$targetFolder = $_POST['upload_path'];
}
if(isset($_POST['timestamp'])){
$verifyToken = md5($_POST['timestamp']);
}
if(isset($_POST['token'])){
$actualToken = $_POST['token'];
}
if(isset($_POST['allowed_extentions'])){
$types = explode(',', $_POST['allowed_extentions']);
if(count($types) > 0 ){
$fileTypes = $types;
}
}
if (!empty($_FILES) && $actualToken == $verifyToken) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = ROOT_SYS . $targetFolder; //$_SERVER['DOCUMENT_ROOT']
$new_filename = USER_ID . '_' . time() . '_' . str_replace(" ", "_", $_FILES['Filedata']['name']);
$targetFile = $targetPath . $new_filename;
// Validate the file type
//$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($new_filename); //str_replace(" ", "_", $_FILES['Filedata']['name'])
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo trim($new_filename);
} else {
echo 'INVALID';
}
}
?>
the following is my javascript
<?php $timestamp = time();?>
<script type="text/javascript">
$(function() {
$('#file_upload').uploadify({
'formData' : {
'timestamp' : '<?php echo $timestamp;?>',
'token' : '<?php echo md5($timestamp);?>',
'upload_path': 'add-ons/ticketing_system/uploads/',
'allowed_extentions': 'jpg,jpeg,gif,PNG,JPG,png,zip,rar,doc,docx,cvs,xls,xlsx,txt'
},
'auto' : true,
'swf' : '../../includes/uploadify.swf',
'uploader' : '../../includes/uploadify.php',
'fileSizeLimit' : '10MB',
'fileTypeExts' : '*.gif; *.jpg; *.JPG; *.png; *.PNG *.zip; *.rar; *.doc; *.docx; *.cvs; *.xls; *.xlsx; *.txt;',
'onUploadSuccess' : function(file, data, response) {
if(data != 'INVALID'){
$('#attached_files').append('<input type="hidden" name="attachments[]" value="'+ $.trim(data) +'" />');
} else {
alert('Invalid File Type');
}
}
});
});
</script>
What am I doing wrong? Why is it not uploading anything and also not giving me any error?
Thanks
Uploadify has a debug mode to help you with issues like this : http://www.uploadify.com/documentation/uploadifive/debug-2/
The things I usually look for are permissions errors...and maybe your authentication methods.
i have this code here which outputs me an image.. I need to change it because for the moment it gives me something like : test.jpg, what i need is for it to give me test_s.jpg
Using the rename function i guess!
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetPath = str_replace('//','/',$targetPath);
$targetFile = $targetPath . $_FILES['Filedata']['name'];
tamano_nuevo_foto($stempFile, 420, $stargetFile);
You could do:
$extension = array_pop( explode(".", $_FILES['Filedata']['name']) ); //get extension
$targetFile = $targetPath . "some_new_name".$extension;
tamano_nuevo_foto($tempFile, 420, $targetFile);
First: You seem to have a path that can be manipulated by the the user. Your usage of $_REQUEST['folder'] directly in your path is bad. The user could put ANYTHING in there, even stuff like ../../../ to move around your filesystem!
To change the name, simply:
$targetFile = $targetPath . "myfilename.png";
Or you can use this function:
function add_s($file){
$fName = substr($file, 0,strpos($file, "."));
$fExtension = substr($file, strpos($file, "."));
$newFName = $fName."_s".$fExtension;
return $newFName;
}
You should use pathinfo and move_uploaded_file
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/'; // should make this more secure, like a fixed path or in a whitelist
$targetPath = str_replace('//','/',$targetPath);
$ext = pathinfo($_FILES['Filedata']['name'], PATHINFO_EXTENSION);
$basename = pathinfo($_FILES['Filedata']['name'], PATHINFO_BASENAME);
$targetFile = $targetPath . $basename . "_s" . $ext;
move_uploaded_file ( $tempFile , string $targetFile)
//tamano_nuevo_foto($stempFile, 420, $stargetFile); // move and resize ??
I'm currently getting to know more with uploadify, which by the way is what I'm using on my Wordpress plugin. I got the uploading of file correctly; it's job is to upload single .pdf files only. When I tried uploading the same file twice and checked the folder where the uploaded files will be stored, I only have a single file. I guess it's being overwritten knowing the file already exists on the folder. What bugs me is that how will I change the filename of the second uploaded file(the same file) such that it will result into 'filename(2)', 'filename(3)' and so on.
Here's my code, enlighten me on where should I start configuring on my uploadify.php:
if (!empty($_FILES)) {
$name = $_FILES['Filedata']['name'];
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
$path = pathinfo($targetFile);
$newTargetFile = $targetFolder.$name;
// Validate the file type
$fileTypes = array('pdf'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
// i think somewhere here , will i put something, but what's that something?
move_uploaded_file($tempFile,$newTargetFile);
echo $newTargetFile;
} else {
echo 'Invalid file type.';
}
return $newTargetFile;
}
Change this:
$newTargetFile = $targetFolder.$name;
To this:
$i = 2;
list( $filename, $ext) = explode( '.', $name);
$newTargetFile = $targetFolder . $filename . '.' . $ext;
while( file_exists( $newTargetFile)) {
$newTargetFile = $targetFolder . $filename . '(' . ++$i . ')' . '.' . $ext;
}
Try this:
<?php
function get_dup_file_name($file_name) {
$suffix = 0;
while (file_exists($file_name . ($suffix == 0 ? "" : "(" . $suffix . ")"))) {
$suffix++;
}
return $file_name . ($suffix == 0 ? "" : "(" . $suffix . ")");
}
?>
I am uploading files using jQuery uploadify plugin. All files are uploaded into same directory. When I try to upload a file twice, it give me following error.
filename.gif (4.3KB) - IO Error
I want to upload a file with unique name every time. There are many other users uploading files in same directory. So there is a chance that two users share same file name. How can I avoid overwritten.
My Code:
$('.SingleFileUpload').uploadify({
'uploader' : '/uploadify/uploadify.swf',
'script' : '/uploadify/uploadify.php',
'cancelImg' : '/uploadify/cancel.png',
'folder' : '/uploads',
'auto' : true,
'queueID' : 'fileQueue',
'removeCompleted':false,
'onComplete' : function(event, ID, fileObj, response, data) {
$(event.target).closest('form').append( '<input type="hidden" name="uploaded_file" value="' + response + '">' );
}
});
To start off, reject duplicate file names:
$targetFolder = '/uploads'; // Relative to the root
if (!empty($_FILES)) {
$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)) {
if (file_exists($targetFile)){
echo 'File does already exist, choose another name!';
}
else {
move_uploaded_file($tempFile,$targetFile);
echo '1';
}
} else {
echo 'Invalid file type.';
}
}
?>
You can prefix all of your file names by the ID of the user + an underscore (or any character to separate the ID from the file name, to avoid UID1 + 2file == UID12 + file.
Instead of forcing the user to choose another name, you can also implement an automated name change: Either by adding a prefix and/or postfix, or by calculating the hash of the file. The last option also prevents duplicate files (same name, same contents) from appearing at the server.
I don't think using javascript is good or safe for this, one method I use is to name each file by calculate its SHA1 on server side.
I'm duplicating the filename and adding the copynr at the end. like:
filename(2)
filename(3)
filename(4) etc.
$('#upload').uploadify({
'uploader' : 'resources/plugins/uploadify/uploadify.swf',
'script' : 'resources/plugins/uploadify/uploadify.php',
'cancelImg' : 'resources/plugins/uploadify/cancel.png',
'folder' : 'uploads/',
'auto' : true,
'multi' : false,
'fileDesc' : '*.jpg;*.jpeg;*.png;*.gif;',
'fileExt' : '*.jpg;*.jpeg;*.png;*.gif;',
onComplete: function (evt, queueID, fileObj, response, data){
alert(response); // = uploaded filename
}
just the uploadify JS part (not using the check method!)
Now the uploadify.php part
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$ext = '.'.pathinfo($_FILES['Filedata']['name'], PATHINFO_EXTENSION);
$filename = substr($_FILES['Filedata']['name'],0,-strlen($ext));
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $filename . $ext;
while(file_exists($targetFile)){
preg_match('/\([0-9]{1,}\)$/', $filename,$matches);
if(!empty($matches)){
preg_match('/[0-9]{1,}/', $matches[0],$nr);
$filename = substr($filename,0,-strlen($matches[0])) . '('.(((int)$nr[0])+1).')';
}else
$filename .= '(2)';
$targetFile = str_replace('//','/',$targetPath) .$filename . $ext;
}
if(!is_dir($targetPath)) mkdir(str_replace('//','/',$targetPath), 0755, true);
move_uploaded_file($tempFile,$targetFile);
echo $filename.$ext;}
HTH