Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this PHP code overwrite file contents while opening?

Tags:

php

I've written some pretty complex PHP apps using this feature, so I'm not sure what's happening here.

I'm currently writing an app that uses an online history to save content (via ajax get). The API I wrote to store the user's history to a file is extremely simple:

$myFile = "./snhistory/".$_GET["uid"];
$stringData = urldecode($_GET["name"])."\n";
$file = fopen($myFile,"a");
fwrite($file,$stringData);
fclose($file);

This looks like the kind of code that adds the data found in name plus a new line to the end of a file, right? Well, that's not how PHP sees it. It adds one name, then when I run the code with a different name, it overwrites the first and only the second one appears. I've tried anything I could think of:

 file_put_contents($myFile,file_get_contents($myFile).$stringData);

And

 file_put_contents($myFile,$stringData,FILE_APPEND);

And

fopen($myFile,"w");
fseek($file,0,SEEK_END);

And all produce the same behaviour. Is it something wrong with PHP or am I missing something here? I feel like if there was a problem in the code, the second thing I tried would have fixed it. But I'm not sure, which is why I'm asking everyone here.

I would really appreciate any help that could be provided.

Edit: As per the answer, the problem with the strings was that they contained punctuation like ' and, for some reason, the url encoding and escaping doesn't work. Read the answer's edit for the final answer.

like image 681
Osmium USA Avatar asked Nov 13 '22 06:11

Osmium USA


1 Answers

Try running the following code on your machine:

<?php
$myFile = "./myfile.txt";
$myString="hello world\n";
$fp = fopen($myFile, "a");
fwrite($fp, $myString);
fclose($fp);
?>

First time I run it (from command line, with php app.php, it creates a file with a single "hello world" line in it.

Run it again, and there are two lines. Again, and there are three...

This is a good test of your basic php installation. If this works, and yet your problem persists, then there's something about the variables you are using that is messing you up - or permissions on the directories, etc. Not a complete solution - but something to help you narrow it down, perhaps?

EDIT Based on the discussions we had in the comments, it seems that this behavior comes and goes depending on the contents of the (URL encoded) variable ($_GET("name")), and that the solution is to "cleanse" the variable - get rid of whatever "bad" characters cause this overwriting behavior. I am adding this information to the answer so people don't have to wade through the answer - if you would provide details on what exact string content makes the behavior appear, it would be helpful to the community.

like image 132
Floris Avatar answered Nov 14 '22 21:11

Floris