I'm using uploadify on a project, and I've got the php script renaming a single file, but I'm unsure how to repeat the process if more than one file is uploaded at a time?
My php script is below...
$targetFolder = '/img/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;
$fileParts = pathinfo($_FILES['Filedata']['name']);
$unique_hash = hash_hmac("md5", file_get_contents($_FILES['Filedata']['name']), SALT);
$targetFile = rtrim($targetPath,'/') . '/' . $unique_hash .'-'.$_POST['userId'].'.'. $fileParts['extension'];
#$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.';
}
}
When you use ajax, you can send a request for every file just one by one then you wont have to use a foreach or you send the form at once and use the code below here.
When you send all file together you will be using in your form something like this: name=userfile[] so you can foreach the files like this:
foreach ($_FILES as $file)
{
$uploadfile = $uploaddir . basename($file['name']);
if (!move_uploaded_file($file["tmp_name"], $uploadfile))
{
echo set_e('error','Image ['.$i.'] not uploaded','');
}
}
Have you tried to do more than one? Uploadify uses jQuery ajax to process the files? It might look simultaneous but it processes one file at a time via ajax. It will call your upload.php as many times as there are files in the queue. So if your function works for one file, it will for the rest. You just need to make sure it's writing a unique filename in the directory every time the function is called whic it looks like it does. Uploadify handles looping through each file name then calls your upload script.
http://www.uploadify.com/demos/
Look at the network console with Chrome or Firebug and upload a bunch of pictures with on the demo. you'll see the upload.php script is called for each file.
FYI,
I used to use uploadify but I changed to PLUPLOAD http://www.plupload.com/. Supports multiple uploads too but better documented and easier to use with great api's.
Related
I'm attempting to move an uploaded image (from Android) that is to be renamed via the PHP below in the second example so that their names cannot conflict. The original example below uploads files correctly but can have naming conflicts. The error that I'm experiencing is that the move_uploaded_files function fails, which I'm unsure as to why. The directory appears the same but I could be wrong and the problem is that image is never moved from the temp directory. Above all else, I think this is just a directory issue since the original example works. Please let me know if you need more information. The example I'm going by is located here: How to rename uploaded file before saving it into a directory?
Original:
$uploaddir = './appphotos/';
$absPath = 'https://'.$_SERVER['HTTP_HOST'].'/complaint_desk/appphotos/';
$file = basename($_FILES['userfile']['name']);
$uploadFile = $file;
$newName = $uploaddir . $uploadFile;
New Attempt:
$temp = explode(".",$_FILES["userfile"]["name"]);
echo json_encode($temp);
$newfilename = rand(1,99999) . '.' .end($temp);
echo json_encode($newfilename);
$uploadFile = move_uploaded_file($_FILES["userfile"]["name"], "/var/www/complaint_desk/appphotos/" . $newfilename); echo json_encode($uploadFile);
You should use the function as follow:
if(move_uploaded_file($_FILES["userfile"]["tmp_name"], "./appphotos/" . $newfilename)) {
echo json_encode($uploadFile); // why do you want to encode it?
} else {
echo 'File failed to move';
}
Always check the result of move_uploaded_file(). Also, the file is located at $_FILES["userfile"]["tmp_name"] before moving.
Also, $absPath is incorrect. It shouldn't start with http protocol. It should look like /var/www/complaint_desk/appphotos/ or C:/complaint_desk/appphotos/.
I am using Uploadify to upload a file. The filename is randomized by the PHP when uploaded. I need to echo the file name back to the JS. I don't know enough PHP to do this.
Here is my PHP Script:
<?php
$targetFolder = '/uploads';
$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$fileParts = pathinfo($_FILES['Filedata']['name']);
$targetFile = sprintf('%s/%s.%s', $targetPath, uniqid(), $fileParts['extension']);
// 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.';
}
}
?>
If I understand the script correctly where the echo '1' at the bottom of the script is where the file name should be. How do I insert the changed or randomized file name there?
Your $targetFile variable contains the full path to your uploaded file (once moved). If you just want the filename part, use basename(), eg
echo basename($targetFile);
See http://php.net/basename
I am trying to use Uploadify on my site and have it setup with the following uploadify.php:
<?php
// Define a destination
//$targetFolder = '/uploads'; // Relative to the root
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'];
$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 wasn't uploading so I commented out $targetFolder and changed $targetPath so that it is just the document root. This results in $targetFile being /home/user/public_html/example.com/file.txt when I try to upload file.txt with Uploadify. The folder is set to 755. I'm at a loss as to what the problem could be. I am otherwise using a vanilla install of Uploadify and everything seems to work fine except that the file never actually goes where it should.
It was an issue with the folder permissions not staying set to 755. I logged out of and back into cPanel and everything's working now.
I am using Uploadify for my script.
The main page:
<?php
session_start();
var_dump($_SESSION);
$uploaded_files = $_SESSION['uploaded_files'];
?>
//Uploadify, HTML forms and more (not related, No PHP in this section)
uploadify.php:
<?php
session_start();
require_once('includes/functions.php');
// Define a destination
$targetFolder = 'uploads/temp'; // Relative to the root
if (!empty($_FILES)) {
$fileParts = pathinfo($_FILES['Filedata']['name']);
$file_hash = GenRndStr(20) . '.' . $fileParts['extension'];
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $file_hash;
// Validate the file type
$fileTypes = array(); // File extensions
move_uploaded_file($tempFile, $targetFile);
$_SESSION['uploaded_files'][] = $file_hash;
echo '1';
}
?>
I'm sure it gets to the $_SESSION['uploaded_files'][] = $file_hash; part, since the actual file is uploaded to the directory. My problem is that the var_dump of $_SESSION['uploaded_files'] returns null.
The files are in the same directory level.
Thanks in advance.
I found the solution. The problem is that Uploadify's flash version is treated as a different client for the server, therefore the server creates a new session id for it.
I followed this topic: http://www.uploadify.com/forum/#/discussion/43
Hope it'll help others.
I'm using the Uploadify jQuery plugin for PHP to upload a file. One thing I am stuck on is that I need to be able to rename the file being uploaded so that I can post that information to my script that inserts data into the mysql database. Can anyone please advise on how to do this?
Thanks,
Jake
Firstly rename the filename as you want in your uploadify.php
Then you just need to return $targetPath from your uploadify.php file, like this --
echo $targetPath
no need to use echo '1'
And now you have to get the renamed file name. You can get this in onUploadSuccess function.
onUploadSuccess() takes three parameters (file, data, response),
where file gives you the actual name of file you browsed through your computer, and data gives you the renamed file name which you generated through your uploadify.php code as per your requirement.
So you can try the below code --
'onUploadSuccess' : function(file, data, response) {
alert('Renamed file name is - ' + data);
}
I hope this will help out. One of my friend told me this, and I got my work done then :)
you can do like this :-
$targetFolder = FCPATH.'/resources/images/users/temp/'; // Relative to the root
if (!empty($image))
{
$time=strtotime("now");
$image['Filedata']['name']=$time.'.jpg';
$tempFile = $image['Filedata']['tmp_name'];
$targetPath = $targetFolder.$image['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($image['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes))
{
move_uploaded_file($tempFile,$targetPath);
echo '1';
}
else
{
echo 'Invalid file type.';
}
}
If you use uploadify.php just go right before the function move_uploaded_files and change the target name.
Anyways you do it this should work. Post the code you have if you want a more detailed answer.
This will put file in new folder with same file name as source file
$source = $_FILES['Filedata']['tmp_name'];
$filename = $_FILES['Filedata']['name'];
$newPath = $folder.'/'.$filename;
rename($source, $newPath);
/*----------------------*/
to have a new filename
function getExtension($path)
{
$result = substr(strtolower(strrchr($path, '.')), 1);
$result = preg_replace('/^([a-zA-Z]+)[^a-zA-Z].*/', '$1', $result);
if ($result === 'jpeg' || empty($result) === true) {
$result = 'jpg';
}
return $result;
}
$source = $_FILES['Filedata']['tmp_name'];
$filename = $_FILES['Filedata']['name'];
$newfileName=$folder."/"."abc".getExtension($filename);
rename($source, $newfileName);