0

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.

2
  • you can't. include() in php acts as if the contents of the file being included were literally cut&pasted into the file doing the include. effectively your foo.php is PART of index.php Commented Nov 25, 2015 at 19:27
  • Thanks MarcB. That was very insightful. Commented Nov 25, 2015 at 20:47

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

This worked. The unfortunate thing with this solution is that it isn't purely resolvable in Python, the working directory has to basically be spoofed in PHP using chdir(). So taking into account MarcB's comment above, it seems as if a true traceback is never going to be possible since Python doesn't have the visibility into the PHP process of including/requiring other files. Thank you both.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.