KiloJKilo
KiloJKilo

Reputation: 485

Getting fopen/fwrite to write to different directory

I need to write text files, i try with this code

public function ResultsTrackingLogs( $event, $message ) {
$logsDir = dirname( __FILE__ ) . "/logs/Results Tracking/$event/";
$fh = fopen( $logsDir . "$event.txt", 'x' ) or die( "can't open file" );
fwrite( $fh, $message );
fclose( $fh );
}

The $logsDir translates into E:\Dropbox\htdocs\Scrapers\this beyond that the \$event\ makes it so each event has its own subfolder.

Anyway I adjust.. I.E /logs/Results Tracking/ .. or \logs\Results Tracking\..

still gives me an error fopen(E:\Dropbox\htdocs\Scrapers\this\logs/Results Tracking/event1/event1.txt): failed to open stream: No such file or directory.

the directory is there, I've created a .txt file there too, doesn't find it. the problem is obviously in how I describe my directory structure. how do i fix this? I don't want to create the directory structure before, I need it to create folders as it needs to.

Upvotes: 0

Views: 1781

Answers (1)

Fabio Mora
Fabio Mora

Reputation: 5479

Check if the destination dir exists, create it if not.

   if(! is_dir($logsDir) ) { mkdir($logsDir, 0777, true); }

You could use the DIRECTORY_SEPARATOR if you want to describe a path.

Upvotes: 1

Related Questions