5
$content = "some text here"; 
$fp = fopen("myText.txt","w"); 
fwrite($fp,$content); 
fclose($fp);

The above code creates a file in the folder where the PHP script is present. However when the script is called by Cpanel Cron then file is created in home directory.

I want file to be created in the same folder where the php script is present even if its run by cron.

How to do that ?

Amit Gupta
  • 2,771
  • 2
  • 17
  • 31
Greatchap
  • 382
  • 8
  • 21

2 Answers2

3

Try using __DIR__ . "/myText.txt" as filename.
http://php.net/manual/en/language.constants.predefined.php

Tekk
  • 307
  • 2
  • 4
  • 14
3

Try something like this, using the dirname(__FILE__) built-in macro.

<?php

$content = "some text here";
$this_directory = dirname(__FILE__);
$fp = fopen($this_directory . "/myText.txt", "w");
fwrite($fp, $content); 
fclose($fp);

?>

__FILE__ is the full path of the currently running PHP script. dirname() returns the containing directory of a given file. So if your script was located at /mysite.com/home/dir/prog.php, dirname(__FILE__) would return...

/mysite.com/home/dir

Thus, the appended "./myText.txt" in the fopen statement. I hope this helps.

Tanner Babcock
  • 3,232
  • 6
  • 21
  • 23