Jump to content

PHP write function to a text file in another or different folder


Recommended Posts

Hey Guys....

 

I am learning how to write to a file....Pretty awesome...I understand how it works, but I need to know if I can run my script in this location ( home/folderA ) and edit a text file in this location ( home/folderB ).  I stole this script from http://www.tizag.com which is a pretty cool website for newbies like me.....Does anyone have any thoughts on this matter?

 

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh);

 

Thanks guys and gals

If your script is located in "home/folderA" and u need to open a file in "home/folderB" ull just need to specify a relative location to the first paramater of fopen(). Ex:

 

$myFile = "../folderB/textFile.txt";
$fh = fopen($myfile, 'w');

 

the "../" will return one folder up from the script directory (folderA), in this case "home". U can use "../" even several times like "../../../". Hope it helps.

Hey thanks for the tip!!  I still have a problem though.  the script is reading the file, but now it isn't writing to the file.  Here is my updated code, can you please take a look at it?

 

Thank you

 

// Checking our file
  $file = "../soda.txt";

// does the file exist?
if(file_exists($file)) 
{


// is it readable?
  if(is_readable($file)) 
  {
    echo $file." is readable! <br/>";
  }


// is it writable?
  if(is_writable($file)) 
  {
echo $file." is writable! <br/>";

$fh = fopen($file, 'w') or die("can't open file");
$stringData = "$htpasswd_text";
fwrite($fh, $stringData);
fclose($fh);
  } 

}

// file does not exist
else { 
   echo("The File Does Not Exist");	 
}

        
       echo "<p><hr></p>"; 
       echo "Your file has been updated!"; 
       echo "<p><hr></p>"; 

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.