Marina Santini
Marina Santini

Reputation: 99

Creating and writing a file in WordPress using PHP

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

Upvotes: 1

Views: 14289

Answers (1)

mishu
mishu

Reputation: 5397

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

Upvotes: 2

Related Questions