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
Related
I have a form in which I have a textarea showing the result of reading a file (via PHP); I want it to edit and pressing a button, store it back
<?php
$salida = file_get_contents($path);
echo "<textarea rows='10' cols='100' id='file' name='file'>" . "$salida" . "</textarea>";
?>
Saving method (JS)
document.getElementById('btn-save').addEventListener('click', function(e) {
e.preventDefault();
request({
method: 'GET',
url: 'actions/save.php?file='+document.getElementById('file').value
}, function(ok) {
...
}, function(ko) {
...
});
});
save.php
<?php
$TEMP = '/tmp/file.tmp';
if (isset($_GET['file']))
{
$fh = fopen($TEMP, "w+");
$string = $_GET['file'];
fwrite($fh, $string); // Write information to the file
fclose($fh); // Close the file
}
The file is like:
line1=a
line2=b
line3=c
Problem is: when reading, it shows all the lines correctly; but when saving (methods above), the file appears like:
line1=aline2=bline3=c
What do I need to preserve the breaks in the file?
Thanks in advance
You could use the built in nl2br() function on the output of that file:
<?php
$salida = file_get_contents($path);
echo "<textarea rows='10' cols='100' id='file' name='file'>" . nl2br($salida) . "</textarea>";
?>
You should use POST method not GET. If your file will contain more then GET limit then you lost content.
document.getElementById('btn-save').addEventListener('click', function(e) {
e.preventDefault();
request({
method: 'POST',
url: 'actions/save.php',
data: {content: document.getElementById('file').value}
}, function(ok) {
...
}, function(ko) {
...
});
});
and PHP file
if (isset($_POST['content']))
{
$fh = fopen($TEMP, "w+");
$string = $_POST['content'];
fwrite($fh, $string); // Write information to the file
fclose($fh); // Close the file
}
I can't download file.I am trying to download file from server through Ajax. I got success response in Ajax data and also file in response but file was not download what i do and how to fix this issue. The file reads successfully and also sever path get proper. Please help me.
This one is java script when i call function and get response throw ajax
<script type="text/javascript">
function push_file(files)
{
$.ajax
({
type: "post",
url: "<?php echo base_url(); ?>Appointment/download_files/",
data: "files=" + files,
success: function(data)
{
alert('ok' + data);
}
});
}
</script>
PHP code and here i want to download file here and
foreach($results as $row){
$r_id = $row->id;
<td><h5><a onclick="push_file(<?php echo $r_id;?>)"> Download </a></hs><t>
}
Controller
Ajax and PHP perform perfectly and read file but its not download
public function download_files() {
//$this->load->view ( 'ajax/download' );
if($_POST)
{
$base = base_url();
$id = $_POST['files'];
$query = $this->db->query("select userfile from patient_report_file where id='".$id."'");
$result = $query ->row();
$name = $result->userfile;
echo $path = $base."Admin/uploads/patient_report/".$name;
force_download($path, NULL);
}
}
How can I download the file.
You try to download a file through ajax which is impossible (at least the way you did it)
Now you have two options
Option #1 - leave the JS behind (why do you even need JS here - an
alert after downloading is useless imho)
your view should look like
foreach($results as $row)
{
echo '<td><h5> Download </h5></td>';
}
and your controller
public function download_files($id)
{
//$this->load->view ( 'ajax/download' );
$base = base_url();
$id = $_POST['files'];
$query = $this->db->query("select userfile from patient_report_file where id='".$id."'");
$result = $query ->row();
$path = $base."Admin/uploads/patient_report/".$result->userfile;
force_download($path, NULL);
}
Option #2 - is a bit more tricky, because it needs some adaption, i'm not gonna write that code for you, but instead i give you some links to study
Download a file by jQuery.Ajax
https://github.com/eligrey/FileSaver.js/
download file using an ajax request
Overall i'm not judging your code but you did a pretty bad job in order to use CI properly ;)
If you want using method POST that this is my solution:
crsf enable:
<script>
function push_file(files)
{
$('<form action="<?php echo site_url('admin/others/test');?>" method="post"><input type="hidden" name="files" value="'+files+'"><input type="hidden" name="csrf_token_name" value="<?php echo $this->input->cookie('csrf_cookie_name');?>"></form>').submit();
}
</script>
crsf disable:
<script>
function push_file(files)
{
$('<form action="<?php echo site_url('admin/others/test');?>" method="post"><input type="hidden" name="files" value="'+files+'"></form>').submit();
}
</script>
you must change path controller.
I'm a beginner in jQuery. I really don't know how to do this but have the basic idea.
I'm using this jQuery uploader by Hayageek and I'm trying to move uploaded files to its permanent directory after form submits.
So, this is how it goes. The user first selects the file and the upload to TEMP directory starts and just stores an json array. But then the user accidentally adds a file that he never meant to and wants to remove that file (removing the array object). After correcting his mistake he then submits the form and the files get stored in a permanent directory.
This is what I have:
upload.php:
$output_dir = "uploads/";
if(isset($_FILES["myfile"]))
{
$ret = array();
$error =$_FILES["myfile"]["error"];
//You need to handle both cases
//If Any browser does not support serializing of multiple files using FormData()
if(!is_array($_FILES["myfile"]["name"])) //single file
{
$fileName = $_FILES["myfile"]["name"];
$ret[]= $fileName;
}
else //Multiple files, file[]
{
$fileCount = count($_FILES["myfile"]["name"]);
for($i=0; $i < $fileCount; $i++)
{
$fileName = $_FILES["myfile"]["name"][$i];
$ret[]= $fileName;
}
}
echo json_encode($ret);
}
Delete file:
//This is the part where you unset the array object of a file.
index.php:
<script>
$(document).ready(function()
{
var settings = {
url: "upload.php",
dragDrop:true,
fileName: "myfile",
allowedTypes:"jpg,png,gif,doc,pdf,zip",
returnType:"json",
onSuccess:function(files,data,xhr)
{
// alert((data));
},
showDelete:true,
deleteCallback: function(data,pd)
{
for(var i=0;i<data.length;i++)
{
$.post("delete.php",{op:"delete",name:data[i]},
function(resp, textStatus, jqXHR)
{
//Show Message
$("#status").append("<div>File Deleted</div>");
});
}
pd.statusbar.hide(); //You choice to hide/not.
}
}
var uploadObj = $("#mulitplefileuploader").uploadFile(settings);
});
</script>
<form action="upload.php" name="upload_form" enctype="multipart/form-data" method="POST">
<div>
<label>Message</label>
<textarea name="description" style="min-height:200px;" value="<?php echo $mess; ?>"></textarea>
<div id="mulitplefileuploader">Upload</div>
<div id="status"></div>
<input type="submit" name="submit" value="Create Project">
</div>
</form>
<?php if(isset($_POST['submit'])){
$tmp_file=$_FILES['myfile']['tmp_name'];
$dir="upload/";
$file_name=$_FILES['myfile']['name'];
if(move_uploaded_file($tmp_file,$dir . $file_name)){
echo "success";
}else{echo "failure";}
}
?>
You can refer some of plugins available online.
https://blueimp.github.io/jQuery-File-Upload/basic-plus.html this is one of them...
I have a php file and I have created 2 buttons get and set in the file.
I want to access Get.php file when I click get
<?php
$file = "xxx.json";
include 'Get.php';
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($file,$output);
?>
and Set.php file when I select set button.
<?php
$file = "xxx.json";
include 'Set.php';
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($file,$output);
?>
My file visual.php file contents are:
<!DOCTYPE html>
<meta charset="utf-8">
<?php
$file = "xxx.json";
include 'Get.php';
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($file,$output);
?>
<style>
right {
display:table-cell;
vertical-align:top;
width:300px;
padding:0 5px;
}
<?php
$color=include('Color.php');
echo $color;
?>
</style>
<body>
<div id=tt>
<button type="submit" onclick="get()"> <b>get</b></button>
<button type="submit" onclick="set()"> <b>set</b></button>
</div>
<div id=graph>
<script src="ll.js"></script>
<script src="visual.js"></script>
<script type="text/javascript">
window.onload = function(){
}
<?php
$link=include('Link.php');
echo $link;
?>
</script>
</div>
<body>
I am not sure how can I get the contents for Get.php file and Set.php file. I know that I can call ajax calls. But in that case only I can get the contents of the Get.php or Set.php files.
But how can I also make other data shown below execute in sequential order.
<?php
$file = "xxx.json";
include 'Get.php';
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($file,$output);
?>
I am new to php. Thanks for all your help.
Bes way, is using standard html methods: name-value for form elements
<body>
<form method="GET">
<button type="submit" name="event" value="get"> <b>get</b></button>
<button type="submit" name="event" value="set"> <b>set</b></button>
</form>
<body>
And the php code:
$file = "xxx.json";
switch ($_GET['event'])
{
case 'get': include 'Get.php'; break;
case 'set': include 'Set.php'; break;
}
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($file,$output);
Dmitriy's answer is pretty easy, and clean looking. I like.
Ive made a little longer example, utilizing a class aswell, and commented it throughoutly for you to perhaps learn a little or two. Hope it helps!
<?php
class HandleFile {
protected $file;
//The construct is called, when the object is created. We request the file here.
public function __construct($file = null) {
//Lets check if the file variable is set or not.
if( !is_null($file) ) {
//Lets check if the file actually exists
if( file_exists($file) ) {
//If the file exists, set the class variable.
$this->file = $file;
} else {
//If the file does not exist. Throw an exception
throw new Exception("Construct:: The file " . $file . ", does not exist.");
}
} else {
//If the file variable is not set, throw an exception.
throw new Exception("Construct:: No file specified.");
}
}
//This function will do our actual logic.
public function doAction($fileToInclude) {
//First, check if the file to include exists.
if( file_exists($fileToInclude) ) {
//Include it
include($fileToInclude);
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($this->file,$output);
} else {
//If it does not exist. Throw exception.
throw new Exception("doAction:: File " . $fileToInclude . ", does not exist.");
}
}
}
//Try/catch. Tries the action and if an error is trown, catch it and output the message.
try {
$Handler = new HandleFile("xxx.json");
} catch(Exception $e) {
print $e->getMessage() . "<br>";
}
//Define a helper variable
$action = null;
//If the GET parameter "get" is set, do a get action
if( isset( $_GET['get'] ) ) {
$action = "Get.php";
//If the GET parameter "post" is set, do a post action.
} elseif( isset( $_GET['post'] ) ) {
$action = "Post.php";
}
//If our helper variable has changed, there must be an action to do.
if( !is_null($action) ) {
//Try/catch. Tries the action and if an error is trown, catch it and output the message.
try {
$Handler->doAction($action);
} catch(Exception $e) {
print $e->getMessage() . "<br>";
}
}
?>
<body>
<form action="" method="GET">
<button type="submit" name="get" value="yes"> <b>get</b></button>
<button type="submit" name="post" value="yes"> <b>set</b></button>
</form>
<body>
You're calling a function which isn't set...
why don't you use $_POST
to with 2 different forms
1 hidden input contains the id type
if the type is get then include the get
if the type is set then include the set
this is just an example tho'
I am trying to create a PHP file that the browser will see as a js file, and are using the content-type header. But there's something not working, even though. So my question is, should this be interpreted as a valid .js file?:
<?php
header('Content-Type: application/javascript');
$mysql_host = "localhost";
$mysql_database = "lalalala";
$mysql_user = "lalalalal";
$mysql_password = "lalalallaala";
if (!mysql_connect($mysql_host, $mysql_user, $mysql_password))
die("Can't connect to database");
if (!mysql_select_db($mysql_database))
die("Can't select database");
mysql_query("SET NAMES 'utf8'");
?>
jQuery(document).ready(function() {
var urlsFinal = [
<?php
$result = mysql_query("SELECT * FROM offer_data ORDER BY id_campo DESC");
while($nt = mysql_fetch_array($result)) {
?>
"<?php echo $nt['url']; ?>",
<?php
};
?>
"oiasdoiajsdoiasdoiasjdioajsiodjaosdjiaoi.com"
];
scriptLoaded();
});
In order for your Browser to see your PHP file like a .js file, echo or print the entire PHP page into a string, there will be no need to use any headers, just something like:
// First let's make a secure page called database.php - put in a restricted folder
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
// now let's go over a new technique you'll cherish in the future - page.php
<?php
include 'restricted/database.php'; $db = db();
if($db->connect_errort)die("Can't connect to database. Error:".$db->connect_errno);
$db->query("UPDATE tabelName SET names='utf8' WHERE column='value'");
$sel = $db->query('SELECT * FROM offer_data ORDER BY id_campo DESC');
if($sel->num_rows > 0){
while($nt = $db->fetch_object()){
$output[] = $nt->url;
}
}
else{
die('No records were returned.')
}
$sel->free(); $out = implode("', '", $output); $db->close();
echo "jQuery(document).ready(function(){
var urlsFinal = ['$out'];
// more jQuery here - you may want to escape some jQuery \$ symbols
}"
?>
Now just make sure your script tag looks like:
<script type='text/javascript' src='page.php'></script>