Ood
Ood

Reputation: 1795

Request another PHP file with any Method (NOT cURL!)

I am building an API in PHP and want the user to include some plug-ins written in any language of choice in a designated directory. The way this should work is that the API sends a request to that user's plug-in file and returns the result.

This should be accomplished without cURL, because cURL is unavailable in this particular environment, so answers using cURL won't be helpful.

The issue that I am having is that my function literally reads the contents of the file (without executing it) when the plug-in is also written in PHP.

This is my code:

function sendRequest($url, $method, $body){

    $http = array(
        
        'method' => $method,
        'header' => 'Authorization: sometoken' . "\r\n".
                    'Content-Type: application/json' . "\r\n",
        'content' => $body
    
    );
    
    $context = stream_context_create(array('http' => $http));

    if($file = file_get_contents($url, false, $context)){

        return $file;

    }
    else{

        return 'Error';

    }

}

This is an example of a simple plug-in file written in PHP:

<?php

    $input = file_get_contents('php://input');
    $input = json_decode($input, true);

    echo($input['a'] + $input['b']);

?>

When it is requested from the API it should return the value of a + b. The above code could also be implemented in any other language, it should work either way. These files are stored locally, not on a remote server (where it would work flawlessly).

Is there any way force the file to be executed without cURL? I imagine include and require are also not an option, since the plug-in file should be in a language of choice, not necessarily PHP.

Thanks in advance!

Upvotes: 0

Views: 113

Answers (1)

DragonYen
DragonYen

Reputation: 968

You'll want to look at the PHP command exec

This would allow you do to something like:

exec('php plugin.php param1', $output);

Then read the results back via the $output variable.

Similar things could be done with other applications/scripts (provided they process with absolutely no interaction).

Upvotes: 1

Related Questions