简体   繁体   English

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

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

I am trying to write a simple PHP script that writes a string to .txt file. 我正在尝试编写一个简单的PHP脚本,该脚本将字符串写入.txt文件。 Simple. 简单。 For that I have this: 为此,我有这个:

<?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);
    }
}
?>

But I really need to be able to save to a specific location, so I have written this: 但是我确实需要能够保存到特定位置,所以我写了这样的代码:

<?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);
    }
}
?>

But of course, this doesn't work. 但是,当然,这是行不通的。
1. How can I save to a specific location with PHP? 1.如何使用PHP保存到特定位置?
2. Can this path be a relative path? 2.此路径可以是相对路径吗? (i just send "/output/" and the save would be done as expected). (我只发送“ / output /”,保存就会按预期完成)。

Thank you. 谢谢。

Now I am here: 现在我在这里:

<?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
}
?>

And i am calling the above like this: 我这样称呼上面:

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

But no file is created. 但是没有文件被创建。 I don't know what to debug to find out what goes wrong. 我不知道要调试什么才能找出问题所在。 Thank you. 谢谢。

You will probably find this is a permissions issue - debug your code to see if $fp is actually set. 您可能会发现这是一个权限问题-调试代码以查看$ fp是否实际设置。

Also, code like this is potentially very dangerous, allowing a file to be created or replaced anywhere the webserver is allowed to access. 同样,这样的代码可能非常危险,允许在允许访问Web服务器的任何位置创建或替换文件。 You should sanitize the fileName, and create the full path yourself, eg 您应该清理文件名,并自己创建完整路径,例如

//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;

But no file is created. 但是没有文件被创建。 I don't know what to debug to find out what goes wrong. 我不知道要调试什么才能找出问题所在。 Thank you. 谢谢。

You should debug the argument that is passed to fopen(). 您应该调试传递给fopen()的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM