Downloading a file while loading another page - php

The context is this:
The user click on a button
The page is refreshed with new information on the page (echo is used to print html code).
A file.txt is created
The download of the created file should start automatically
With the code below, the file is created and the remaining part of the page is presented, but no download starts. Also, if I click on the link, the download doesn't start, but the txt file is opened in the browser (whilst I want to force the download).
On the other hand, if I comment the javascript and uncomment the header instructions, I refresh the correct page and download the txt file, but the content of that file is wrong (it contains the html code echoed in the rest of the page).
=================NOT WORKING CODE==================
echo "
<form name=\"fn\" action=\"index.php?option=com_comp\" method=\"post\">
// more not related stuff
<input type=\"image\" src=\"".JURI::root().
"components/com_comp/images/download_icon.png\" .
"\" name=\"downloadaddresses\">DOWNLOAD_RESULTS
// more not related stuff";
if($_POST['downloadaddresses_x']!=0) {
$myfilename = "tmp/results.txt";
$fh = fopen($myfilename, 'w');
$recipients = $_POST['recipients'];
$semicolon_separated = implode(";", $recipients);
fwrite($fh, $semicolon_separated);
fclose($fh);
/*header('Content-disposition: attachment; filename='.$myfilename);
header("Content-type: application/octet-stream");*/
echo "<a href=\"".$myfilename."\" id=\"downloadlink\">
This download should start automatically!</a>";
echo "<script type=\"text/javascript\">
newwindow=function{
window.open('".$myfilename."','name','height=400,width=200');
if (window.focus) {newwindow.focus()}}
</script>";
}
========================MORE CODE THAT DOES NOT WORK==================
<script type="text/javascipt">
var el = document.getElementById('downloadlink');
if (document.createEvent) {
var event = document.createEvent(\"MouseEvents\");
event.initEvent(\"click\", true, true);
el.dispatchEvent(event);
}
else if (el.click) {
el.click();
}
</script>

Instead of this click simulation code:
<script type="text/javascipt">
var el = document.getElementById('downloadlink');
if (document.createEvent) {
var event = document.createEvent(\"MouseEvents\");
event.initEvent(\"click\", true, true);
el.dispatchEvent(event);
}
else if (el.click) {
el.click();
}
</script>
Can you use this:
<script type="text/javascript">
location.href = document.getElementById('downloadlink').getAttribute('href');
</script>

Related

Want to perform php using OnClick function without clearing the current web page

This is the js script at the bottom of my wp post.
<script type="text/javascript" src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
var id = 'downloadid';
var data_from_ajax;
$.post('download.php', {id : id}) .done(function(data) {
data_from_ajax = data;
});
function hey() {
document.write(data_from_ajax);
}
</script>
Function hey was being called from a link OnClick function. When using this, the page would successfully perform the php code on download php (update a db then download a file) although it would clear the current page I was on. What I wanted to do was perform the php and keep the current page template. So next I tried using
document.getElementById("download").innerHTML = data_from_ajax;
instead of document.write. I made a div with the id download. Now when I click it, it simply won't perform the php. when I replace the data_from_ajax with a string, it gladly puts it in the div though.
Any help would be great.
EDIT:
my html is
download
<div id='download'>&nbsp</div>
http://jsfiddle.net/7smJE/
From PHP code which you've provided, I think you should replace document.write() in your code with $('#download').html(). This way you don't need to put the returned result in your download div anymore because when PHP page gets loaded it'll do this for you and you have to put your $.post in hey() function too because you need this to perform when your link gets clicked.
PHP:
<?php
$fileid = $id;
if (is_file('d84ue9d/' . $fileid . '.apk'))
{
$ip = $_SERVER['REMOTE_ADDR'];
$con=mysqli_connect("localhost","docvet95_check","%tothemax%","docvet95_downcheck");
$result = mysqli_query($con,"SELECT * FROM `download-check` where ip = '$ip'");
while ($row = mysqli_fetch_array($result))
{
$files = $row['files'];
$downloads = $row['downloads'];
}
if ($downloads > 4)
{
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%61%6C%65%72%74%28%27%59%6F%75%5C%27%76%65%20%64%6F%77%6E%6C%6F%61%64%65%64%20%66%69%76%65%20%6F%72%20%6D%6F%72%65%20%66%69%6C%65%73%2E%20%46%6F%72%20%72%69%67%68%74%20%6E%6F%77%2C%20%74%68%69%73%20%69%73%20%6F%6B%61%79%2E%20%49%6E%20%74%68%65%20%66%75%74%75%72%65%2C%20%79%6F%75%20%77%69%6C%6C%20%6E%65%65%64%20%74%6F%20%63%6F%6D%70%6C%65%74%65%20%61%20%73%75%72%76%65%79%20%69%6E%20%6F%72%64%65%72%20%74%6F%20%63%6F%6E%74%69%6E%75%65%20%64%6F%77%6E%6C%6F%61%64%69%6E%67%2E%20%54%68%61%6E%6B%20%79%6F%75%20%66%6F%72%20%75%73%69%6E%67%20%6F%75%72%20%77%65%62%73%69%74%65%27%29%3B%20%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%2F%61%70%6B%73%2F%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
}
else
{
$downloadq = $downloads + 1;
$there = $result->num_rows;
if ($there <1)
{
$addidnip = mysqli_query($con,"INSERT INTO `download-check` (ip, files, downloads) VALUES ('$ip', '$fileid', 1)");
}
else
{
$idtoarray = explode(",", $files);
if (!in_array($fileid, $idtoarray))
{
array_push($idtoarray, $fileid);
$newfile = implode(",", $idtoarray);
$adddw = mysqli_query($con,"UPDATE `download-check` SET downloads=$downloadq, files='$newfile' where ip = '$ip'");
}
}
print "<script type=\"text/javascript\">";
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
print "</script>";
}
}
else
{ echo 'Whoops, looks like we couldn\'t find that file. You could try searching for it?'; }
?>
JavaScript:
var id = 'downloadid';
var data_from_ajax;
function hey() {
$.post('download.php', {id : id});
}
But I recommend you to return the exact data from your PHP without any extra tag and then use it this way:
var id = 'downloadid';
function hey() {
$.post('download.php', {id : id}).done(function(data) {
$("#download").html(unescape(data));
});
}
From what I can see without the fiddle:
The hey function is probably fired before the done function is ready. Why don't you call hey() from within done()?

upload file using ajax like facebook uploading

My problem is, I want to upload a csv file without pressing a submit button and I used ajax for that case. But now, their is something errors appear, and the error said fopen() Filename cannot be empty. But I already get the file value that I want, but the $_FILES[$fie]['tmp_name'] can't read this value. But if I attach the variable in an alert() they display the exact filename. This is my sample codes.
This is the html:
<form id="Form2">
<input type="file" id="fie" />
</form>
this is the javascript:
<script style="text/javascript">
$(function(){
$('#Form2').change(function(e){
e.preventDefault();
var sub = document.getElementById("fie").files[0].name;
if($('#cat1').hasClass('show')){
$('#cat1').hide();
$('#cat2').html("<img src='pb1.gif' />");
$.ajax({
url:'uploading.php',
action:'get',
data: 'fie='+sub,
success: function(data){
$('#cat2').html(data);
}
});
}
});
});
</script>
This is the Php:
uploading.php
<?php
include("conn.php"); //assuming that connected to a database.
if (isset($_GET['fie'])) {
echo "<script>alert('".$_GET['fie']."')</script>";//IN ALERT THEY EXECUTE THE EXACT VALUE OF THE FILE I INPUT
$fie = $_GET['fie'];
$file = $_FILES[$fie]['tmp_name']; //PROBLEM IS THIS. THEY CAN'T READ THE VALUE AND TELL THEIR IS NO FILE.
$handle = fopen($file,'r') or die ('Cannot open file');
fgets($handle);
do {
if (isset($data[0])) {
mysql_query("INSERT INTO tbl_numbers (numbers,cute) VALUES ('".addslashes($data[0])."','".addslashes($data[1])."')");
}
}
while ($data = fgetcsv($handle,1000,",","'"));
echo "Successful Upload~!";
}
?>
Thanks for the reply.

how do i copy a file on button click?

I want to build a one page utility/prototype that will do the following:
provide the admin user with a drop down box. when they select an option and then click on a submit button, i want to be able to COPY a file from /var/www/mysite/abc.txt to /var/www/mysecondsite/abc.txt
I've written the php / html to display the form, but can I use jquery/ajax to call a function on the same php file?
Here's my code:
<?php
$listofcountries='';
echo "<h2>Select a site</h2>";
echo " <script src='http://myserver/myapp/assets/js/jquery-1.8.1.min.js'></script>";
if ($handle = opendir(dirname(__FILE__)."/secrets/")) {
echo "<input type=text list=site >";
echo "<datalist id=site >";
/* This is the correct way to loop over the directory. */
while (false !== ($entry = readdir($handle))) {
//ignore temporary files, and directories.
if ( (strpos($entry, "~") === false) && !(trim($entry)==".") && !( $entry=="..") ){
//echo "$entry\n<BR>";
$country=getCountryName($entry);
echo "<option>".$country;
}
}
}
closedir($handle);
echo "</datalist>";
echo "<input type=submit id='changert'><BR>";
echo "<script>";
echo "$(document).ready(function(){";
echo " $('#changert').live('click', function() {";
echo " alert('in the changert function'); ";
echo " });";
echo " }); "; //end document ready
echo "</script> "; //end javascript
function getCountryName($fileame)
{
$pattern = '/([a-z]*).([a-z]*).([a-z]*).php/i';
preg_match_all($pattern, $fileame, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
return $match[1];
}
}
in the real version, this solution will be part of a codeigniter solution... so i'll have a proper MVC.
But for now, I'd like to be able to contain all the logic in one file.
Can you tell me how i can do this?
jQuery is just JavaScript so it's all on the client. Any server-side file copying would still need to be handled by your PHP. Simplest solution is just to make an AJAX request on button click which hits your PHP API and passes a token or something so non-session users aren't copying files maliciously.
$('#myButton').on('click', function(e) {
$.ajax({
url : '/copyFile.php',
data : {
fileName : $('#mySelectMenu').val(),
token : someTokenYourPHPInjectedIntoYourJS
},
type : 'POST',
success : function (data) {
// yay
}
});
});
You should check PHP Documentation at: http://mx2.php.net/manual/en/function.copy.php
There's an exaple to copy a file.
<?php
$file = 'example.txt';
$newfile = 'example.txt.bak';
if (!copy($file, $newfile)) {
echo "failed to copy $file...\n";
}
?>
Remember this directories must exists and be visible to each other (inside the same web server)
Add an Ajax call on your user interface,
$.ajax({
url: 'copy.php',
success: function(data) {
if(data == 'true'){
alert('The file has been copied');
}
}
});
Create a second php file to handle the file copy on request
/* copy.php */
<?php
$result = copy('/dir1', '/dir2');
echo $result?'true':'false';
Of curse, this is over-simplified, you have to do some error-handling input-checking and security improvements, but I just wanted to illustrate the way to go.

Content on page disappears

I have a simple script of code that reads a PHP file and when it get's changed it's supposed to say CHANGED on the page which I will change to refresh the page or change the content. For now, it shows the content, the function repeats once or twice and then it just shows nothing. Any help?
Here is the code:
<?php
$handle = fopen("../chat/real/chatserver.php", "r");
$contents = fread($handle, filesize("../chat/real/chatserver.php"));
fclose($handle);
$newcontents = $contents;
echo $contents;
?>
<script type="text/javascript">
checkchanged();
function checkchanged() {
document.write("<?php $handle = fopen('../chat/real/chatserver.php', 'r');
$newcontents = fread($handle,filesize('../chat/real/chatserver.php'));fclose($handle);?>");
document.write("<?php if(!($contents==$newcontents)){echo 'Changed';} ?>");
setTimeout('checkchanged()',3000);
}
</script>
Link to example
Thanks for the help
This is because you can't include PHP in your JavaScript in order to execute it by the client. Yes, you can include PHP values, but that's it. Have a look at the source code in your browser:
<script type="text/javascript">
checkchanged();
function checkchanged() {
document.write("");
document.write("");
setTimeout('checkchanged()',3000);
}
</script>
As you can see, the function document.write gets called with an empty string "". This is because everything that is in <?php ?> gets executed on the server, not on the client, before the resulting page gets sent to the client.
Since every PHP code is parsed only once $contents==$newcontents will be true, so you'll never see Changed.
To achieve something like a chat server you'll need new http request. Have a look at AJAX.

Where to place the unlink code to delete a file from the server

I have a javascript function below where it removes an appended file name from .listImage when the user clicks on the "Delete" button:
function stopImageUpload(success, imagefilename){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').eq(window.lastUploadImageIndex).append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage">Delete</button><br/><hr/></div>');
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
$(".deletefileimage").on("click", function(event) {
$(this).parent().remove();
});
return true;
}
As you can see the $(".deletefileimage").on("click", function(event) { is used to delete the correct appended file name.
But what I want to do is that when the user deletes a file name, it also deletes the file from the server. So I am trying to use this code: unlink($_FILES["fileImage"]["temp_name"]); to delete the file from the server.
But what I want to know is that where do I store this code so that it uses the javascript function to delete the appended file name but then be able to go onto the php script to delete the file from the server?
BELOW IS the php script (imageupload.php) where the uploading of files occur:
<?php
session_start();
$result = 0;
if( file_exists("ImageFiles/".$_FILES['fileImage']['name'])) {
$parts = explode(".",$_FILES['fileImage']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;
while( file_exists("ImageFiles2/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileImage']['name'] = $base."_".$n.".".$ext;
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles2/" . $_FILES["fileImage"]["name"]);
$result = 1;
}
else
{
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles2/" . $_FILES["fileImage"]["name"]);
$result = 1;
}
?>
<script language="javascript" type="text/javascript">window.top.stopImageUpload(<?php echo $result ? 'true' : 'false'; ?>, '<?php echo $_FILES['fileImage']['name'] ?>');</script>
You will need to use an ajax call to your php script to allow deletion of files on the server. JQuery's ajax documentation can be found here.
First, you will need to connect your button and image file name like so
$('.listImage').eq(window.lastUploadImageIndex).append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" image_file_name="' + imagefilename + '">Delete</button><br/><hr/></div>');
Now, your delete method will then look something like this.
$(".deletefileimage").on("click", function(event) {
// Find the image file name that is associated with this delete button. You
// may want to think about linking the image file name and the delete button
// in a better way than this.
var image_file_name = $(this).attr('image_file_name');
$(this).parent().remove();
console.log("Deleting " + image_file_name);
jQuery.ajax("delete.php?imagefilename=" + image_file_name)
.done(function(data) {
$(".msg").append(data);
});
});
Finally, the delete.php will need to look something like this
<?php
$image_file_name = "ImageFiles/" . $_GET["imagefilename"];
if (User Uploaded this File || Has Permission to Delete it)
{
print "Deleting $image_file_name";
// This assumes delete.php is in the same directory as the image file.
unlink($image_file_name);
}
?>
Here is a JSFiddle to show you working code.
Good idea to store your uploaded files in public temp directory and move then only when content saved.
Another way to have list of all all the time uploaded files with marker "active/inactive" and periodicly run script that deletes old files (inactive and created hours or days ago). In this case when you adding files or deleting content you mark it as "inactive", and when you save content you mark used files as "active".

Categories