Grant permission to www-data to write to json-file

52 Views Asked by At

I'm trying to make a simple (locally hosted) webpage that calls on a python script to generate a list of random numbers and display them in the browser.

This is generate.php (neglecting enclosing html)

<?php 
    error_reporting(E_ALL);
    ini_set('display_errors', 1);

    //DEBUG
    $pythonExec = '/usr/local/bin/python3';
    $pythonScript = 'gen_array.py';

    clearstatcache();
    if (!file_exists($pythonExec)) {
        exit("The python executable '$pythonExec' does not exist!");
    }
    if (!is_executable($pythonExec)) {
        exit(("The python executable '$pythonExec' is not executable!"));
    }
    if (!file_exists($pythonScript)) {
        exit("The python script file '$pythonScript' does not exist!");
    }

    // Execute it, and redirect STDERR to STDOUT to display error messages
    exec("$pythonExec \"$pythonScript\" 2>&1", $output);

    // Show the output of the script
    print_r($output); 

    $json_data = file_get_contents(__DIR__.'/data.json');
    // Decoding the JSON data to obtain a PHP array
    $php_array = json_decode($json_data, true);

    foreach ($php_array as $element) {
        echo $element . "\n";
    }
?>

This is gen_array.py

import numpy as np
import json

array = np.random.uniform(1.0, 100.0, 10)
a = array.tolist()

# Writing the list to a JSON file
with open('data.json', 'w') as json_file:
    json.dump(a, json_file)

Error 13 in Browser

To pass the list from python to php, a json file is generated and processed into an array on the php end. When I open generate.php in my browser, I get Error 13 indicating no permission to generate and write to data.json. I've done some searching and come up with the reason being that server is trying to accomplish this as user 'www-data' with no permission to write this json-file to my disk. Unfortunately, I can't seem to find out how to circumvent this. How could I grant the necessary permissions? I'm on macOS, running an apache Webserver via XAMPP.

I'm still new to anything dynamic-web. I realise this specific task could easily be completed without external python-scripts, this only serves as an example for me to familiarise. Later, I'll need to do more complicated data analysis that I'm uncomfortable with doing outside of python.

Edit: The additional complaint "null given" appears because I ran gen_array.py in terminal, then deleted the entries in the json-file to see whether running it in browser would write new random numbers to the json-file. It didn't, so this is an empty json-file.

0

There are 0 best solutions below