Edit and save a file on server (PHP) - javascript

I have a page that displays the content of a C++ file into a textarea and I need to be able to save the contents of it using a script. (The C++ file does not have to be configured just saved.)
I'm using a PHP script to load the code from a file to display it on the textarea. How can I send back the contents to the script and save it to the same file or to a file with a new name?
PHP, HTML file:
<?php
$file = '/var/www/cgi-bin/cpp_get3.cpp';
$content = file_get_contents($file);
?>
<input type="text" id="filename" value="cpp_get3.cpp"><br>
<textarea id="cpp_content" rows="15">
<?php
echo($content);
?>
</textarea><br/>
<button id="save"onclick="savefile();">save</button>
Script:
function savefiles() {
var contentArea = document.getElementsById('cpp_content');
var cpp_content = contentArea.value;
var request = new XMLHttpRequest();
request.open('POST', '/php/save_contents.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
console.log("Success");
var resp = this.response;
} else {
alert ("Target server reached, but it returned an error" );
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send(cpp_content);
}
PHP file:
<?php
$filename = '/var/www/html/cgi-bin/cpp_get3.cpp';
$cpp_content = $_POST['cpp_content'];
if(file_exists($filename)){
file_put_contents($filename, $cpp_content);
}
?>
I expect for the C++ file of a text file at this point to get save with the content in the textarea.

You don't deserve me ;)
<?php
$fn = 'example.cpp';
file_exists($fn) or touch($fn);
if (!empty($_POST)) {
var_dump($_POST);
$_POST['filename'] === $fn or $fn = $_POST['filename'];
file_exists($fn) or touch($fn);
file_put_contents($fn, $_POST['cpp_content']);
}
$file = file_get_contents($fn);
?>
<html>
<head></head>
<body>
<form action="hi.php" method="post">
<h1>ig #WookieeTyler</h1>
<input type="text" name="filename" value="<?=$fn?>">
<br>
<textarea name="cpp_content" rows="15">
<?= htmlspecialchars($file); ?>
</textarea>
<br/>
<button id="save" type="submit">save</button>
</form>
</body>
</html>

Another option would be to send the contents to a separated PHP file through an XMLHttpRequest. This way you don't have to reload the page when saving. Something like this:
var request = new XMLHttpRequest();
request.open('POST', '/my/url/save_contents.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
var resp = this.response;
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send('cpp_content=' + cpp_content);

Related

Why does file_put_contents not work in my online php script?

I am trying to use a .php file to edit a .txt file on my http web server. I can call the .php file and get it to run (and echo something random back) just fine, but when I use file_put_contents it doesn't work. I have tried setting file permissions to 777, 0775, etc but nothing happens. (although from what I have gathered, it seems that permissions are for local systems only). I know that there are some similar questions already here, but I cannot understand the answers to any of them.
testingPHP.js (trimmed):
function submitData() {
var data = prompt('Enter data');
sendToServer(data, 'test.txt');
}
function sendToServer(data, file) {//file is file to write into, not the php file
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
}
}
xmlhttp.open("GET", "editTXT.php?txtFile=file&data=data");
xmlhttp.send();
setTimeout(update, 500);
}
function update() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = xhttp.responseText;
console.log(response);
}
};
xhttp.open("GET", "readTxt.php?file=test.txt", true);
xhttp.send();
}
setInterval(update, 1000);
editTxt.php:
<?php
$txtFile = $_GET["txtFile"];
$data = $_GET["data"];
file_put_contents($txtFile, $data);
?>
readTxt.php:
<?php
$file = $_GET['file'];
$data = file_get_contents($file);
echo $data;
?>
I hope the following might help - I think the main problem is in the javascript funnily enough but I'll post here the changes I made to all files anyway. Incidentally - constant polling like this using Ajax could instead be done in a cleaner way using an EventSource connection and Server Sent Events.
If the textfile is to be overwritten completely when the script is invoked then this works fine ( in test anyway ) but if the data is intended to add to existing content you'd need to add FILE_APPEND as the final argument to file_put_contents
editTxt.php
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['txtFile'], $_GET['data'] ) ){
$file=__DIR__ . '/' . $_GET['txtFile'];
$data=$_GET['data'];
$bytes=file_put_contents( $file, $data );
if( !$bytes )exit('error');
}
?>
readTxt.php
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['file'] ) ){
$file=__DIR__ . '/' . $_GET['file'];
exit( file_get_contents( $file ) );
}
?>
And the HTML & Javascript
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
</head>
<body>
<script>
function submitData() {
var data = prompt('Enter data');
if( data ){/* only submit if there is data */
sendToServer(data, 'test.txt');
setInterval(update, 1000);
return true;
}
}
function sendToServer(data, file) {//file is file to write into, not the php file
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
}
}
/* the filename and the data need to be escaped in the string */
xmlhttp.open("GET", "editTXT.php?txtFile="+file+"&data="+data);
xmlhttp.send();
setTimeout(update, 500);
}
function update() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = xhttp.responseText;
console.log(response);
}
};
xhttp.open("GET", "readTxt.php?file=test.txt", true);
xhttp.send();
}
/* call the function that prompts for data input */
submitData();
</script>
</body>
</html>

