반응형
PHP는 MB / KB 변환을 파일 화합니다
filesize()
MegaBytes, KiloBytes 등으로 PHP 함수 의 출력을 멋진 형식으로 변환해야 할 일?
처럼 :
- 크기가 1MB 미만인 경우 크기를 KB로 표시하십시오.
- 1MB-1GB 사이이면 MB로 표시
- 더 큰 경우 -GB
다음은 샘플입니다.
<?php
// Snippet from PHP Share: http://www.phpshare.org
function formatSizeUnits($bytes)
{
if ($bytes >= 1073741824)
{
$bytes = number_format($bytes / 1073741824, 2) . ' GB';
}
elseif ($bytes >= 1048576)
{
$bytes = number_format($bytes / 1048576, 2) . ' MB';
}
elseif ($bytes >= 1024)
{
$bytes = number_format($bytes / 1024, 2) . ' KB';
}
elseif ($bytes > 1)
{
$bytes = $bytes . ' bytes';
}
elseif ($bytes == 1)
{
$bytes = $bytes . ' byte';
}
else
{
$bytes = '0 bytes';
}
return $bytes;
}
?>
내가 만든 플러그인 에서 만든이 버전이 더 좋습니다.
function filesize_formatted($path)
{
$size = filesize($path);
$units = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$power = $size > 0 ? floor(log($size, 1024)) : 0;
return number_format($size / pow(1024, $power), 2, '.', ',') . ' ' . $units[$power];
}
파일 크기 () 문서 에서 참고
PHP의 정수 유형이되고 서명 된 많은 플랫폼이 32 비트 정수를 사용하는 일부 파일 시스템에서 2GB보다 큰 파일에 대해 함수가없는 결과를 반환 할 수 있습니다.
보다 깔끔한 :
function Size($path)
{
$bytes = sprintf('%u', filesize($path));
if ($bytes > 0)
{
$unit = intval(log($bytes, 1024));
$units = array('B', 'KB', 'MB', 'GB');
if (array_key_exists($unit, $units) === true)
{
return sprintf('%d %s', $bytes / pow(1024, $unit), $units[$unit]);
}
}
return $bytes;
}
나는 그것이 더 나은 생각한다. 간단하고 똑바로.
public function sizeFilter( $bytes )
{
$label = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB' );
for( $i = 0; $bytes >= 1024 && $i < ( count( $label ) -1 ); $bytes /= 1024, $i++ );
return( round( $bytes, 2 ) . " " . $label[$i] );
}
이것은 @adnan의 훌륭한 답변을 기반으로합니다.
변경 사항 :
- 내부 파일 크기 () 호출 추가
- 초기 스타일을 반환
- 하나의 연결을 1 바이트에 저장
그리고 순수 바이트 형식화 함수를 위해 여전히 파일 크기 () 호출을 호출 할 수 있습니다. 그러나 이것은 파일에서 작동합니다.
/**
* Formats filesize in human readable way.
*
* @param file $file
* @return string Formatted Filesize, e.g. "113.24 MB".
*/
function filesize_formatted($file)
{
$bytes = filesize($file);
if ($bytes >= 1073741824) {
return number_format($bytes / 1073741824, 2) . ' GB';
} elseif ($bytes >= 1048576) {
return number_format($bytes / 1048576, 2) . ' MB';
} elseif ($bytes >= 1024) {
return number_format($bytes / 1024, 2) . ' KB';
} elseif ($bytes > 1) {
return $bytes . ' bytes';
} elseif ($bytes == 1) {
return '1 byte';
} else {
return '0 bytes';
}
}
이것은 더 육체적 인 구현입니다.
function size2Byte($size) {
$units = array('KB', 'MB', 'GB', 'TB');
$currUnit = '';
while (count($units) > 0 && $size > 1024) {
$currUnit = array_shift($units);
$size /= 1024;
}
return ($size | 0) . $currUnit;
}
완전한 예.
<?php
$units = explode(' ','B KB MB GB TB PB');
echo("<html><body>");
echo('file size: ' . format_size(filesize("example.txt")));
echo("</body></html>");
function format_size($size) {
$mod = 1024;
for ($i = 0; $size > $mod; $i++) {
$size /= $mod;
}
$endIndex = strpos($size, ".")+3;
return substr( $size, 0, $endIndex).' '.$units[$i];
}
?>
function getNiceFileSize($file, $digits = 2){
if (is_file($file)) {
$filePath = $file;
if (!realpath($filePath)) {
$filePath = $_SERVER["DOCUMENT_ROOT"] . $filePath;
}
$fileSize = filesize($filePath);
$sizes = array("TB", "GB", "MB", "KB", "B");
$total = count($sizes);
while ($total-- && $fileSize > 1024) {
$fileSize /= 1024;
}
return round($fileSize, $digits) . " " . $sizes[$total];
}
return false;
}
다음은 바이트를 KB, MB, GB, TB로 변환하는 간단한 함수입니다.
# Size in Bytes
$size = 14903511;
# Call this function to convert bytes to KB/MB/GB/TB
echo convertToReadableSize($size);
# Output => 14.2 MB
function convertToReadableSize($size){
$base = log($size) / log(1024);
$suffix = array("", "KB", "MB", "GB", "TB");
$f_base = floor($base);
return round(pow(1024, $base - floor($base)), 1) . $suffix[$f_base];
}
function calcSize($size,$accuracy=2) {
$units = array('b','Kb','Mb','Gb');
foreach($units as $n=>$u) {
$div = pow(1024,$n);
if($size > $div) $output = number_format($size/$div,$accuracy).$u;
}
return $output;
}
//Get the size in bytes
function calculateFileSize($size)
{
$sizes = ['B', 'KB', 'MB', 'GB'];
$count=0;
if ($size < 1024) {
return $size . " " . $sizes[$count];
} else{
while ($size>1024){
$size=round($size/1024,2);
$count++;
}
return $size . " " . $sizes[$count];
}
}
질문에 대한 모든 답변은 1 킬로바이트 = 1024 바이트를 사용합니다 . ( 1 키비 바이트 = 1024 바이트 )
질문에서 파일 크기 변환을 요청하기 때문에 1KB = 1000 바이트를 많이 사용합니다 ( https://wiki.ubuntu.com/UnitsPolicy 참조 )
function format_bytes($bytes, $precision = 2) {
$units = array('B', 'KB', 'MB', 'GB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1000));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1000, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
참고 URL : https://stackoverflow.com/questions/5501427/php-filesize-mb-kb-conversion
반응형
'IT' 카테고리의 다른 글
TypeScript 정적 클래스 (0) | 2020.07.15 |
---|---|
Javascript에서 goto를 어떻게 사용합니까? (0) | 2020.07.15 |
버전 관리를하는 이유는 무엇입니까? (0) | 2020.07.15 |
TFS에서 로컬 폴더 삭제 (0) | 2020.07.14 |
브라우저 링크-툴바 (0) | 2020.07.14 |