简体   繁体   中英

How can a Python script know the path of the PHP file calling it?

I am executing a Python script from foo.php using exec and I want the Python script to know what directory the PHP call is originating from. In this example, it should be: /www/includes

# File tree
/script.py
/www/index.php
/www/includes/foo.php

foo.php

var_dump( exec( "/usr/bin/python /script.py" ) );

script.py

#!/usr/bin/env python

import os

print( os.getcwd() )

I found that os.getcwd() works great when the foo.php URL is called directly in the browser. I get the desired result: /www/includes

However, it does not work when foo.php is being called from another PHP file in a different directory, like /www/index.php .

index.php

require_once '/www/includes/foo.php';

The Python script prints /www since that is where index.php lives.

Problem

How can I get the Python script to return /www/includes when it's executed by foo.php no matter how the foo.php is being called? I have tried some traceback methods with no luck as I think it only applies to tracing errors.

You need to change your working directory to the directory of foo.php, which you should be able to do with chdir:

chdir (__DIR__); # change working dir to current directory.

In foo.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM