Overwrite file on server (PHP)
Asked Answered
U

4

9

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

For this I'm using POST and fopen/fwrite but this method only appends to the file and using unlink before writing to the file has no effect. (file_put_contents has the exact same effect)

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.

Unwary answered 8/7, 2014 at 19:3 Comment(1)
No way this could be happening. fopen in w mode is "open file, truncate to zero length". If it was appending, you'd have to be opening in a modeAisha
L
12

Use wa+ for opening and truncating:

$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.

Leclair answered 8/7, 2014 at 19:7 Comment(2)
You must be doing something wrong. As the manual says: it truncates to 0 length.Leclair
i was using string = string + newString and forgetting to call string = "" before clicking save a second time so it was just adding the new ones on each timeUnwary
E
7
file_put_contents($savePath,$fileContent);

Will overwrite the file or create if not already exist.

Einsteinium answered 8/7, 2014 at 19:11 Comment(0)
C
0

read this it will help show all the options for fopen

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

Cheyennecheyne answered 8/7, 2014 at 19:17 Comment(0)
U
-1

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

Unwary answered 9/7, 2014 at 12:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.