update string from text file to server ( somefile.txt )

Hello @ll

this is my first Q in forum :slight_smile:

Ok, I have a text file on my android device which I send to server every 2 min’s

text file contain’s only 1 ( single line ) (filename gps.txt)

that single line in text file look’s like this 45:16.2432432;19:2465467;12;4

in a server directory I have filename gps.txt ( in that file I store data )
curently I use this php script on my server ( named upload_file.php )

[php]<?php

$file_path = "uploads/";
 
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
    echo "success";
} else{
    echo "fail";
}

?>
[/php]

but it only overwrite existing file!!!

how to modify my existing php file so that add only ( new line to existing txt file on server ) ?

B.R.

You don’t want to upload the file from the sounds of it, you want it to read the contents of the file and then append the original.

[START]

  1. Load the file under a tmp name.
  2. Read the contents of that files.
  3. Append the original files with those contents, line by line if necessary.
  4. Close the files.
  5. Delete the tmp file.
    [END]

[php]<?php

//expected data: 45:16.2432432;19:2465467;12;4

//file_path to the saved file.
$file_path = ‘uploads/’;
//file name of the temp file:
$file_name = sys_get_tmp_dir() . $_SERVER[‘uploaded_file’][‘tmp_name’];
//name of the saved file.
$new_file = $_SERVER[‘uploaded_file’][‘tmp_name’];

//if temp file doesn’t exist.
if(!file_exists($file_name)) {
exit(‘The requested file was not uploaded.’);
}

//if the file exists, then get it’s contents into a string.
$contents = file_get_contents($file_name);
//test for expected data.
$contents = preg_replace(’/[^0-9:.;]/’,’’,$contents);
//append it to the saved file, testing to make sure it saved.
if(file_put_contents($file_path . $new_file,$contents . PHP_EOL, FILE_APPEND) !== FALSE) {
echo ‘success.’;
}[/php]

I have try this = not working

[php] <?php
$result = ‘fail’;
$newText = trim(file_get_contents($_FILES[‘uploaded_file’][‘tmp_name’]));
if($newText !== ‘’) {
// [a]ppend mode:
$fh = fopen(‘uploads/’.basename($_FILES[‘uploaded_file’][‘name’], ‘a’);
if(fputs($fh, $newText.PHP_EOL)) {
$result = ‘success’;
}
}
echo $result; [/php]

I have try also this, also not working…

Sponsor our Newsletter | Privacy Policy | Terms of Service