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 ?

2
  • You shoud use full path to the folder in PHP code Commented Jan 26, 2018 at 8:06
  • 3
    try __DIR__ constant to access current script directory or basename( __FILE__) if you are running old PHP interpreter Commented Jan 26, 2018 at 8:09

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.