devnotes.

Working with JSON and File Uploads

JSON is PHP's most common data interchange format, especially for APIs.

$data = ['name' => 'Alice', 'age' => 30, 'tags' => ['admin', 'active']];

$json = json_encode($data);            // PHP array -> JSON string
$json = json_encode($data, JSON_PRETTY_PRINT); // human-readable formatting

$decoded = json_decode($json, true);   // JSON string -> associative array
$object  = json_decode($json);          // JSON string -> stdClass object

if (json_last_error() !== JSON_ERROR_NONE) {
    echo 'Invalid JSON: ' . json_last_error_msg();
}

File uploads arrive in the $_FILES superglobal. A basic, safe upload handler:

if ($_FILES['avatar']['error'] === UPLOAD_ERR_OK) {
    $tmpPath = $_FILES['avatar']['tmp_name'];
    $originalName = basename($_FILES['avatar']['name']);
    $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));

    $allowed = ['jpg', 'jpeg', 'png', 'webp'];
    if (!in_array($extension, $allowed, true)) {
        throw new InvalidArgumentException('File type not allowed.');
    }

    $safeName = uniqid('avatar_', true) . '.' . $extension;
    $destination = __DIR__ . '/uploads/' . $safeName;

    move_uploaded_file($tmpPath, $destination);
}

Security essentials for uploads: never trust the client-supplied filename or MIME type as-is; validate the actual file content (e.g. getimagesize() for images); generate a new, random filename rather than reusing the user's; store uploads outside the public web root when possible, or serve them through a controller that checks permissions; and always enforce a maximum file size both in PHP config (upload_max_filesize) and in your validation code.

PHP JSON Encoding and Secure File Uploads | DevNotes