...

View Full Version : Confused over fwrite behaviour



adarshakb
10-25-2009, 06:16 PM
I wrote a file using fwrite in Php to a file '\dump.txt'
The file was created in C:\dump.txt and not in my web site folder (as i am running a local server its c:\docs\)

I couldnt understand why. As when i read using fread() then it checks in my web site folder. But while writing it writes to c:\

How to make it write in my current directory the page is located in?

adarshakb
10-25-2009, 06:36 PM
here is my code the problem occurred in



<?php
$file='\dump.txt';
if(isset($_POST['submit']))
{
if($_POST['txt']!='Enter here')
{
$fo=fopen($file,'a') or die('File op error');
//echo "Wrote $_POST['txt']";
fwrite($fo,$_POST['txt'].'<br />') or die('File op error');
fclose($fo);
$_POST['txt']="Enter here";
}
}
if(file_exists($file))
{
$read=file('c:'.$file);
echo "Contents of the file DUMP are:<br /><br />";

foreach($read as $i)
{
echo $i."<br />";
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<input name="txt" type="text" value="Enter here" />
<input name="submit" type="submit" value="submit" />
</form>

Fou-Lu
10-25-2009, 07:53 PM
\ is interpreted as root:


>php -r "print realpath('\\');"
C:\

On *nix based filesystems, that would still be interpreted as just root (/). Note there are two in this code since otherwise it will attempt an escape where it doesn't belong.
To write to you're current executing directory (this is different than the __FILE__ directory), you can just omit the / or \ from the path. Just use the file name.
Should this file be included from another location however, this will refer to that path, not this file. If it always needs to be relative to this file, you can use this:


$file= dirname(__FILE__) . '/dump.txt';

And you can translate it with realpath if you desire. Also, get into the habit of using '/' instead of '\'. '/' is used for universal identifiers, and will be translated properly in a windows environment; however, I don't think that *nix cares one bit for \ in their file paths.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum