[英]Edit and save a file on server (PHP)
我有一个页面将 C++ 文件的内容显示到textarea
中,我需要能够使用脚本保存它的内容。 (C++ 文件不必配置,只需保存即可。)
我正在使用 PHP 脚本从文件加载代码以将其显示在textarea
上。 如何将内容发送回脚本并将其保存到同一个文件或具有新名称的文件?
PHP、HTML 文件:
<input type="text" id="filename" value="cpp_get3.cpp"><br>
<textarea id="cpp_content" rows="15">
<?php
$fn = "/var/www/cgi-bin/cpp_get3.cpp";
print htmlspecialchars(implode("",file($fn)));
?>
</textarea><br/>
<button id="save"onclick="savefile();">save</button>
脚本:
var fn = '/var/www/html/mediawiki/php/cpp_get3.cpp';
var cpp_content = document.getElementsByClassNameId('cpp_content')
//Not really sure what to do next
I expect for the C++ file of a text file at this point to get save with the content in the `textarea`.
你不值得我;)
<?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>
另一种选择是通过 XMLHttpRequest 将内容发送到单独的 PHP 文件。 这样您就不必在保存时重新加载页面。 像这样的东西:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.