Upload multiple - Write data in json file

Friends, I created a system to upload multiple images but I need to write everything in a json file instead of a database.

I need the id, the id and name of the gallery and the image file is written to the json file, but multiple objects “images” are written in the file. The data should be recorded within a single object “images”.

My script:

// Informações para conexão
$host = ‘localhost’;
$usuario = ‘root’;
$senha = ‘’;
$banco = ‘kurt’;
// Realizando conexão e selecionando o banco de dados
$conn = mysql_connect($host, $usuario, $senha) or die(mysql_error());
$db = mysql_select_db($banco, $conn) or die(mysql_error());
// Definindo o charset como utf8 para evitar problemas com acentuação
$charset = mysql_set_charset(‘utf8’);

include(‘class/resize-class.php’);

$fn = (isset($_SERVER[‘HTTP_X_FILENAME’]) ? $_SERVER[‘HTTP_X_FILENAME’] : false);

function extensao($file_name){
$ext = explode(‘.’, $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}

function criptografa($file_name){
$ext = explode(‘.’, $file_name);
$ext = array_pop($ext);
$nome = md5(uniqid(rand(), true)) . ‘.’ . strtolower($ext);
return $nome;
}

if ($fn) {

$arquivo = criptografa($fn);

// AJAX call
file_put_contents(
‘uploads/’ . $arquivo,
file_get_contents(‘php://input’)
);
echo “$arquivo uploaded”;

$resizeObj = new resize(‘uploads/’ . $arquivo);
$resizeObj -> resizeImage(200, 200, ‘crop’);
$resizeObj -> saveImage(‘uploads/thumb_’ . $arquivo, 100);

$galeria = $_SERVER[‘HTTP_X_GALERIA’];

header(‘Content-Type: application/json;charset=utf-8’);
$filename = ‘test.json’;

$i = 0;
$busca = array();

$busca[$i][‘id’] = rand(1, 99);
$busca[$i][‘galeria’] = $galeria;
$busca[$i][‘imagem’] = criptografa($fn);

foreach($busca as $string)
{

$grava[“imagens”] = $string;

$somecontent = json_encode($grava);

if (is_writable($filename)) {

if (!$handle = fopen($filename, ‘a’)) {
echo “Não foi possível abrir o arquivo ($filename)”;
exit;
}

if (fwrite($handle, $somecontent) === FALSE) {
echo “Não foi possível escrever no aqruivo ($filename)”;
exit;
}

echo “Sucesso. Escreveu ($somecontent) no arquivo ($filename)”;

fclose($handle);

} else {
echo “Impossível escrever em $filename”;
}

}

$i++;

exit();

}