How to convert bytes Into KB, MB, and GB using PHP

In this simple article, we will show you how to convert bytes Into KB, MB, and GB using PHP. This is a simple PHP code that converts bytes Into KB, MB, and GB

HTML Code

<html>
    <body>
        <form method="post"action="">
            <input type="text" name="size" placeholder="Enter Bytes">
            <select name="convert_unit">
                <option>KB</option>
                <option>MB</option>
                <option>GB</option>
            </select>
            <br>
            <input type="submit" name="convert_size" value="Convert Bytes">
        </form>
        <p><?php echo $size; ?></p>
    </body>
</html>

PHP Code

<?php
$size = '';
function convert($size,$unit) 
 {
    if ($unit == "KB") {
        return $fileSize = round($size / 1024, 4) . 'KB';
    }
    if ($unit == "MB") {
        return $fileSize = round($size / 1024 / 1024, 4) . 'MB';
    }
    if ($unit == "GB") {
        return $fileSize = round($size / 1024 / 1024 / 1024, 4) . 'GB';
    }
}

if (isset($_POST['convert_size'])) {
    $size = $_POST['size'];
    $unit = $_POST['convert_unit'];
    $size = convert($size, $unit);
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *