簡體   English   中英

在服務器上編輯和保存文件 (PHP)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM