Web Hosting Talk







View Full Version : [php] select text from a text file


-Edward-
01-04-2005, 02:54 PM
Happy new year folks!

The titlemight make this seem like an easy to answer question :)

However here's the complicated bit (well for me anyway).

In my text file that is written to by the users in a chatroom it looks like this:

nickname||color||what the user is saying||user

how can i make it so that if they have a private message when they press update it pulls the message from the text file and displays it in the frame but also deletes the text?

Also, how can i make it so that if in a drop down menu they select the word "everybody" it goes to a file called messages.txt and if they select "user" or "user2" or "user3" from the list it writes to private.txt is this at all possible? user and user2 etc arent hardcoded it's pulling the names from a list of online users.

Burhan
01-05-2005, 03:06 AM
Any reasion you are using text files for this? A database would be much easier, plus -- you wouldn't have to run into file locking problems.

-Edward-
01-05-2005, 05:10 AM
I'm learning about php so im building it in both formats. I think i'll do it with a database as you say due to filelocking. How would I perform the tasks above though?

Burhan
01-05-2005, 05:17 AM
Well, you would have to lock the file, read the contents, delete a line, write back the contents, unlock the file :

Read the following documentation pages :

http://www.php.net/flock
http://www.php.net/fopen
http://www.php.net/fread
http://www.php.net/fwrite

-Edward-
01-05-2005, 05:24 AM
Thanks for those links :)

With the second thing I want todo would I use an if statement? where it would check if it's "everybody" and put it in one place or if it's anything else the it would pass to the } else { and use that command?

valmark
01-06-2005, 02:38 PM
Yes you need a statement to determine which is the group a user is talking to, however doing only 1 if statement is not the best option because if for some reason (it may be bug or user trying to harm your script) the variable assigned by the drop down menu is not everyone nor any 'user' it will still use the else function as it is for 'user'.Better do 2 if satements build in one another:


if ( $talkto == "everyone") {
// Do something for everyone
}
else {
if ($talkto =="user") {
// Do something for user
}
else {
// Wrong selection - msg is going to dev/null :)
}
}


Something like this.

As for reading from text files, you should use the fopen,fread,fput etc. to get a string from the file and then explode this string into pieces and put it into an array :-) But as mentioned above you better use sql for this.

-Edward-
01-07-2005, 05:00 AM
Thanks for your feedback i'll give it a try.