Jpaji Rajnish Jpaji Rajnish - 7 months ago 18
PHP Question

Possible to have one config file for javascript and php?

I have some host-specific values I keep various config files for but now I need some of their values in my javascript code. How can I have one config for both javascript and php?

The information in the config should be private if possible as it contains host/database credentials.

Answer

If your configuration is contained in an object you can fully disclose, you can simply do:

<script>var config = <?php echo json_encode($config); ?>;</script>

But if you only want/need some of its properties, you could do something like:

<script>var host = <?php echo $config["host"]; ?>;</script>

or, in a more maintainable way:

<?php

$config = array(
    "host" => "http://example.com",
    "items_per_page" => 10,
    "db_password" => "1234"
);
// Properties you want to include in your JS
$public_properties = array("host", "items_per_page");

// This function returns JSON containing the values from $obj,
// but only for properties contained in $props
function get_public_json($obj, $props) {
    $res = array();
    foreach($props as $prop)
    {
        $res[$prop] = $obj[$prop];
    }
    return json_encode($res);
}

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>My website</title>
    <script>
        var config = <?php echo get_public_json($config, $public_properties); ?>;
        // will look like this: {"host" : "http://example.com", "items_per_page" : 10}
    </script>
</head>
<body>

</body>
</html>
Comments