How to read a large binary file using PHP and send few bytes each time through AJAX on clicking a button?

I'm trying to send some fixed length of data from a large binary file each time, when a user clicks a button.
I'm using PHP to read binary file and AJAX for receiving data. I tried the following way but same data is received every time when I click a button.
index.html
<html>
<body>
<button name="click" onclick="loadFile()">Click me!</button>
<div id="txt"></div>
<script>
function loadFile() {
console.log("ok here");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txt").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "load_file.php", true);
xmlhttp.send();
}
</script>
</body>
</html>
load_file.php
<?php
$filename = "binary.DAT";
$handle = fopen($filename, "rb");
if (!$handle)
die('file does not exist or cannot be opened');
$contents = substr(strtoupper(bin2hex(fread($handle, 200))),10*2,138*2);
$formatedContent = "<pre>" . implode(' ',str_split($contents, 2)) . "</pre>";
echo $formatedContent;
ob_flush();
flush();
fclose($handle);
?>
I'm expecting different data each time but each time I'm receiving same data. Any help on how to handle this case is highly appreciated.

Javascript and PHP in one file (form handling and XMLHTTPRequest)

I am confused about my homework requirements: we need to put JS, HTML and PHP code in the same file xxx.php.
There is a form in the HTML, and once I submit the form, I need to send a request (XMLHTTPRequest) to myPHP.php with the form inputs (using POST to transfer the form data PHP). The PHP file will retrieve the form inputs, reformat it to the syntax of the API and send it to the Google API to get JSON object.
I am a beginner of PHP and JS, and I don't know how to combine them in the same file and do the homework based on the requirements. Like, how to send the JSON object obtained in PHP to Javascript.
Here is framework of my code (myPHP.php):
<html>
<head>
<script type="text/javascript">
// show the result
function show() {
var xmlhttpreq = new XMLHttpRequest();
var keyword = document.getElementById("keyword").value;
var post_data = "keyword=" + keyword;
xmlhttpreq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonObj = JSON.parse(this.responseText);
createTable(jsonObj);
}
};
xmlhttpreq.open("POST", "myPHP.php", true);
xmlhttpreq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttpreq.send(post_data);
}
function createTable(object) {
var out = "xxx";
document.getElementById("display").innerHTML = out;
}
</script>
</head>
<body>
<div id="display"></div>
<form action="myPHP.php" name="myForm" method="POST">
<b>Keyword </b><input type="text" id="keyword" name="keyword">
<br>
<button type="submit" onclick="show()" name="search">Search</button>
</form>
<?php
if (isset($_POST["search"])) {
// extract the form data
$keyword = $_POST["keyword"];
// geocode the address
$location = urlencode($location);
// google map geocode api url
$url = "xxxxxxxx";
$res_json = file_get_contents($url);
echo $res_json;
}
?>
</body>
</html>
You can try something like this:
<?php
if (isset($_POST["search"])) {
// extract the form data
$keyword = $_POST["keyword"];
// geocode the address
$location = urlencode($location);
// google map geocode api url
$url = "xxxxxxxx";
echo file_get_contents($url);
} else {
echo '<html>
<head>
<script type="text/javascript">
// show the result
function show() {
var xmlhttpreq = new XMLHttpRequest();
var keyword = document.getElementById("keyword").value;
var post_data = "keyword=" + keyword;
xmlhttpreq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonObj = JSON.parse(this.responseText);
createTable(jsonObj);
}
};
xmlhttpreq.open("POST", "myPHP.php", true);
xmlhttpreq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttpreq.send(post_data);
}
function createTable(object) {
var out = "xxx";
document.getElementById("display").innerHTML = out;
}
</script>
</head>
<body>
<div id="display">
<?php echo $result; ?>
</div>
<form action="myPHP.php" name="myForm" method="POST">
<b>Keyword </b><input type="text" id="keyword" name="keyword">
<br>
<button type="submit" onclick="show()" name="search">Search</button>
</form>
</body>
</html>';
}
?>
You first have to test in myPHP.php if there is some data send. If so, the form already has been display and the browser is sending the form data back. If not, it is the first time the php-page is loaded and you can display the html and javascript.
So:
<?php
//test if there is data from the form
if( isset( $_POST['some-form-variable'] ) ){
// YES
// process data an display something
}
else{
// NO DATA
// display form and javascript
}

