Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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.

like image 987
Uberfuzzy Avatar asked Oct 10 '08 16:10

Uberfuzzy


People also ask

Which function used to identify the current working directory in PHP?

The getcwd() function returns the current working directory.

How to current directory in PHP?

getcwd() returns the path of the "main" script referenced in the URL. dirname(__FILE__) will return the path of the script currently executing.

Can we use PHP to write command line scripts?

A Simple Command Line ScriptYes, we can create a command-line PHP script as we do for web script, but with few little tweaks. We won't be using any kind of HTML tags in command-line scripting, as the output is not going to be rendered in a web browser, but displayed in the DOS prompt / Shell prompt.

What is PHP command line?

PHP's Command Line Interface (CLI) allows you to execute PHP scripts when logged in to your server through SSH. ServerPilot installs multiple versions of PHP on your server so there are multiple PHP executables available to run.


1 Answers

chdir(dirname(__FILE__));
like image 56
eyelidlessness Avatar answered Oct 20 '22 06:10

eyelidlessness