Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwrite file on server (PHP)

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.

like image 606
Luke Pring Avatar asked Jul 08 '14 19:07

Luke Pring


3 Answers

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.

like image 159
putvande Avatar answered Nov 18 '22 07:11

putvande


file_put_contents($savePath,$fileContent);

Will overwrite the file or create if not already exist.

like image 22
andrew Avatar answered Nov 18 '22 09:11

andrew


read this it will help show all the options for fopen

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

like image 1
user583576 Avatar answered Nov 18 '22 07:11

user583576