PHP create file in same directory as script
Asked Answered
A

2

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 ?

Afterburning answered 26/1, 2018 at 8:4 Comment(2)
You shoud use full path to the folder in PHP codeFlashcube
try __DIR__ constant to access current script directory or basename( __FILE__) if you are running old PHP interpreterSotted
D
3

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

Decline answered 26/1, 2018 at 8:10 Comment(0)
R
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.

Rocky answered 26/1, 2018 at 8:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.