Information
For testing purposes I am building a system where a javascript file contains an array called "contains".
The javascript will then make the browser redirect to another page where the php-code is located, and that code should add the keyword as a new array-element
And before anyone of you try to say how simple this is, let me reiterate that I am injecting the JS code on another page using Tampermonkey, and I have no chance to modify their code
The code should then be converted to JS again and be written to a file which is called "copyright.js"
Code
At the moment the "copyright.js" file looks like this
var contains = ["original"]
The following code returns a positive result
$str = 'var contains = ["original"]';
$str = str_replace("var ", '$', $str);
eval($str.";");
But when I try to fetch the variable from the file i get an error
$file = fopen('copyright.js', 'r') or die('Unable to open File');
$str = fread($file, filesize('copyright.js'));
fclose($file);
$str = str_replace("var ", '$', $str);
eval($str.";");
If there is a better solution to this, please don't hesitate to tell me :)
Related
I've this code that works fine to get the user Timezone and echo in php. There's also an alert message before.
<script type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js">
</script> <script> var timezone =
Intl.DateTimeFormat().resolvedOptions().timeZone; alert(timezone);
</script>
<?php
$time= "<script>document.writeln(timezone);</script>";
echo $time;
I want to store this echo in the file time.txt
I've tried with this:
$file_name = 'time.txt';
//opens the file.txt file or implicitly creates the file
$myfile = fopen($file_name, 'w') or die('Cannot open file: '.$file_name);
// write name to the file
fwrite($myfile, $time);
// close the file
fclose($myfile);
but it doens't work .
Any solutions?
It seems like what you want is for PHP to write the file with the result of the timezone variable, i.e. that it would be a text file with the name of a timezone in it.
Probably what you are seeing is PHP writing that JavaScript line instead, i.e. <script>document.writeln(timezone);</script>
Right?
What's happening is PHP executes completely before JavaScript is run. Your first example is working because PHP executes, including the writing of a line of JavaScript, and then JavaScript executes, including that line, and you see the result.
What you are trying to do in the second example isn't possible. PHP is executing, including the writing of that line of JavaScript (to the file), and then JavaScript executes, but of course not in that text file.
Your two choices are to find a different way to get the timezone strictly in PHP, or else to get it with JavaScript and then use AJAX to trigger a later run of PHP, i.e. after JavaScript has run.
EDIT
Your JavaScript will fetch the timezone as before. Then it will send that to a separate file that outputs it:
var url = '..'; // url of a php file that JUST processes the file write
$.ajax({
type: "POST",
url: url,
data: {
'timezoneToPrint' : timezone
}
});
And in your other PHP file, which you have just called, you can now print it to a file
if($_POST['timezoneToPrint']){
// ..write the file here, the timezone is in $_POST['timezoneToPrint']
}
I'm trying to pass a variable ( n ) from a JS script to PHP thru the URL and get it to write said variable to a file. Unfortunately I can see the PHP script being called over the network, with the appropriate URL and with 200 status, but it doesn't seem to be executing. The file it should be writing to never changes. The disk is not full, the file is not in use by another process and the file it is writing to has completely open permissions as a testing measure. Hopefully this is a simple fix, thanks in advance.
<?php
$my_file='count.txt';
$count= $_GET['n'];
$handle = fopen($my_file, 'w');
fwrite($handle, $count);
fclose($handle);
?>
Examples of requests being sent
Your code is working fine and its writing whatever value for n is passed. however it keeps on overwriting previous value for every new request.
$handle = fopen($my_file, 'w');
In 'w' mode it create new file for read and write while placing pointer at the beginning.
Use 'w+' mode this places the pointer at the end of file.
$handle = fopen($my_file, 'w+');
For more details on files you can check below url for different modes and other functions
http://php.net/manual/en/function.fopen.php
I'm making a PHP script for a JavaScipt site I've made.
The goal is to save the contents of a string as an HTML file when I click a button.
I'm using jQuery to make a Post request.
I'm using an Ubuntu OS with an Apache 2 server. The folder I'm writing to has permissions 777 (for testing only, will repeal this).
A requirement is the PHP must live in another file.
The issue is whenever I make the request, the file saves blank.
A requirement is each filename must be a timestamp. The file has the correct file name, but not contents.
So far, here is my code:
<?php
$fileName = $_GET['fileNameData'];
$htmlImport = $_GET['htmlToSaveData'];
$htmlToSave = (string)$htmlImport;
$myFile = fopen($fileName, "w") or die('You do not have write permissions');
//fwrite($myFile, $htmlToSave);
file_put_contents($myFile, $htmlToSave);
fclose($myFile);
?>
I've tried the frwite function that I've commented out, same effect.
I have tested this in terminal by passing in arguments ($argv[1] and $argv[2]). That works fine.
The JS I've made to run my site looks like:
var newURL = 'saveHTML.php/?fileNameData=' + fileName + '&htmlToSaveData=' + htmlToSave
$.post(newURL)
.done(function(){
alert('Your file saved as ...' + htmlToSave)
})
I've also tried this code, with the same result:
$.post('saveHTML.php/', {
fileNameData : fileName,
htmlToSaveData : htmlToSave
})
Both the fileName and htmlToSave are strings, although htmlToSave is rather long and is actually html text that I've converted to a string.
Does anyone have ideas about what's going on here? I'm not a PHP developer at all.
I'm using a callback so I can be sure I've collected all my html before I pass the string to PHP.
I've read and tested the recommendations on this question here and this has been fruitless.
EDIT Don't be alarmed about the code, I realise it's a security issue but this is a learning project and this will not be in production.
I can see right off the bat that you have
$myFile = fopen($fileName, "w") or die('You do not have write permissions');
//fwrite($myFile, $htmlToSave);
file_put_contents($myFile, $htmlToSave);
fclose($myFile);
file_put_contents takes a file name, not a handle. So you would only need
file_put_contents($fileName, $htmlToSave);
Edit: I also feel like I should point out that you should not allow your users to name your files. They could potentially do some nasty stuff to your machine.
I have a page that has a JavaScript function that uses Post to send a variable to a php file. The problem is, that I am using "header" to download the file and my JS does not open the PHP script in a new page.
When I open the php file in a new page, it does not receive the needed variable from the JS.
I know it sounds confusing, but I hope my code can shed some light on my problem.
The short version is, I am trying to download a file that is selected by a radiobutton. I use JS to check which radiobutton is checked and then send that to my php file. Which then needs to download the file.
Thank you all in advance.
PHP:
<?php
if (isset($_POST['routenumber'])) {
if(!isset($_SESSION)){session_start();}
$routenumber = (isset($_POST['routenumber']) ? $_POST['routenumber'] : null);
$directory = ("Users/".$_SESSION['id']."/SavedRoutes/");
$routes = scandir($directory);
sort($routes);
$route = $routes[$routenumber];
$file =("Users/".$_SESSION['id']."/SavedRoutes/".$route);
header("Content-type: application/gpx+xml");
// header("Content-Disposition: attachment;Filename=".json_encode($route).".gpx");
header("Content-Disposition: attachment;Filename=route.gpx");
readfile($file);
}
?>
JS:
function fuAccountDownloadRoute(){
var i=2;
var SelectedRadio
while (i < routecounter){
var str1='radio';
var str2=JSON.stringify(i);
var result = str1.concat(str2);
if (document.getElementById(result).checked){
SelectedRadio = result.slice(5);
}
i=i+1;
}
$.post('accountPage.php',{routenumber:SelectedRadio});
}
When you open the url: http://localhost/accountPage.php in your browser it makes a GET request. You should change all the $_POST to $_GET in your code if you want to make it possible, and then you can open it like this: http://localhost/accountPage.php?routenumber=3, though it's probably not what you really want.
The below code checks for a directory 'dat'; if it ins't there, it creates one. That part works just fine; what I need is for it to write a file to said directory where AJAX can read it from.
Here's the php...
//checks for 'dat' directory; if false, creates it, if true, does nothing.
$dir = 'c:\wamp\www\dat';
if(file_exists($dir)){
return;
}
else{
mkdir ('C:\wamp\www\dat',0700);
}
//writes chats to file
$data = fopen($dir. "/chatlog". date('d'). '.txt', 'a+');
fwrite($data, $speak);
fclose($data);
}
And here's the AJAX; I don't need as much help here as I do above, but I won't complain if you provide the help for the AJAX below, mainly in getting it to read from the file within the 'dat' directory...
xhr.open("GET","chatlog<?php /*stamps the chatlog file with date (numerical day only)*/ echo date("d");?>.txt",true);
Your PHP script is running inside www, then, your file you be created there.
If you want to create the file inside the directory www/dat, just change this line
$file = "chatlog". date('d'). ".txt";
for this one
$file = 'dat\chatlog'. date('d'). '.txt';