Creating and writing a file in WordPress using PHP

Marina Santini picture Marina Santini · Sep 14, 2011 · Viewed 10.3k times · Source

I would like to create a file to cache my lookups (coordinates and so on). I don't know why but I cannot create and write to it within WordPress. I am using this code for a try:

<?php

 $filename = 'sitevisitors.txt';

 if (file_exists($filename)) 
 {
    $count = file(TEMPLATEPATH . 'sitevisitors.txt'); 
    $count[0] ++;
    $fp = fopen(TEMPLATEPATH . "sitevisitors.txt", "w");
    fputs ($fp, "$count[0]");
    fclose ($fp);
    echo $count[0];
 } 

 else 
 {
    $fh = fopen(TEMPLATEPATH . "sitevisitors.txt", "w");
    if($fh==false)
        die("unable to create file");
    fputs ($fh, 1);
    fclose ($fh);
    $count = file(TEMPLATEPATH . 'sitevisitors.txt'); 
    echo $count[0];
 }

 ?> 

I do not get any error message, but the file "sitevisitors.txt" is not created and update and does not appear on my server. What am I doing wrong? The path should be ok. My server host confirms that I have full privileges. This code works beautifully outside WordPress...

Any suggestion is welcome!

Cheers, Marina

Answer

mishu picture mishu · Sep 14, 2011

The TEMPLATEPATH constant doesn't have a slash at the end, you should use it like:

$fh = fopen(TEMPLATEPATH . "/sitevisitors.txt", "w");

notice the slash just before the filename