change variable value in a file in php

69
July 19, 2018, at 04:30 AM

I have a file which is a small place_config.php file.

Take this as an example where i am setting my variables

<?php
//config file
$place_config = array(
    'credentials' => array(
        'sid' => 'some_value',
        'token' => 'some_token'
    )
?>

I want to change the sid and token from the admin panel of the user for the ease. How can i effectively achieve this. One solution which i understand is to make the content of the file in a string with the variables of $_REQUEST placed after the post request write that whole string to the file? Is it a effective approach?

Answer 1

Instead of storing the configuration data in a php file, I'll recommend storing them in a json file which can be easily read/edited through php.

Create a json file, let's say config.json. Then you can load the configuration using $conf = json_decode(file_get_contents("config.json")). You can make changes to the $conf object and save back the configurations as file_put_contents("config.json", json_encode($conf)).

Answer 2

Submit a form with the proper inputs and when submitted call update_place_config():

function update_place_config() {
    include('place_config.php');
    $place_config['credentials']['sid'] = $_POST['sid'];
    $place_config['credentials']['token'] = $_POST['token'];
    $output = '<?php $place_config = ' . var_export($place_config, true) . '; ?>';
    file_put_contents('place_config.php', $output);
    return $place_config; //if you want to get the new config
}

Another option:

$content = file_get_contents('place_config.php');
$content = preg_replace("/('sid' =>) '[^']+'/", "$1 '{$_POST['sid']}'", $content);
file_put_contents('place_config.php', $content);

I personally would store in a database or use JSON if it needs to be a file.

READ ALSO
Data Not Being Sent Back On Ajax Request

Data Not Being Sent Back On Ajax Request

I'm sending an AJAX request to my server to create a new entry in my database, then return the id of the created entryWhen I run my code, the console says that response is undefined

28
laravel queue - job failing without error message

laravel queue - job failing without error message

I'm trying to use a job for massive data upload

84
Problems accessing API with PHP

Problems accessing API with PHP

I am trying to use an API and I'm trying to do it using PHPThe API Instructions Guide says that i need to post 2 required values and I am doing so, but it is showing no return from the API

43
Unable to connect to SQL instance Database on Google Cloud

Unable to connect to SQL instance Database on Google Cloud

Can anyone help me with a Codeigniter application deployment on Google Cloud App Engine? It seems I need to define <project-id>:<region>:<instance-name> somewhere for the mysqli_connect to work (As per this video tutorial goes, I guess that's...

30