覆盖服务器上的文件 (PHP)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24639760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:25:12  来源:igfitidea点击:

Overwrite file on server (PHP)

phpfopenfwriteoverwriteunlink

提问by Luke Pring

I am making an Android application that need to be able to push files onto a server.

我正在制作一个需要能够将文件推送到服务器的 Android 应用程序。

For this I'm using POSTand fopen/fwritebut this method only appends to the file and using unlinkbefore writing to the file has no effect. (file_put_contentshas the exact same effect)

为此,我正在使用POSTandfopen/fwrite但此方法仅附加到文件,并且unlink在写入文件之前使用无效。(file_put_contents具有完全相同的效果)

This is what I have so far

这是我到目前为止

<?php
$fileContent = $_POST['filecontent'];

$relativePath = "/DatabaseFiles/SavedToDoLists/".$_POST['filename'];
$savePath = $_SERVER["DOCUMENT_ROOT"].$relativePath; 

unlink($savePath);

$file = fopen($savePath,"w");
fwrite($file,$fileContent);
fclose($file);

?>

The file will correctly delete its self when I don't try and write to it after but if I do try and write to it, it will appended.

当我之后不尝试写入文件时,该文件将正确删除其自身,但如果我尝试写入文件,它将被附加。

Anyone got any suggestions on overwriting the file contents?

有人对覆盖文件内容有什么建议吗?

Thanks, Luke.

谢谢,卢克。

回答by putvande

Use wa+for opening and truncating:

使用wa+开启和截断:

$file = fopen($savePath,"wa+");

fopen

打开

w+: Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

a+: Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

w+: 可读写;将文件指针放在文件的开头并将文件截断为零长度。如果该文件不存在,请尝试创建它。

a+: 开放读写;将文件指针放在文件末尾。如果该文件不存在,请尝试创建它。

回答by andrew

file_put_contents($savePath,$fileContent);

Will overwrite the file or create if not already exist.

如果文件不存在,将覆盖文件或创建。

回答by user583576

read this it will help show all the options for fopen

阅读这将有助于显示 fopen 的所有选项

http://www.php.net/manual/en/function.fopen.php

http://www.php.net/manual/en/function.fopen.php

回答by Luke Pring

Found the error, i forgot to reset a string inside of my application

发现错误,我忘了在我的应用程序中重置一个字符串