Log in

View Full Version : Change contents of a .txt file with php Code Help



biggus
10-01-2008, 01:07 PM
I'm new'ish to PHP so please bare with me. I'll try explain what I'm wanting to do.

I'm wanting to write a php script that I can run as a cron job on a weekly basis to re-write the contents of a text file.

Basically, There is a jpg picture on my website that displays depending on whats in the .txt file. This is good as people who admin the site can change this when need be but now I want to be able to change whats in the txt file every friday.
My script needs to go along the lines of.

Open txtfile
delete all text in the file
write "example text"
save file
close

Could anybody help or point me in the right direction. As I said I'm new to php any help would be appreicated.

Thanks
Biggus

Medyman
10-01-2008, 05:06 PM
Search the PHP forums here. This question has come up before and I'm pretty sure solutions/resources were offered.

biggus
10-02-2008, 09:56 AM
I found this but I can't seem to customize it for my own use.. I'm trying to make sense of it but I'm still new to all this/

http://www.dynamicdrive.com/forums/archive/index.php/t-4539.html

Biggus

Twey
10-02-2008, 01:12 PM
PHP is unnecessary and inelegant here. You can do it directly in cron: have a line in your crontab like:
0 0 0 0 fri echo -n "example text" > /foo/bar/baz.txt

Know the right tool for the job. Hint: that's very rarely PHP. :)

biggus
10-02-2008, 01:27 PM
I've manged it by .php

//the file you want to open
$myFile = "yourfile.txt";

//opening the file
$fh = fopen($myFile, 'w') or die("can't open file");

//data you want to write
$data = "example text";

//writing the data
fwrite($fh, $data);

//close the file
fclose($fh);

I've never written a cron before. Would it be better to use that?

Twey
10-02-2008, 06:37 PM
Much better, yes. There's no need for an external file, and no need for those five lines of code (three discounting redundant variables).

biggus
10-03-2008, 09:24 AM
Thanks Trey for the cron job technique I'm using C-Panel and manged to write it and the bonus is it works :)