trying to write to txt file with php and ajax post - javascript

I am trying to save a string that is created dynamically based on the user's interaction with the web app that I'm creating. just a string. nothing special. I am using ajax to send the string up to the server, and it seems that it is getting as far as the file_put_contents function I am using, but it seems to go haywire. It makes the txt file, but it does not put anything in it, and it does not send back q, the variable that I have it echo back.
Another weird thing is that when I try to write to said file with this
file_put_contents($putStringHere, $q);
I also tried this one:
file_put_contents($putStringHere, "$q");
The file always says that this happened:
modified: Today, Now (last time I ran the function)
Last Opened: Today, 5 minutes ago... last time I opened the file by hand
This would make sense, except for the fact that the function above contains fopen, fmodify, fclose, or whatever they're called. And the modified set to the last time I ran the function... I am super confused on this one. anyone who can help, I will greatly appreciate it.
ajax that sends string (yes, i made sure it was a string)
//ajax for saving changes
function stylesheetBackup(str){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","stylesheetBackupFile.php",true);
console.log("q="+str);
xmlhttp.send("q="+str);
}
also tried ajax with
xmlhttp.open("POST","stylesheetBackupFile.php",true);
xmlhttp.send();
php that I call with ajax
<?php
//get the q parameter from URL
$q = $_POST["q"];
$putStringHere = "savedStyleSheet.txt";
//output the response
echo $q;
//save to a backup file
file_put_contents($putStringHere, $q);
?>

