Jump to content

Writing into a file


dalawh

Recommended Posts

When you set a file to read and write, I know you can read it using fread, but can you read it using the url (site.com/logs.txt)? Now if you set it to write only, I assume fread does not work right? Does reading it using the url work?

Link to comment
Share on other sites

The PHP server can be configured so that you can use URLs or other protocols with fopen, although not everything may be supported. I doubt you'll find a server anywhere that will let you write to a file via HTTP even though it may technically be possible (e.g., a server configured with HTTP PUT support to write to the filesystem).

Link to comment
Share on other sites

The PHP server can be configured so that you can use URLs or other protocols with fopen, although not everything may be supported. I doubt you'll find a server anywhere that will let you write to a file via HTTP even though it may technically be possible (e.g., a server configured with HTTP PUT support to write to the filesystem).
That is not what I meant. Sorry for the confusion. What I was trying to ask is that am I able to look at the file through url, meaning if I type the url into the address and hit enter, will the contents appear, if it was set to write only.
Link to comment
Share on other sites

The mode that you open a file in doesn't affect the original file, it doesn't change the permissions or anything like that. It's just the mode for that particular file stream.
Oh okay, so it is just how the f__ works. Is there anyway to prevent the .txt file from being accessed through the url? Do I just change the chmod of a folder that it is in?
Link to comment
Share on other sites

Guest So Called
That is not what I meant. Sorry for the confusion. What I was trying to ask is that am I able to look at the file through url, meaning if I type the url into the address and hit enter, will the contents appear, if it was set to write only.
If you create a text file in a directory that is accessible to the web then a browser could access the file and view the contents (if any). "Write only" affects only the specific instance of PHP using the file handle that's assigned. The "write only" does not affect access of that file from the web.
Link to comment
Share on other sites

  • 2 weeks later...

Not sure what is wrong, it says it does not truncate, but it seems like it does. Every time I use fwrite inside the same fopen, it writes after it, instead of above it. Every time I use fwrite to a different fopen, it cleans it and writes.

Link to comment
Share on other sites

Guest So Called

That's the way it is supposed to work. If you open it with truncate it will delete the contents and start writing at beginning of file. Continued writes are appended after. If you want every write to truncate all contents you'll have to open/write/close for each time. If you don't want to truncate then open the file in append mode.

Link to comment
Share on other sites

That's the way it is supposed to work. If you open it with truncate it will delete the contents and start writing at beginning of file. Continued writes are appended after. If you want every write to truncate all contents you'll have to open/write/close for each time. If you don't want to truncate then open the file in append mode.
I am trying to keep track of the IPs of all visitors, so I am opening, writing, closing, opening, writing, closing, etc. I want to keep all the content, so I want it to write to the top of the text file. It says "c" does not truncate, so it should not delete. Am I right? It also says the pointer is positioned at the beginning.
Link to comment
Share on other sites

Guest So Called

Why you don't just do what most people would do, open the file for append and the new entries will appear at the bottom? Upon reviewing the choices http://www.php.net/manual/en/function.fopen.php I'm not sure you can even do what you're trying to do, insert a record at the beginning of the file and keep the rest of the contents. You could of course do that by starting a new file each time, adding your new record, then appending the old file contents to the new file (possibly followed by deletion of the old file and renaming the new file to the old file name). Post some code including how you open the file, how you write to it, and how you close the file. Also be advised that if it is possible for two visitors to access your site at the same time you may end up with race conditions and no guaranteed results. Also be advised that if you intend to port your code, like from WAMP to LAMP, your code may not work the same after ported. Also be advised that you'll be better off if you keep such data in a MySQL database rather than a flat text file.

Link to comment
Share on other sites

Why you don't just do what most people would do, open the file for append and the new entries will appear at the bottom?
It thought it would be easier reading the most current at the top than the bottom, but if it is not possible, I will do that.
Upon reviewing the choices http://www.php.net/m...ction.fopen.php I'm not sure you can even do what you're trying to do, insert a record at the beginning of the file and keep the rest of the contents. You could of course do that by starting a new file each time, adding your new record, then appending the old file contents to the new file (possibly followed by deletion of the old file and renaming the new file to the old file name).
I looked at http://www.php.net/manual/en/function.fopen.php and it seems "c" should do the job. jsg confirmed it did too.It says if the file does not exist, it creates it. If the file exists, it does no truncate it and it points to the beginning. Am I reading it wrong?
Post some code including how you open the file, how you write to it, and how you close the file.
Um... here is the simple version.
<?php$file=fopen("random.txt","c");fwrite($file,"BOO");fclose($file);?>

Ignore the syntax if anything went wrong. I just wrote it up quickly.

Also be advised that if it is possible for two visitors to access your site at the same time you may end up with race conditions and no guaranteed results.
That is unlikely until it the site gets popular, but it is something to worry about. When you say no guaranteed results, do you mean it won't write or it won't write correctly or one of them is ignored? Is there any way to deal with this?
Also be advised that if you intend to port your code, like from WAMP to LAMP, your code may not work the same after ported.
I am using XAMPP to test things out right now. Once I am done, I will upload it to a file hosting site and hopefully test it out.
Also be advised that you'll be better off if you keep such data in a MySQL database rather than a flat text file.
I will switch over MySQL database later. I want to practice PHP right now to get a better hang of it.
Link to comment
Share on other sites

Guest So Called

Well I copied your code and ran it on my shared hosting site (LAMP) and it runs exactly the same for me as it does for you. When you open with "c" it positions the pointer at the beginning of the file, and as soon as you write it truncates (destroys) the contents of the file. So irrespective of how you expect it to work or wish it to work, it doesn't work that way. And note that in the explanation of "c" it does not say that it doesn't destroy the file contents:

Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file. This may be useful if it's desired to get an advisory lock (see flock()) before attempting to modify the file, as using 'w' could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).
It just says the pointer is at the beginning of the file. It says nothing about what will happen if you write. It neither says the rest of the file will be saved nor does it say it will be destroyed. I think we know now that the latter is the case, that a write will destroy the file. You can jump through hoops if you like. You could read in the file, append it to your new entry, then write it back out. Or you can just open for a normal append and have your file in chronological order, most recent entry last. By the way, you have neglected to test your file open for success, which is not good programming practice. Better:
<?php$file=fopen("random.txt","c");if ($file) {    fwrite($file,"BOO");    fclose($file);}?>

Link to comment
Share on other sites

Oh. We must of misread it. Instead of using "a" to write to the end, can't I used "w" to create the text file and every case after the first, use "r+" to write to the top? I assume there is no option where you can create and write to the top right? Opening a file is not always guaranteed? If it doesn't open, should I use a recursive method to repeat itself (as in open and write)?

Link to comment
Share on other sites

Guest So Called

I suggest you try any other a, w, r+ or anything you think will work. It took me perhaps 10 minutes to set up the test, I presume you can do it more quickly since you have a local server and you already have the code. (I deleted my code when I finished checking it out.) Please note that I am not an authority on every possible way to open a file. When I need to do something new I read the docco and do whatever it says. I'm not aware of any way to insert records at the beginning of a file but that is no indication that it cannot be done. No, we did not misread it. We simply made mistaken assumptions. The docco does not say either way whether the remainder of the file will be saved or truncated. When you've assumed that fopen() will open the file you've made another unwarranted assumption. The docco says "Returns a file pointer resource on success, or FALSE on error." Obviously there can be an error. For example, if there is a path name and no such path exists then fopen() will probably fail. Your path could also point to an area where you do not have permissions to open or write to such a file. You could recurse but if the error is a permanent condition would be recursing forever. OTOH an error could be temporary too. For example it's possible to lock a file so if you attempt to open it for write mode it will fail, but when the other process unlocks the file then your code will be able to proceed. In your case it would be unlikely/impossible for a file to be locked unless you locked it yourself. So I advise that you should write test code and play with it. That is how I learned PHP functions, and I presume that's how most people learn. You read the docco, you try to execute test code, that fails, so you go back and read again, write test code again, etc. until your code works. Sometimes you give up and find another way to get the job done.

Link to comment
Share on other sites

You can also use file_get_contents and file_put_contents. file_put_contents('log.txt', $new_entry . file_get_contents('log.txt'));
Too bad the file_put_contents erases everything instead of adds to it. I just wrote this. Everything seems to work fine. Tell me what you think of it.
  $fileName='firstVisitLog.txt';  require 'date.php';  $data=$last.' | '.$first.' | '.getIP().' | '.getDateInfo().' | '.$_SERVER['SCRIPT_FILENAME']."\r\n";  if(file_exists($fileName)){ //File exists   $prev=file_get_contents($fileName);   $file=fopen($fileName,"r+"); //Writes to beginning   if($file){ //File opens successfully	//Writes 'last | first | IP | date and time | page' into firstVisitLog.txt	fwrite($file, $data."\r\n".$prev);	fclose($file);   }  } else{ //File does not exists   $file=fopen($fileName,"a+"); //Creates and writes into it.   if($file){ //File opens successfully	//Writes 'last | first | IP | date and time | page' into firstVisitLog.txt	fwrite($file, $data);	fclose($file);   }  }

Is there a better way to do this? I checked to make sure the file was opened correctly before writing into it like so called said. To be honest... they need to add a fwrite options where none of the contents gets deleted. I am sure many people use them in different fopen and they don't want their data deleted. Oh well.

Edited by dalawh
Link to comment
Share on other sites

Too bad the file_put_contents erases everything instead of adds to it.
You can have it append to the bottom, you can't have it insert to the top though.
Is there a better way to do this?
file_put_contents is the equivalent of fopen, fwrite, fclose. You can have it either replace the contents or append, and it will create the file if it doesn't exist.
This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file. If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...