0

I want to save a file as JSON, with the JSON format using PHP.

Currently I have this code, but instead of variables.txt, I want to save as variables.json, with the JSON file format, something like this: { ssh_user: teste, ssh_pw: teste }

This is my PHP code:

<?php
    extract($_REQUEST);
    $file=fopen("variables.txt","w");

    fwrite($file,"ssh_user: ");
    fwrite($file, $username ."\n");
    fwrite($file,"ssh_pw: ");
    fwrite($file, $password ."\n");
    fclose($file);
?>

This may sound confusing, but can someone give me a tip? Thank you.

3
  • 1
    Are you familiar with the json_encode() function? Commented Jun 15, 2020 at 18:05
  • @ADyson not really, I'm kinda new on JSON and PHP stuff... Commented Jun 15, 2020 at 18:10
  • 1
    @ADyson is what you need. Create and object with those fields and use json_encode to create the json string you need to write to the file. I'd question why you are storing usernames and passwords in plaintext files. Commented Jun 15, 2020 at 21:24

1 Answer 1

1
file_put_contents('variables.json', json_encode([
    'ssh_user' => $_REQUEST['username'] ?? null,
    'ssh_pw'   => $_REQUEST['password'] ?? null,
]));

Please note that your code extract($_REQUEST) can have security implications.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.