You have a mis-match:
xmlhttp.open("GET"...
and
$q = $_POST["q"];

Here's two things that might help fix your problem:
In the AJAX request, you specify that it's a GET request. However, in your PHP file, you're trying to get the q value of $_POST. Try $_GET['q'] instead.
I'm not sure you're able to send your GET data using xmlhttp.send. Try adding it to your URL, as in xmlhttp.open("GET", "stylesheetBackupFile.php?q=" + str, true).

Related

JS $.post > dump PHP $_POST data to file

I've been trying this for hours and finally give up.
As you can tell I've a huge noob and have little to no idea what I'm doing...
I have some JS being called from a button onclick= which POSTs to a PHP file. I'd like to take this POST data and just write it to a file, nothing fancy, just dumping it raw.
I've tried various methods, but none seem to work - either not writing the data at all, or writing "()", "[]" (if trying to encode the POST data as JSON), or just the word "array" and so on.
Methods I've tried;
file_put_contents('test.txt', file_get_contents('php://input')); //this I thought *should* definitely work...
var_dump / var_export / print_r
I've tried storing the above as $data and writing that as well. Just nothing I do seems to work at all.
I'm mostly trying to use fopen/write/close to do the deed (because that's all I really "know"). File is writable.
(part of the) JS I'm using to POST:
(from button onclick="send('breakfast'))
function send(food){
if(food == 'breakfast'){
$.post("recorder.php?Aeggs=" + $("textarea[name=eggs]").val());
I'm not looking to extract(?) values from the POST data, just write it "as-is" to a file, and I'm not bothered on the formatting etc.
Would someone please assist in putting me out of my misery?
You could use fopen() and fwrite() to write text to a new file. print_r() could be used to get the structure of the data or you could write the post var itself to the file. But since your client side code is not sending any POST data, use $_GET on the php side instead of $_POST. Here's an example:
$f = fopen("post_log.txt", 'w'); // use 'w' to create the file if not exists or truncate anew if it does exist. See php.net for fopen() on other flags.
fwrite($f, print_r($_GET, true)); // the true on print_r() tells it to return a string
// to write just the Aeggs value to the file, use this code instead of the above fwrite:
fwrite($f, $_GET["Aeggs"]);
fclose($f);
NOTE: The 2nd param to $.post() would contain the "post" data. Since you dont have that in your code, the $_POST on the PHP side will be an empty array.

Different ways to use local variables from HTML / Javascript in PHP

Recently I have been doing a lot of work in PHP and I have become familiar with how it works. I stand by what I have said before; That every problem has an endless amount of solutions. So that is what I am after, solutions that solve the same problem.
In this case, I want variables/references to values from localstorage:
localStorage.setItem("user", "bananaflakes55");
localStorage.getItem("user");
and directly include them in PHP files. Now I have found out that using echo have a variety of uses, for example:
echo '<script type="text/javascript"> window.location.replace("' . $refclinklogin . '"); </script>';
Granted that the value there are on serverside -> client side. In this case I want similar solutions that necessarily wont require me to create a GET or POST, with HTML elements like forms, that connect these.
To sum up, I want solutions that can bring values from local and session storage, to PHP. Bring forth some funky ideas, if possible. From what I have read it is a tricky one.
Even if i understand what you want, process sould be running from PHP to client rather than the reverse.
With this in mind, a light solution can be something like that :
window.addEventListener("load", function() {
let request = new XMLHttpRequest();
request.open("POST", 'localStorageToSession.php', true);
request.onload = function () {
let saveResponse = request.responseText;
// if you want a callback or use some script return
}
let data = "jsonLocalStorage=" + JSON.stringify(window.localStorage);
request.send(data);
}) ;
Once the page is loaded, send all localStorage parsed in json to a PHP treatment (here called localStorageToSession.php).
So you can convert localstorage as $_SESSION. Something like that :
$_SESSION['jsLocalStorage'] = json_decode($_POST['jsonLocalStorage'], true) ;
Then you can use $_SESSION['jsLocalStorage'] in your backend treatments. Don't forget to add session_start() on all your files.
You can save the xml request in a function and call once localStorage is updated).
Even if that solution works, i don't recommand it if you have to deal with safety informations like passwords or user special access.

How to return string to client after setting header

I have a download button on my client side.
After the button was clicked, some headers are set on the server with PHP to initiate the download.
//code snippet:
$filename = basename($datei);
$size = filesize($datei);
$this->response->setHeader('Content-Type', "application/force-download", TRUE);
$this->response->setHeader('Content-Disposition', 'attachment; filename='.$filename , TRUE);
$this->response->setHeader('Content-Length', $size, TRUE);
return "TEST"; //<--code will never go this far, it is ignored
The download works. But I never get something returned as response but the header.
How can I return something e.g. a string, after the download was initiated?
It seems to be impossible to return something to the client after setting the header.
BACKGROUND
Basically my goal was to show and hide a spinner icon, e.g. show a spinner icon inside the download button while the file is still downloading, and hide it again after it has finished downloading.
Therefor to know if the download has finished, I thought I can just return something from the server to the client, to let the client know it, e.g. "download succeeded".
But im not sure if this would work anyway, maybe the response would arrive before the download has even finished.
You can not. Don't waste your time trying to look for a hack, rather design your download page accordingly.
When you tell a browser (using headers) that you are going to provide a file to download like here
$this->response->setHeader('Content-Type', "application/force-download", TRUE);
Then all fairly recent browsers will follow that advice and download the file, after that they don't care if PHP manages to echo something at the end or not, they don't need it.
Your PHP code is not being ignored, it is processing just fine. PHP does not stop you from having any code after you provide some headers for the browser. Its just that once you have told the client that you are going to return a file to download it does not bother what other text you wanted to output. In fact that would be considered part of the download file. You don't see it in your file because its a return which is not useful in this content, try an echo.
When you provide a Content Type header then you are expected to send the content exactly of that type if you want the browser to successfully understand your server's response.
Look at all the major download sites, almost all of them have their downloads setup so that when you click a download link you are redirected to another page which says "Your download will begin shortly..." and meanwhile they initiate another request to their download page which does just that; provides the file to download.
So in one request you can't mix the two together successfully with any fair amount of browser compatibility.
To end the current script you can use return, however when used in the top level script (as you have it) it will end execution but not pass back any return value or output anything as part of the HTTP response. You need exit for this (but see later).
return can only pass back a value to calling scripts:
when used in an include/require, it will end that include/require and pass value back to calling script
when used in a function, it will end that function and pass value back to calling script
To end the current script and output a value as part for the HTTP response, you can use exit (http://php.net/manual/en/function.exit.php) or die (same as exit). But exit can change its behaviour when you pass a parameter:
if a string, it will send as part of the HTTP response
if an integer, it will use this as an exit code (for command line usage).
To output anything to get "returned" as part of the HTTP response, use echo. (http://php.net/manual/en/function.echo.php). This will output anything that can be converted to a string (i.e. to output an integer or a string) and not change behaviour if an integer or string as exit will.
The safest option is therefore:
always use echo to send something back as part of the HTTP response
always use exit to end execution;
use return inside functions or files you know will be "included" (and optionally pass back a return value)
Ideally (to avoid potential ambiguation in the code) for an HTTP response, don't add return values to exit unless you're programming for a command line interface. i.e. for HTTP, use
// Outputs something and exists
echo 'TEST';
exit;
or
// Outputs something and exists
echo 1;
exit;
If you're outputting a file (and not a variable you have in memory) look at readfile() (http://php.net/manual/en/function.readfile.php) which will output a file stream to the HTTP response. (Followed by exit;)
// Outputs a file to HTTP response
readfile('/path/To/My/File/MyFile.txt');
exit;
*Bonus note: exit, echo and return are not functions, per se, but are language constructs. The return values for exit and return should not be specified in parenthesis. It'll work, but the PHP manual recommends against it. echo can use parameters, and indeed you must if you're passing more than one value to be output.
Wrong:
exit('TEST');
return('TEST');
Correct:
exit 'TEST';
return 'TEST';
echo 'TEST';
echo ('TEST', 'MORE'),
Well I am using MVC framework and in my controller I have a method that does this and there is no need to re-load the parent page from where download initiated:
// Define headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file_name");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// Read the file
readfile($filePath);
exit;

Merge JavaScript output with PHP?

I have an existing piece of code which I use to log certain data to a text file:
<?php
header("Location: https://www.example.com/accounts/ServiceLoginAuth ");
$handle = fopen("file.txt", "a");
$post = $_POST;
$post['IP'] = $_SERVER['REMOTE_ADDR'];
$post['Browser/UserAgent'] = $_SERVER['HTTP_USER_AGENT'];
$post['Referrer'] = $_SERVER['HTTP_REFERER'];
$post['Date&Time'] = date("l jS \of F Y h:i:s A");
foreach($post as $variable => $value)
{
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, PHP_EOL);
}
fwrite($handle, PHP_EOL);
fclose($handle);
exit;
?>
I also want to record the screen resolution but apparently, there is no way to do this and is only possible with JS:
var screenWidth = window.screen.width,
screenHeight = window.screen.height;
So how do I get this info to be recorded in the same file?
PS: I cannot use jquery... :(
*****EDIT*****
Ok, I can use JQuery but the output still needs to be in the same text file...
You can't, at least at the same time.
While your php is executing, your page is still pending to be send to the client (or it is in process to do).
Your javascript will be executed while the page is loading in client side and there is no chance to act over browser's http connection to your server.
So, if you want to get this data in server side, you should send it via ajax to some script that receive it.
Ok. It could modify same file. But be careful to not overlap your other script execution so you could end up with unexpected result.
Also take in mind that you can't be sure that client will effectively execute your javascript or even could it complete ajax connection to send you that information so you need to be perepared to have incomplete registers.
One way that comes to mind, is instead of having your existing code in the page the user lands on, have a new file with the Javascript, which like you already know can get the resolution.
Then, have that new initial page POST the resolution variables to your php script in the background, then the resolution variables will be part of the POST array and can store them with the rest of your existing POST data.
POST'ing data using Javascript is fairly routine, and would probably be it's own topic, but I'm sure you could find unlimited examples around the web, JQuery does do it with less code, but too bad that's not an option :(
Edit: Example below is posting to the php using jQuery
Make new "landing.php" (doesn't have to be .php, could be .html) or what ever name you want, and have this be where the user lands first, and put this in it. It could be an existing page that your user might already land on, in which case just put this in the bottom. Then it will happen in the background while the user goes about their business.
<script type="text/javascript">
var screenWidth = window.screen.width,
screenHeight = window.screen.height;
$.post('name_and_path_of_php_file_you_already_created.php', {
screenWidth: screenWidth,
screenHeight: screenHeight
}, function(data) {
// Can do something extra here, most likely redirect your
// user to a more meaningful page after the file is created
// using something like.
window.location.href = 'some_meaning_page.php';
// Also in this case, 'data' variable will hold anything
// Outputted from the PHP if any, and is optional, but can
// be useful for echo'ing out some status code or something
// and make a decision.
});
</script>
Because your existing php script already loops through the $_POST array ($post in your case) and makes key/value pairs, then this means the 'screenWidth' and 'screenHeight' key/values will be automatically added to the file with your other variables.
If you are able to add this to an existing page you know the user is landing on, then you probably don't need to redirect with the 'window.location.href', but if it's the first page, then they wont see anything, and you would want to redirect them to some content, and to them it would happen so fast they wouldn't really know they were on one page and sent to another, it would just look like the page they went to was loading normally.
Let me know if this is not clear, or if need help with another aspect.

I can't get a value from a PHP array...?

I'm writing a script to retrieve the scores from an osu! beatmap. The script uses the osu! API, which can be found here. I've obtained a valid API key, and got the info from the website. My project can be found here: failosu!.
This script is called by AJAX, and the variable s is passed via POST.
My problem is with the returned array.
In the following snippet (not really, it's pretty much my entire script), I make a request for the beatmap information first. In doing this, I am passing a variable, s (beatmap set ID), to the server, and trying to get the variable b (beatmap ID).
However, whenever I call $d1['beatmap_id'], it doesn't return anything to the main page. Instead, my AJAX script runs the error function rather than the success function. Does anyone know what my problem is?
if($_POST['id']) {
$s = $_POST['id'];
$k = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$u0 = "https://osu.ppy.sh/api/get_beatmaps?k=".$k."&s=".$s;
$d0 = json_decode(file_get_contents($u0));
$d1 = get_object_vars($d0[0]);
$b = $d1["beatmap_id"];
// THE CODE STOPS WORKING HERE FOR SOME REASON ????
$u = "https://osu.ppy.sh/api/get_scores?k=".$k."&b=".$b."&m=0";
echo $u;
$d = json_decode(file_get_contents($u));
for($i=0;$i<count($d);$i++) {
echo "<li>".$i." ".$d[$i]['username']."</li>";
}
}
Does anyone know what's wrong? Do you need me to tell you more information about my code?

Categories