Garbage output while downloading apk from server using PHP - javascript

I'm using PHP to compile an app on an apache server based on the input provided by the user and then provide the app to them using the readfile() method.
The problem that I'm facing is that instead of actually downloading the app, the .apk file is being opened as a text file.
I have added the android app mime type in the PHP code.
My php code is :
<?php
echo "Please wait while the app is being generated, it can take around 10 minutes for the build to finish.The completed app will be mailed to you ";
if(isset($_POST['timestamp']))
{
$uid = $_POST['timestamp'];
exec("sudo python /var/www/html/appgenserver.py $uid");
header("Content-Description: File Transfer");
header("Content-Type: application/vnd.android.package-archive");
header("Content-Transfer-Encoding: Binary"); //Adding or removing this hass no effect
header('Content-Disposition: attachment; filename="Foo.apk"');
ob_clean();
flush();
readfile("/var/www/html/".$uid."/releaseapk.apk");
exit();
}
?>
Any help would be appreciated.

I think you can solve it by removing the echo. Don't output to the page before the headers have been sent.

The garbled output caused by the buffer is not clean, search for the output on the page before headers or Try using ob_end_clean() instead of ob_clean() and put it before your header()

So what I did was, rather than return the app from PHP script, I returned it URL to the AJAX call.
From there I navigated to that URL and the download initiated automatically.
PHP code :
<?php
{
echo "http://server_ip/release/".$uid."/releaseapk.apk";
}
?>
Ajax cal :
$.ajax({
type: "POST",
url: "/test.php",
data: { timestamp : timestamp },
success: function(response){
console.log("Success",response);
window.location = response;
}
});

Related

Writing to JSON file using ajax and php. Server not recieving POST

I tried following the steps in a few other stackoverflow questions, but for some reason my server is not showing any indicator of recieving a request. I know that the client is sending the request since it shows up in firefox debugger.
Here is the js method:
function writeToFile(dat) {
$.ajax({
url : 'dataSaveAjax.php',
method : 'post',
data : { 'data': JSON.stringify(dat) },
success : function( response ) {
alert( response);
}
});
}
PHP code:
<?php
$fp = fopen('general.json', 'w');
fwrite($fp, json_encode($_POST['data']));
fclose($fp);
?>
Try updating your code like that
<?php
$fp = fopen('general.json', 'w');
$writtingResponse = fwrite($fp, $_POST['data']);
fclose($fp);
echo $writtingResponse;
?>
You did not write any response and you encode json twice.
first you need to understand what is the reason and why our script does not work. First, let's look at the server part (php). First, put the data in a variable, instead of $ _POST ['data'] try to do something like:
<?php
$fp = fopen('general.json', 'w');
fwrite($fp, 'MyTest');
fclose($fp);
?>
If this does not work, most likely the reason is that you need to set the write permissions for the file (Chmod).
If everything is recorded correctly, then something is wrong with the client part of your site. When it comes to POST / GET queries, I usually use Postman. It allows not only to test requests, but also to generate code. If you run a query through Postman and the result is written to a file, then the error is unambiguous in javascript. Try to press F12 in the browser and go to the js console, there you will see an error message. Do you use jQuery in the example, and is it connected? Is it connected before you try to execute the script?
Try to look at the data that you are trying to send using console (F12)
console.log(JSON.stringify(dat));
Are your data really going to be collected, or are you trying to send empty data to the file?

Download file with ajax and php - readfile not working

I want to save a value to a txt-file and download it to the user.
Right now, the value is being printed into the txt-file correctly, but the readfile function is not triggered, thus no downloading begins.
The php, this code is located on the same page as the ajax call.
<?php
if (isset($_POST['data']))
{
$handle = fopen("file.txt", "w");
fwrite($handle, $_POST['data']);
fclose($handle);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
exit;
}
?>
The javascript, there is no url because the data is to be sent to the current page.
function exportColors() {
var exportData = this.dataset.id;
$.ajax({
type: "POST",
data: {data: exportData},
success: function (data) {
console.log(data);
}
});
}
You need to separate the functionality, that is, post the data to PHP first, save the content of the text file and then, in a second request, let the user download the file. So one (skeleton) approach would be:
JS File:
function exportColors() {
var exportData = this.dataset.id;
$.ajax({
type: "POST",
data: {data: exportData},
success: function (data) {
// redirect or print out a link
}
});
}
PHP File for the first request (saving the content):
<?php
if (isset($_POST['data'])) {
$handle = fopen("file.txt", "w");
fwrite($handle, $_POST['data']);
fclose($handle);
// give back some unique id or the unique filepath
}
?>
PHP File for the second request (be it through clicking on a link or after having been redirected):
// essentially everything that outputs your file
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
exit;
Comments:
Either give back a unique filepath or via a handle through a database (more secure, but more complex as well). Besides, why should the user download the unchanged data he has formerly submitted? Is there more to it than meets the eye?
Ok I'm going out on a limb so take this with a grain of salt.
You said this request is going to the current page? Does that mean you've excluded (for the sake of brevity) HTML content from the PHP file you're showing us? If you have ANY content above your opening <?php tag, then any call to header will fail with an error (because headers must come before the body of a request). This would cause the script to terminate and prevent the readfile line from ever being reached.
Are your headers being sent? Do you see anything in the error log? If the answers to these are yes and no respectively then I'm wrong and you can ignore this.
Due to security reasons, ajax won't be able to download/save the file to the client's system because of java-script constraints.
Instead you can use
jquery.fileDownload.js
Please have a look at http://jqueryfiledownload.apphb.com/
Hope this helps.
you can't
beacuse javascript is not able to write on user file system.
see answer
Download a file by jQuery.Ajax
explain problem very well
The following Ajax generates a new file on the server at runtime AND downloads it to the client machine's /downloads directory with a single click. It uses Javascript to download the file, not PHP readfile().
await $.ajax("generateFile.php", {
type: "POST",
data: {
param_1: param_1,
param_2: param_2
},
success: function(data){
var a = $("<a>")
.attr("href", "path/filename_on_server.txt")
.attr("download", "filename_on_client.txt")
.appendTo("body");
a[0].click();
a.remove();
},
error : function(data) {
alert("ajax error, json: " + data);
}
});

Getting data from database on pageload jquery php

can any one help me please
What Im trying to do is a phone app using HTML5, JQUERY, Json and PHP. I cannot use PHP pages in this as I will be packaging it with Phone Gap Cloud Compliler.
I have tried using many scripts and suggestions that I have researched on the internet but cannot seem to get this to work.
On the page I need to retrieve data from the database there are 6 text boxes or divs I wish to populate using a on page ajax request to a PHP processing page that gets the required data and forms it into a Json string, the following scripts will show where I am at presently.
PHP Page:- this works as far as getting the data from the database and from the research I have done succssefully parces it into a Json format
PHP Script **********************************************
<?php
include_once 'db_connect.php';
header("Content-Type: application/json"); //this will tell the browser to send a json object back to client not text/html (as default)
session_start();
$return_arr = array();
$sql = "SELECT * FROM `autumnTerm`"; //query
$result = mysqli_query($mysqli, $sql);
while($row = mysqli_fetch_array($result)) {
$row['term1start'] = date('d-m-y', strtotime($row['term1start']));
$row['term1finish'] = date('d-m-y', strtotime($row['term1finish']));
$row['term2start'] = date('d-m-y', strtotime($row['term2start']));
$row['term2finish'] = date('d-m-y', strtotime($row['term2finish']));
$row_array['term1start'] = $row['term1start'];
$row_array['term1finish'] = $row['term1finish'];
$row_array['term2start'] = $row['term2start'];
$row_array['term2finish'] = $row['term2finish'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
?>
this returns the following json :-
[{"term1start":"01-04-15","term1finish":"02-04-15","term2start":"03-04-15","term2finish":"04-04-15"}]
which I believe to be the right format.
The Jquery:-
<script>
I think I am right in believing that document ready should run the jquery script on page load
$(document).ready(function() {
the processing page address which is associated to a variable
var url = "http://www.newberylodge.co.uk/webapp/includes/retrieveAutumn.inc.php";
The ajax request defining the request elements
$.ajax({
type: "POST",
cache: false,
url: url,
dataType: "json",
success: function(data) {
$('#termoneError').text('The page has been successfully loaded');
},
error: function() {
$('#termoneError').text('An error occurred');
}
});//ajax request
});//ready function
</script>
If anyone would be so kind as to helping me figure this out I would be most greatful, I have been trying to resolve this for over a week now
I havent posted the html trying not to swamp the question with code, but if its needed I will put it up on request
try this:
$.ajax({
type: "GET",
cache: false,
url: url,
dataType: "json",
success: function() {
console.log()
$('#termoneError').text('The page has been successfully loaded');
},
error: function() {
$('#termoneError').text('An error occurred');
}
});//ajax request
});//ready function
</script>
and try to see the console is there any error?
you should try for the error Cross-Origin Request Blocked to put proper header
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET,POST,OPTIONS');
header('Access-Control-Allow-Credentials: true');
the rest code its ok

Downloading a file with a different name to the stored name with ajax

I follow what it's write here Downloading a file with a different name to the stored name .
But i'm not sur too understand everything because it's don't work when i try do it with ajax. I signal that i use Smarty.
This is my html code :
// In $attache.id their is the id of the data i want to dowload in the database
<a href='javascript:uploadAttachFile({- $attache.id -});'><img src='../tools/telecharger.gif' /></a>
This is my jQuery code :
function uploadAttachFile(idAttache)
{
$.ajax({
//This permit me to go to the php function
url: ajaxURL("attacheUpload"),
type: "POST",
data: {
idAttache: idAttache
},
success: function(data)
{
alert(data);
}
})
}
This is my php code :
//Permit to have the path and new title of the file
$attacheEntite = Model_AttacheDB::getNameAndPathAttachFile(request('idAttache'));
$file = 'path' . $attacheEntite['path'];
if (file_exists($file))
{
header('Content-disposition: application/force-download; filename="' .$attacheEntite['titre']. '"');
header("Content-Type: application/pdf");
header('Content-Transfer-Encoding: binary');
header("Content-Length: " . filesize($file));
header("Pragma: ");
header("Expires: 0");
// upload the file to the user and quit
ob_clean();
flush();
readfile($file);
exit;
}
I know that it pass by my php code because the ajax reuest pass by succes and alert an incomprehensible code who is certainly the code of the pdf file when i read it.
You can't make the client download the file through an ajax request.
What you are doing here is reading the file server-side with PHP and returning his content to the caller script ( in fact you see the content in the "data" variable )
Without ajax, you can call the script like this:
<a href='path/to/your/phpscript.php' target='_blank' ><img src='../tools/telecharger.gif' /></a>
And it will send the file to the browser
EDIT: if you add the attribute target="_blank" to the anchor it will open the download in a new tab, without reloading the current page

Why does the following php file does not work?

The following is the log.php file that is running on google app engine locally (on localhost).
<?php
if (isset($_POST['name'])) {
$name = $_POST['name'];
$filename = "log.txt";
file_put_contents($filename, $name, FILE_APPEND | LOCK_EX);
}
?>
I am calling the above file using the following jquery call:
$.ajax({
url: './php/log.php',
type: 'POST',
data: {name: name},
success: function (data) {
console.log(data);
}
});
I believe the ajax is working as I get a log on console which is just the entire php code. But the php is not writing anything into the log.txt file. Can anyone please help?
As you get in the AJAX response the entire PHP code then you most probably don't have the App Engine or PHP configured properly.
Since you get the PHP code as plain text, then the server isn't configured to run it as code and does not recognize it as such.
Check that.

Categories