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