簡體   English   中英

如何使用PHP在特定路徑上保存* .txt文件?

[英]How to save a *.txt file with PHP on a specific path?

我正在嘗試編寫一個簡單的PHP腳本,該腳本將字符串寫入.txt文件。 簡單。 為此,我有這個:

<?php
if(isset(isset($_GET["fileName"]) == true && isset($_GET["output"]) == true){
    $fp = fopen($_GET["fileName"], "a+");
    if($fp !== null){
        fputs($fp, $_GET["output"] . "\r\n");
        fclose($fp);
    }
}
?>

但是我確實需要能夠保存到特定位置,所以我寫了這樣的代碼:

<?php
if(isset($_GET["filePath"]) == true && isset($_GET["fileName"]) == true && isset($_GET["output"]) == true){
    $fp = fopen($_GET["filePath"] . $_GET["fileName"], "a+");
    if($fp !== null){
        fputs($fp, $_GET["output"] . "\r\n");
        fclose($fp);
    }
}
?>

但是,當然,這是行不通的。
1.如何使用PHP保存到特定位置?
2.此路徑可以是相對路徑嗎? (我只發送“ / output /”,保存就會按預期完成)。

謝謝。

現在我在這里:

<?php
if(isset($_GET["filePath"]) && isset($_GET["fileName"]) && isset($_GET["output"])){

    $filename=preg_replace('/[^a-z0-9]/i', '', $_GET['fileName']).'.txt';
    $filepathSanitized='http://thepathtomywebsite/~subdomain/'.$_GET["filePath"].$filename;

    echo $filepathSanitized;  // i get the correct path, but no file is present there 
    $fp = fopen($_GET["filepathSanitized"], "a+");
    if($fp !== null){

        fputs($fp, $_GET["output"] . "\r\n");
        fclose($fp);
    }
    else echo ('Something wrong'); // it never gets to this
}
?>

我這樣稱呼上面:

$.get("save_me.php", { filePath: "demo/", fileName: "text", output: 'thing to write into' });

但是沒有文件被創建。 我不知道要調試什么才能找出問題所在。 謝謝。

您可能會發現這是一個權限問題-調試代碼以查看$ fp是否實際設置。

同樣,這樣的代碼可能非常危險,允許在允許訪問Web服務器的任何位置創建或替換文件。 您應該清理文件名,並自己創建完整路徑,例如

//clean any nasties from the filename
$filename=preg_replace('/[^a-z0-9]/i', '', $_GET['fileName']).'.txt';

//calculate a path relative to our document root...
$filepath=$_SERVER['DOCUMENT_ROOT'].'/path/to/files/'.$filename;

但是沒有文件被創建。 我不知道要調試什么才能找出問題所在。 謝謝。

您應該調試傳遞給fopen()的參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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