Random number php not working

I am trying to generate random number with New York Lottery's Take 5, it generates right, but then i wanted to write it to .txt file and then load it with ajax.
HTML:
<div class="col-lg-10" id="rolled"></div>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="POST">
<input type="submit" value="submit">
</form>
PHP:
function roll() {
$server_seed = "39b7d32fcb743c244c569a56d6de4dc27577d6277d6cf155bdcba6d05befcb34";
$lotto = "0422262831";
$round_id = "1";
$hash = hash("sha256",$server_seed."-".$lotto."-".$round_id);
$roll = hexdec(substr($hash,0,8)) % 15;
$fn = "ram.txt";
$file = fopen($fn, "w");
fwrite($file, $roll);
fclose($file);
echo "<script>paste_rolled();</script>";
}
if (isset($_POST["submit"])) {
roll();
}
JAVASCRIPT:
function paste_rolled() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("rolled").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ram.txt", true);
xhttp.send();
}
It doesn´t work, even doesn´t write number to .txt file and i don´t know why.
When i tried that lotery system in another file, it worked. Thank you for any help.

Trying to write JSON data to a txt file using Ajax and PHP

My project is to take input from the user and write it to the end of a text file in JSON format using ajax and php. Problem is that the php only writes the time and date to the end of the file and nothing else. I took the example from a previous post and modified it here for my purposes. Here's the html
movie.html:
<html lang="en">
<head>
<meta charset="utf-8"/>
<script src="movie.js" type="text/javascript"></script>
</head>
<body>
<h1>
<center>
<input id="box" type="textbox"name="box" value="Enter Movie:"/>
<input id="add" type="button" value="Submit" onClick="addStuff();" /></center>
</h1>
<div id="status" ></div>
<h2>MOVIE NAME:</h2>
<ul id="list" name="list">
</ul>
<div id="status"></div>
</body>
</html>
Here's the movie.js file which sends the data via Ajax:
function addStuff(){
var movie_name_entered = document.getElementById("box").value;
var movieList = document.getElementById("list");
var hr= new XMLHttpRequest();
var url= "movie.php";
hr.open("POST",url,true);
hr.setRequestHeader("Context-type","application/x-www-form-urlencoded");
var param = "film=" + movie_name_entered;
hr.setRequestHeader("Content-length", param.length);
hr.setRequestHeader("Connection", "close");
hr.onreadystatechange= function(){
if(hr.readyState==4 && hr.status==200){
var return_data=hr.responseText;
console.log(hr.responseText);
document.getElementById("status").innerHTML=return_data;
}
}
hr.send(param);
document.getElementById("status").innerHTML = "processing...";
}
Here's the php (btw, I console.logged the data being sent to the php and it is correct):
<?php
if($_POST){
$data = $_POST["film"];
$file ='movie.txt';
$fp = fopen($file, "a");
$encoded = json_encode($data);
fwrite($fp, $encoded);
fclose($fp);
return $encoded;}
?>
As mentioned above, the code only writes the time and date to the text file and nothing more no matter what I do. I tested the data being sent and it's valid $_POST data. I'm not sure how else to proceed. Any helop would be appreciated. Thx!
try this code in movie.js
function addStuff() {
var movie_name_entered = document.getElementById("box").value;
var movieList = document.getElementById("list");
var hr = new XMLHttpRequest();
var url = "movie.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var param = "film=" + movie_name_entered;
hr.setRequestHeader("Content-length", param.length);
hr.setRequestHeader("Connection", "close");
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
console.log(hr.responseText);
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(param);
document.getElementById("status").innerHTML = "processing...";
}
Please change your php code to below
if ($_POST) {
$data = $_POST["film"];
$file = 'movie.txt';
$fp = fopen($file, "a+");
$encoded = json_encode($data);
fwrite($fp, $encoded);
fclose($fp);
exit();
}
you are getting a empty $_POST variable so your php code is never gets executed. you have a mistake in your code :
hr.setRequestHeader("Context-type","application/x-www-form-urlencoded");
it should be Content-type , replace x with c :D

Categories