mfx28
mfx28

Reputation: 23

PHP to save file with JSON format

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.

Upvotes: 0

Views: 75

Answers (1)

drkdsk
drkdsk

Reputation: 64

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.

Upvotes: 1

Related Questions