I am very new to javascript and ajax and I would like to do the folowing:
I have got a page where you can select the name of the person you want to upload a file. Then, through javascript you get that name in a variable and through ajax you pass the variable to a .php file where the upload takes place. The problem is that no name is passed and the file is upload in the same folder where all the names of the people are, not inside one of them. Here is the code I have got for the moment:
SOME NEW EDITS IN THE CODE
html
<select id="cuadro" name="op-cliente">
<option>bbraun</option>
<option>biosystems</option>
<option>seat</option>
<option>tradsp</option>
<option>tradin</option>
<option>vanderlande</option>
</select>
<script type="text/javascript">
$(function() {
// Setup html5 version
$("#uploader").pluploadQueue({
// General settings
runtimes : 'html5,flash,silverlight,html4',
url : 'plupload/examples/upload.php',
multipart_params: {'valor' : $('#cuadro').val()},
chunk_size: '5mb',
rename : true,
dragdrop: true,
filters : {
// Maximum file size
max_file_size : '500mb',
// Specify what files to browse for
mime_types: [
]
},
flash_swf_url : 'plupload/js/Moxie.swf',
silverlight_xap_url : 'plupload/js/Moxie.xap'
});
});
</script>
php
$valor = $_REQUEST['valor'];
$targetDir = ".." . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "uploads" . DIRECTORY_SEPARATOR . $valor;
$cleanupTargetDir = true; // Remove old files
$maxFileAge = 7 * 24 * 3600; // Temp file age in seconds
// Create target dir
if (!file_exists($targetDir)) {
#mkdir($targetDir);
}
// Get a file name
if (isset($_REQUEST["name"])) {
$fileName = $_REQUEST["name"];
} elseif (!empty($_FILES)) {
$fileName = $_FILES["file"]["name"];
} else {
$fileName = uniqid("file_");
}
$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
// Chunking might be enabled
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
// Remove old temp files
if ($cleanupTargetDir) {
if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
}
while (($file = readdir($dir)) !== false) {
$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
// If temp file is current file proceed to the next
if ($tmpfilePath == "{$filePath}.part") {
continue;
}
// Remove temp file if it is older than the max age and is not the current file
if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
#unlink($tmpfilePath);
}
}
closedir($dir);
}
And this last time I got something that could be revealing: if I change this: multipart_params: {'valor' : $('#cuadro').val()}, to this: multipart_params: {'valor' : '5'}, it works and creates a folder called "5"....
Thank you very much for your time
I see you're passing it as a GET value. Therefore the variable is not in the POST.
Change
$_POST['valor']; to $_GET['valor'];
An Alternative
<select id="cuadro" name="op-cliente">
<option>bbraun</option>
<option>biosystems</option>
<option>seat</option>
<option>tradsp</option>
<option>tradin</option>
<option>vanderlande</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
$('#cuadro').change(function(){
var selectedValue = $("#cuadro").val();
$.ajax({url:"plupload/examples/upload.php?valor="+selectedValue,cache:false,success:function(result){
alert("success");
}});
});
</script>
upload.php (For this way, use $_GET to get valor.)
$targetDir = ".." . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR .
"uploads" . DIRECTORY_SEPARATOR . $_GET['valor'];
the problem i think you face is because you send the name of the person in one request and the file in an other request but if you send them in the same request you will get the wanted result i have tested this and it works for me.
this is index.php
<html>
<head>
<script type="text/javascript" src="jquery-1.12.0.js"></script>
<script type="text/javascript">
$(function(){
$('#my_Form').on('submit',function(e){
e.preventDefault();
var $form=$(this);
var fd = (window.FormData)? new FormData($form[0]) : null;
var data=(fd !==null)? fd : $form.serialize();
$.ajax($form.attr('action'),{
type:$form.attr('method'),
contentType:false,
processData:false,
dataType:'json',
data:data,
success:function(response){alert("sucess");},
error:function(response){alert("update failre");}
});
});
});
</script>
</head>
<body>
<form id="my_Form" action="upload.php" method="POST" enctype="multipart/form-data">
<fieldset>
<select name="person" >
<option value="jhon">jhnon</option>
<option value="albert">albert</option>
<option value="achabahe">achabahe</option>
<option value="Tom">Tom</option>
</select>
<input type="file" name="myFile"/>
<input type="submit" value="Upload"/>
</fieldset>
</form>
</body>
</html>
and this is upload.php
<?php
$tempFile=$_FILES['myFile']['tmp_name'];
$targetDir = ".." . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "uploads" . DIRECTORY_SEPARATOR . $_POST['person'];
$uploadedFileName= $_FILES['myFile']['name'];
$maxFileAge=7*24*3600;
$cleanUpTargetDir=true;
if(!file_exists($targetDir)){
#mkdir($targetDir);
}
if($dir=opendir($targetDir)){
while($file=readdir($dir)) {
$file=$targetDir.DIRECTORY_SEPARATOR.$file;
if(filemtime($file)<(time() - $maxFileAge )){
#unlink($file);
}
}
}else{
die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
}
$filePath= $targetDir . DIRECTORY_SEPARATOR .$uploadedFileName;
move_uploaded_file($tempFile,$filePath);
?>
Related
we have construct the one secret URL for my application.i have PHP script how to change java script any one help me to solve the issue
Below mentioned script how to change java script in c# application
i have php script this to change javascript
<html>
<title>Live</title>
<head>
<script src="http://content.jwplatform.com/libraries/Y09dkRGs.js"></script>
<script>jwplayer.key = "ti8UU55KNdJCPX+oWrJhLJNjkZYGiX13KS7yhlM7Ok/wmU3R";</script>
</head>
<body>
<?php
function bg_gen_secure_uri($file, $directory, $secret, $expiry=0, $allowed_countries='',
$disallowed_countries='', $allowed_ip='', $allowed_useragent='',
$allowed_metros='', $disallowed_metros='',
$progressive_start='', $progressive_end='',
$extra_params='') {
if ($file==''||$secret=='') {
return false;
}
// Construct the values for the MD5 salt ...
if (substr($expiry,0,1)=='=') {
$timestamp=substr($expiry,1);
} else if ($expiry > 0) {
$now=time(); // use UTC time since the server does
$timestamp=$now+$expiry;
} else {
$timestamp=0;
}
if ($allowed_countries) {
$allowed_countries='&a='.$allowed_countries;
}
if ($disallowed_countries) {
$disallowed_countries='&d='.$disallowed_countries;
}
if ($allowed_ip) {
$allowed_ip='&i='.$allowed_ip;
}
if ($allowed_useragent) {
$allowed_useragent='&u='.$allowed_useragent;
}
if ($progressive_start!='') {
$progressive_start='&start='.$progressive_start;
}
if ($progressive_end) {
$progressive_end='&end='.$progressive_end;
}
if ($allowed_metros) {
$allowed_metros='&am='.$allowed_metros;
}
if ($disallowed_metros) {
$disallowed_metros='&dm='.$disallowed_metros;
}
if ($extra_params) {
$extra_params=urldecode($extra_params);
}
// Generate the MD5 salt ...
if ($directory == '') {
$salt = $secret . $file . '?e=' . $timestamp . $allowed_countries .
$disallowed_countries . $allowed_metros . $disallowed_metros . $allowed_ip .
$allowed_useragent . $progressive_start . $progressive_end;
} else {
$salt = $secret . $directory . '?e=' . $timestamp . $allowed_countries .
$disallowed_countries . $allowed_metros . $disallowed_metros . $allowed_ip .
$allowed_useragent . $progressive_start . $progressive_end;
}
// Generate the MD5 hash ...
$hash_code = md5($salt);
// Generate the link ...
$url = $file . '?e=' . $timestamp . $allowed_countries . $disallowed_countries .
$allowed_metros . $disallowed_metros . $allowed_ip . $allowed_useragent .
$progressive_start . $progressive_end . '&h=' . $hash_code . $extra_params;
return $url;
}
function get_secure_url($file,$directory,$secret) {
$expiry=3600;
$allowed_countries='';
$disallowed_countries='';
$allowed_ip='';
$allowed_useragent='';
$allowed_metros='';
$disallowed_metros='';
$progressive_start='';
$progressive_end='';
$extra_params='&bgsecuredir=1';
return bg_gen_secure_uri($file, $directory, $secret, $expiry, $allowed_countries, $disallowed_countries, $allowed_ip, $allowed_useragent, $allowed_metros, $disallowed_metros, $progressive_start, $progressive_end, $extra_params);
}
$url = 'http://tv.live-s.cdn.bitgravity.com/cdn-live/_definst_/tv'.get_secure_url('/secure/live/tv/playlist.m3u8','/tv/secure/','kkkfdashfsdiads');
?>
<div>
<div id="player">
<div id="myElement"> </div>
<script type="text/javascript">
jwplayer("myElement").setup({
file: '<?=$url?>',
width: '100%',
aspectratio: '16:9',
stretching:'exactfit',
autostart: false,
androidhls: true,
skin: 'vapor',
primary: 'html5'
});
</script>
</div>
</div>
Install Composer from http://getcomposer.org/
Add the "base-reality/php-to-javascript": ">=0.0.3" to your project's
composer.json file:
"require":{ "base-reality/php-to-javascript": "0.1.16" }
Or the latest tagged version. The dev master should only be used for
development, not production.\
Include the Composer SPL autoload file in your project:
require_once('../vendor/autoload.php');
Call the converter:
$phpToJavascript = new PHPToJavascript\PHPToJavascript();
$phpToJavascript->addFromFile($inputFilename); $jsOutput =
$phpToJavascript->toJavascript();
$jsOutput will now contain an auto-generated Javascript version of
the PHP source file.
Hope this helps!
Thanks
You can convert PHP syntax to JS with https://gitlab.com/kornelski/babel-preset-php
I'm trying to create a specific module to upload files.
I'm using this code:
Client side:
<?php
// No direct access
defined('_JEXEC') or die; $resposta =""; ?>
<form name="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file_upload" />
<input type="submit" name="submit_file" value="submit_file"/>
<input type="text" name="resposta" value=<?php echo $resposta; ?> />
</form>
My module:
<?php
defined('_JEXEC') or die;
include_once __DIR__ . '/helper.php';
//trigger the event
// Instantiate global document object
defined('_JEXEC') or die;
// Include the syndicate functions only once
require_once dirname(__FILE__) . '/helper.php';
$resposta = ModuploadfileHelper::getuploadfile($params);
require JModuleHelper::getLayoutPath('mod_upload_file');
?>
My helper:
<?php
class ModuploadfileHelper {
public static function getuploadfile($params) {
/*
* File upload example
*/
//Retrieve file details from uploaded file, sent from upload form
$file = JFactory::getApplication()->input->get('file_upload');
//Import filesystem libraries. Perhaps not necessary, but does not hurt
jimport('joomla.filesystem.file');
//Clean up filename to get rid of strange characters like spaces etc
$filename = JFile::makeSafe($file['name']);
//Set up the source and destination of the file
$src = $file['tmp_name'];
$dest = JPATH_COMPONENT . DS . "uploads" . DS . $filename;
if(!JFolder::exists($dest))
{
$mode = 0755;
JFolder::create($dest, $mode);
}
$resposta = null;
//First check if the file has the right extension, we need jpg only
if (strtolower(JFile::getExt($filename)) == 'jpg')
{
// TODO: Add security checks
if (JFile::upload($src, $dest))
{
$resposta = "Sucesso ao arquivar a imagem";
}
else
{
$resposta = "Insucesso ao arquivar a imagem";
}
}
else
{
$resposta = "O ficheiro não é uma imagem";
}
return $resposta;
}
}
?>
First question: Does something like this work?
Second question: How to perform a trigger for the module to work?
Thirteenth question: How to pass the module to ajax?
I have something like this:
Module code:
<?php
defined('_JEXEC') or die;
include_once __DIR__ . '/helper.php';
// Instantiate global document object
defined('_JEXEC') or die;
// Include the syndicate functions only once
require_once dirname(__FILE__) . '/helper.php';
$resposta = ModuploadfileHelper::getuploadfile($params);
defined('_JEXEC') or die;
include_once __DIR__ . '/helper.php';
// Instantiate global document object
$doc = JFactory::getDocument();
$js = <<<JS
(function ($) {
$(document).on('click', 'input[type=submit]', function () {
formdata = new FormData();
var file = this.files[0];
formdata.append("image", file);
$.ajax({
type : 'POST',
data : request,
success: function (response) {
$('.search-results').html(response);
}
});
return false;
});
})(jQuery)
JS;
$doc->addScriptDeclaration($js);
require JModuleHelper::getLayoutPath('mod_upload_file');
?>
Help me please.
It is possible, what you need to do, is to use the Joomla ajax interface.
See the documentation here: https://docs.joomla.org/Using_Joomla_Ajax_Interface
There is a full example of a module implementing this, that you can easily modify to adapt to file upload:
https://github.com/Joomla-Ajax-Interface/Ajax-Session-Module
Hello I have a view file and controller, what makes multiple inputs where I can upload files in to folder, but its uploading only one file in to folder. I know what is problem, but I dont know how to fix this or how to do this.
My Controller:
public function uploadFile() {
$filename = '';
if ($this->request->is('post')) { // checks for the post values
$uploadData = $this->data['files'];
//print_r($this->data['files']); die;
if ( $uploadData['size'] == 0 || $uploadData['error'] !== 0) { // checks for the errors and size of the uploaded file
echo "Failide maht kokku ei tohi olla üle 5MB";
return false;
}
$filename = basename($uploadData['name']); // gets the base name of the uploaded file
$uploadFolder = WWW_ROOT. 'files'; // path where the uploaded file has to be saved
$filename = $filename; // adding time stamp for the uploaded image for uniqueness
$uploadPath = $uploadFolder . DS . $filename;
if( !file_exists($uploadFolder) ){
mkdir($uploadFolder); // creates folder if not found
}
if (!move_uploaded_file($uploadData['tmp_name'], $uploadPath)) {
return false;
}
echo "Sa sisestasid faili(d): $filename";
}
}
My View file:
<?php
echo $this->Form->create('uploadFile', array( 'type' => 'file'));
?>
<div class="input_fields_wrap">
<label for="uploadFilefiles"></label>
<input type="file" name="data[files]" id="uploadFilefiles">
</div>
<button type="button" class="add_field_button">+</button> <br><br>
<form name="frm1" method="post" onsubmit="return greeting()">
<input type="submit" value="Submit">
</form>
<?php
echo $this->Html->script('addFile');
And this script what Im using in View :
$(document).ready(function() {
var max_fields = 3;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append("<div><input type='file' name='data[files]' id='uploadFilefiles'/><a href='#' class='remove_field'>Kustuta</a></div>");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
I think that, the problem is in input names. If Im doing more inputs, then the inputs names are same, and thanks to this its uploading only one file in to webroot/files folder, but I want these all.
Can anybody help me or give me some tips.
Thanks !
Here is someone with almost exactly the same issue as you have:
Create multiple Upload File dynamically
Try doing the same. I haven't programmed PHP for quite some time, but I guess you should replace data[files] to just data[], so it creates a new array item for each field. Now you are giving each field the same name.
Then you can loop over them in your controller by using:
foreach($_FILES['data'] as $file){
//do stuff with $file
}
EDIT 2:
As you are saying, you want to upload the files (not to a db). So I guess this should work:
public function uploadFile() {
$filename = '';
if ($this->request->is('post')) { // checks for the post values
$uploadData = $this->data;
foreach($uploadData as $file){
if ( $file['size'] == 0 || $file['error'] !== 0) { // checks for the errors and size of the uploaded file
echo "Failide maht kokku ei tohi olla üle 5MB";
return false;
}
$filename = basename($file['name']); // gets the base name of the uploaded file
$uploadFolder = WWW_ROOT. 'files'; // path where the uploaded file has to be saved
$filename = $filename; // adding time stamp for the uploaded image for uniqueness
$uploadPath = $uploadFolder . DS . $filename;
if( !file_exists($uploadFolder) ){
mkdir($uploadFolder); // creates folder if not found
}
if (!move_uploaded_file($file['tmp_name'], $file)) {
return false;
}
echo "Sa sisestasid faili(d): $filename";
}
}
}
Try this function:
function multi_upload($file_id, $folder="", $types="") {
$all_types = explode(",",strtolower($types));
foreach($_FILES[$file_id]['tmp_name'] as $key => $tmp_name ){
if(!$_FILES[$file_id]['name'][$key]){
$return[$key]= array('','No file specified');
continue;
}
$file_title = $_FILES[$file_id]['name'][$key];
$ext_arr = pathinfo($file_title, PATHINFO_EXTENSION);
$ext = strtolower($ext_arr); //Get the last extension
//Not really uniqe - but for all practical reasons, it is
$uniqer = substr(md5(uniqid(rand(),1)),0,5);
$file_name = $uniqer . '_' . $file_title;//Get Unique Name
if($types!=''){
if(in_array($ext,$all_types));
else {
$result = "'".$_FILES[$file_id]['name'][$key]."' is not a valid file."; //Show error if any.
$return[$key]= array('',$result);
continue;
}
}
//Where the file must be uploaded to
if($folder) $folder .= '/';//Add a '/' at the end of the folder
$uploadfile = $folder . $file_name;
$result = '';
//Move the file from the stored location to the new location
if (!move_uploaded_file($_FILES[$file_id]['tmp_name'][$key], $uploadfile)) {
$result = "Cannot upload the file '".$_FILES[$file_id]['name'][$key]."'"; //Show error if any.
if(!file_exists($folder)) {
$result .= " : Folder don't exist.";
} elseif(!is_writable($folder)) {
$result .= " : Folder not writable.";
} elseif(!is_writable($uploadfile)) {
$result .= " : File not writable.";
}
$file_name = '';
}
else {
if(!$_FILES[$file_id]['size']) { //Check if the file is made
#unlink($uploadfile);//Delete the Empty file
$file_name = '';
$result = "Empty file found - please use a valid file."; //Show the error message
}
else {
#chmod($uploadfile,0777);//Make it universally writable.
}
}
$return[$key]=array($file_name,$result);
}
return $return;
}
html: <input type="file" name="data_file[]" id="uploadFilefiles">
Call by multi_upload("data_file","upload_to_folder","pdf,jpg,txt,bmp")
I am using some jquery to help upload a file to a php script. Everything is working fine and the file does in fact get uploaded. But during the upload, I have made it so the file gets resized to our needs, with a new unique file name. I'd like to pass that new unique file name back to the jquery and have it display on the page. Right now, it just displays the original image (which is not resized)
Here's the jquery code:
$(function(){
var btnUpload=$('#upload');
var status=$('#status');
new AjaxUpload(btnUpload, {
action: 'upload-file.php',
name: 'uploadfile',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
// extension is not allowed
status.text('Only JPG, PNG or GIF files are allowed');
return false;
}
status.text('Uploading...');
},
onComplete: function(file, response){
//On completion clear the status
status.text('');
//Add uploaded file to list
if(response==="success"){
$('<li></li>').appendTo('#files').html('<img src="./uploads/'+file+'" alt="" /><br />'+file).addClass('success');
} else{
$('<li></li>').appendTo('#files').text(file).addClass('error');
}
}
});
});
And then my upload php file looks like this:
$uploaddir = 'uploads';
$file = $uploaddir . basename($_FILES['uploadfile']['name']);
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
$path = realpath(dirname(__FILE__));
include $path . '/uploads/phmagick.php';
$temp_file = explode(".", $_FILES['uploadfile']['name']);
$time = time();
$new_file = $time . '.' . $temp_file[1];
$p = new phmagick($path . '/uploads/' . $_FILES['uploadfile']['name'], $path . '/uploads/' . $new_file);
$p->convert();
$phMagick = new phMagick($path . '/uploads/' . $new_file, $path . '/uploads/' . $new_file);
$phMagick->debug=true;
$phMagick->resize(414,414,true);
echo "success";
} else {
echo "error";
}
Any thoughts on how I can get the new unique file name back, which would be something like: 1397413326.jpg?
Thank you
Echo the filename back instead of the word "success".
I am using uploadify and my problem is that the files are not uploading.
This is my code:
On uploadify.php I've set the root path to: /
Like this:
$targetFolder = '/'; // Relative to the root
Then the rest on the script:
<script type="text/javascript">
jQuery(document).ready(function() {
$('#file_upload').uploadify({
'uploader' : '/myIncludes/UploadiftyFolder/uploadify.php',
'swf' : '/myIncludes/UploadiftyFolder/uploadify.swf',
'cancelImg' : '/myIncludes/UploadiftyFolder/cancel.png',
'folder' : '/myUploads/UploadsDirectory/images/',
'auto' : true,
'multi' : false,
'checkExisting' : false
});
});
</script>
//Finally
<input id="file_upload" type="file" name="Filedata" />
Upload Files
When I try to upload an image it all works well (seems too) and it says - Complete ...
But nothing is being uploaded.
Any ideas?
UPDATE:
Here are my server structure paths:
My Paths:
root/myIncludes/UploadiftyFolder/ <--Here are all the uploadify files
root/myUploads/UploadsDirectory/images/ <--Here is where I need to upload
Here are my current settings on uploadify:
folder --> '/myUploads/UploadsDirectory/images/',
and in uploadify.php --> $targetFolder = '/'; // Relative to the root
Here is the rest of the uploadify.php file ... I haven't changed anything there:
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)) {
move_uploaded_file($tempFile,$targetFile);
echo '1';
} else {
echo 'Invalid file type.';
}
}
For me, the problem was in the uploadify.php file. They are using:
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
$targetFolder is defined by you at the top.
and then later:
move_uploaded_file($tempFile,$targetFile);
The default example appends the target folder to the end of $_SERVER['DOCUMENT_ROOT']. My $_SERVER['DOCUMENT_ROOT'] was actually C:\xampp\htdocs. So, to make it work your target folder would have to be:
$targetFolder = "/yourSiteFolder/wherever/your/upload/folder/is";
What I did:
Got rid of $_SERVER['DOCUMENT_ROOT'] altogether. Here is my uploadify.php file:
<?php
/*
Uploadify v3.1.0
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
// Define a destination
//$targetFolder = '/sandbox/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)) {
move_uploaded_file($_FILES["Filedata"]["tmp_name"], "uploads/" . $_FILES["Filedata"]["name"]);
echo '1';
} else {
echo 'Invalid file type.';
}
}
?>
The major change is that I've replaced this:
move_uploaded_file($tempFile,$targetFile);
with this:
move_uploaded_file($_FILES["Filedata"]["tmp_name"], "uploads/" . $_FILES["Filedata"]["name"]);
And then commented out several lines that weren't needed anymore.
And this is my check-exists.php file:
<?php
/*
Uploadify v3.1.0
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
// Define a destination
//$targetFolder = 'uploads'; // Relative to the root and should match the upload folder in the uploader script
if (file_exists("uploads/" . $_POST['filename'])) {
echo 1;
} else {
echo 0;
}
?>
And this is my jquery code:
$(function() {
$("#uploadify").uploadify({
height : 30,
swf : 'uploadify/uploadify.swf',
uploader : 'uploadify/uploadify.php',
width : 120
});
});
A note about the file structure of my site:
All the uploadify files are in the root of my site in a folder called uploadify. Within uploadify is a folder called uploads and this is where the files are uploaded.
Hope that helps.
I tried all of the other suggestions here, but none of them worked for me. Then I realized that version 3.2 of Uploadify (and maybe previous versions, too) requires a timestamp and hashed token in order to complete the upload.
First off, I had to move the script from an external JS file to my PHP file so that I could get the timestamp from PHP. (You could also do this via a hidden input value or other method, but this was the simplest way.) Then I had to add the 'formData' option to my Uploadify call along with some PHP code that gets the timestamp and hashes it with a unique salt (which you should change to a random string):
<?php $timestamp = time();?>
<script>
$('#file_upload').uploadify({
'swf' : '/uploadify/uploadify.swf',
'uploader' : '/uploadify/uploadify.php',
'formData' : {
'timestamp' : '<?php echo $timestamp;?>',
'token' : '<?php echo md5("unique_salt" . $timestamp);?>'
}
});
</script>
Although this code seems to be required in version 3.2, it is not mentioned in the implementation documentation. I had to look in the index.php file that came in the download package to find it.
Try giving "~/" before uploads folder
(Or) here is the entire script:
<script type="text/javascript">
$(window).load(
function () {
$("#fileInput1").uploadify({
'uploader': 'scripts/uploadify.swf',
'cancelImg': 'images/cancel.png',
'buttonText': 'Browse Files',
'script': 'UploadVB.ashx',
'folder': 'uploads',
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
'queueSizeLimit': 9999,
'simUploadLimit': 2,
'sizeLimit': 4000000,
'multi': true,
'auto': true,
'onComplete': function (event, queueID, fileObj, response, data) {
$("#thumbnail").append(response)
},
'onError': function (event, ID, fileObj, errorObj) {
alert(errorObj.type + ' Error: ' + errorObj.info);
}
});
}
);
</script>
For me, all I had to do was get rid of $_SERVER['DOCUMENT_ROOT'] in the $targetPath definition. And then I also used "uploads" instead of "/uploads" as my $targetFolder.