Mantykora 7
Mantykora 7

Reputation: 173

PHP bytes to kilobytes

I have something like this

<td><?php echo $row_rsPhoto['size']; ?></td>

and displays the file size in bytes, can do that in kilobytes, I'm trying to do this - function

public function size_as_kb()
{
    if ($this->size < 1024) {
        return "{$this->size} bytes";
    } elseif ($this->size < 1048576) {
        $size_kb = round($this->size/1024);
        return "{$size_kb} KB";
    } else {
        $size_mb = round($this->size/1048576, 1);
        return "{$size_mb} MB";
    }
}

I do not know if this works and how to connect it $row_rsPhoto['size']; with function

thank you in advance for your help

Upvotes: 1

Views: 15821

Answers (5)

arilia
arilia

Reputation: 9398

look at this discussion

PHP filesize MB/KB conversion

then you can use

<td><?php echo size_as_kb($row_rsPhoto['size']); ?></td>

Upvotes: 5

Prasanth
Prasanth

Reputation: 5258

This outputs Kilo Bytes..

<td><?php echo $row_rsPhoto['size'] >> 10; ?></td>

Upvotes: 3

Mohammad Ismail Khan
Mohammad Ismail Khan

Reputation: 651

just need to call the function and add parameters to it.

<td><?php echo size_as_kb($row_rsPhoto['size']); ?></td>

 public function size_as_kb($size) {
if($size < 1024) {
return "{$size} bytes";
} elseif($size < 1048576) {
$size_kb = round($size/1024);
return "{$size_kb} KB";
} else {
$size_mb = round(size/1048576, 1);
return "{$size_mb} MB";
}
}

Upvotes: 1

timod
timod

Reputation: 595

use function parameters:

 echo size_as_kb($row_rsPhoto['size']);

public function size_as_kb($size=0) {
    if($size < 1024) {
    return "{$size} bytes";
    } elseif($size < 1048576) {
    $size_kb = round($size/1024);
    return "{$size_kb} KB";
    } else {
    $size_mb = round($size/1048576, 1);
    return "{$size_mb} MB";
    }
    }

Upvotes: 1

mavrosxristoforos
mavrosxristoforos

Reputation: 3643

You wrote your answer. Only you needed to add the parameter of the function.

public function size_as_kb($yoursize) {
  if($yoursize < 1024) {
    return "{$yoursize} bytes";
  } elseif($yoursize < 1048576) {
    $size_kb = round($yoursize/1024);
    return "{$size_kb} KB";
  } else {
    $size_mb = round($yoursize/1048576, 1);
    return "{$size_mb} MB";
  }
}

Call that by writing

$photo_size = size_as_kb($row_rsPhoto['size']);

Upvotes: 1

Related Questions