Uberfuzzy
Uberfuzzy

Reputation: 8372

In PHP, Best way to ensure current working directory is same as script , when using CLI

When calling php via cli, the current directory is NOT changed to the one of the script. All the scripts i have running in crontab run via the CLI, so this is an issue.

I'm currently fixing the problem by doing a chdir() with the absolute path where the script is, but i REALLY dont like hardcoding paths into stuff like that.

I'm looking for the most portable/reliable method for ensuring that the current working directory is the one where the script it is at.

Upvotes: 16

Views: 6978

Answers (2)

eyelidlessness
eyelidlessness

Reputation: 63519

chdir(dirname(__FILE__));

Upvotes: 37

hasseg
hasseg

Reputation: 6807

You can use __FILE__ to get the full absolute path to the executing file itself:

<?php
echo "I'm here: ".__FILE__."\n";
?>

See the documentation for more info.

Upvotes: 3

Related Questions