skip to Main Content
$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

Answers


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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search