Hello, I have tried my best in achieving this, and for some reason, it's not working.

What I am trying to do, is to write to file and echo on screen, a converted version of how many bytes/megabytes etc. a file has been uploaded, and echoed on screen upon success, instead of the standard e.g. 101355 bytes.

Here is my present code, and any help would be appreciated, thank you.

<?php

require('security.php');

//set where you want to store files
//in this example we keep file in folder upload
//$HTTP_POST_FILES['ufile']['name']; = upload file name


// DATE STAMP FUNCTION start
$today = mktime(0, 0, 0, date("m"), date("d"), date("y"));
// DATE STAMP FUNCTION end


$path1= "../folder_upload/".$HTTP_POST_FILES['ufile']['name'][0];

copy($HTTP_POST_FILES['ufile']['tmp_name'][0], $path1);

echo "File Name: ".$HTTP_POST_FILES['ufile']['name'][0]."<BR/>";
echo "File Size: ".$HTTP_POST_FILES['ufile']['size'][0]."<BR/>";
echo "File Type: ".$HTTP_POST_FILES['ufile']['type'][0]."<BR/>";
echo "<P>";


///////////////////////////////////////////////////////

// Use this code to display the error or success.


$filesize1=$HTTP_POST_FILES['ufile']['name'][0];
$filesize2=$HTTP_POST_FILES['ufile']['size'][0];

if($filesize1 != 1)
{
echo "<br><b>All files have been successfully uploaded.</b>";

// filesize test

function formatBytes($b,$p = null) {
    /**
     *
     * returns formatted number of bytes.
     * two parameters: the bytes and the precision (optional).
     * if no precision is set, function will determine clean
     * result automatically.
     *
     **/
    $units = array("B","kB","MB","GB","TB","PB","EB","ZB","YB");
    $c=0;
    if(!$p && $p !== 0) {
        foreach($units as $k => $u) {
            if(($b / pow(1024,$k)) >= 1) {
                $r["bytes"] = $b / pow(1024,$k);
                $r["units"] = $u;
                $c++;
            }
        }
        return number_format($r["bytes"],2) . " " . $r["units"];
    } else {
        return number_format($b / pow(1024,$p)) . " " . $units[$p];
    }
}

echo "\n";
echo formatBytes($filesize2);   //returns in MB
echo "\n";
echo formatBytes($filesize2,0); //returns in B
echo "\n";
echo formatBytes($filesize2,1); //returns in kB


// filesize test



// start writing to file


$lines = file('uploaded.txt');
$fopen = fopen("uploaded.txt", "w+");

fwrite($fopen, ("<P align=\"justify\" class=\"para\"><b>")."");
fwrite($fopen, $_POST["date1"]."");
fwrite($fopen, ("<br>")."");
fwrite($fopen, $_POST["header1"]."");
fwrite($fopen, ("</b><br>")."");
fwrite($fopen, $_POST["description1"]."");
fwrite($fopen, ("<br><br>")."");

//GOOD ONE
fwrite($fopen, ("<a href=\"$path1\"><img border=\"0\" src=\"/img/icon1.gif\" align=\"left\" hspace=\"4\" align=\"absmiddle\" width=\"16\" height=\"16\">")."");

fwrite($fopen, ("Posted file</a> - Document size: $filesize2 in bytes/kb/or megabytes etc")."\r\n");

//date stamp
fwrite($fopen, "\n- Posted on ".date("D m/d/Y", $today)."");

fwrite($fopen, (" (Automatically generated)")."");

// Horizontal line
fwrite($fopen, ("<HR style=\"border: 1px dotted #C0C0C0\" color=\"#263E72\" align=\"justify\">")."");

// 1 empty line below <HR>
fwrite($fopen, ("<br>")."");

foreach ($lines as $line) { fwrite( $fopen, "$line"); }

// find and replace function start

echo "\nSuccess writing to file.";

fclose($fopen);

// end writing to file

// find and replace function start
// open file to find \ and other weird characters

include 'find_and_replace.php' ;

}

else {
echo "ERROR.....";
}

?>
Member Avatar for diafol

I'm a bit confused as to what you're going with a file array. You only seem to be dealing with one (item 0).

require('security.php');

function formatBytes($b,$p = null) {
    $units = array("B","kB","MB","GB","TB","PB","EB","ZB","YB");
    $c=0;
    if(!$p && $p !== 0) {
        foreach($units as $k => $u) {
            if(($b / pow(1024,$k)) >= 1) {
                $r["bytes"] = $b / pow(1024,$k);
                $r["units"] = $u;
                $c++;
            }
        }
        return number_format($r["bytes"],2) . " " . $r["units"];
    } else {
        return number_format($b / pow(1024,$p)) . " " . $units[$p];
    }
}

$path1= "../folder_upload/".$_FILES['ufile']['name'][0];
 
copy($_FILES['ufile']['tmp_name'][0], $path1);
 
echo "File Name: ".$_FILES['ufile']['name'][0]."<br/>";
echo "File Size: ".$_FILES['ufile']['size'][0]."<br/>";
echo "File Type: ".$_FILES['ufile']['type'][0]."<br/>";
echo "<br />";

//THIS DOESN'T MAKE SENSE TO ME 
$filesize1=$_FILES['ufile']['name'][0];
$filesize2=$_FILES['ufile']['size'][0];
 
if($filesize1 != 1)
{
	echo "<br><b>All files have been successfully uploaded.</b>";
	echo "\n";
	echo formatBytes($filesize2);   //returns in MB
	echo "\n";
	echo formatBytes($filesize2,0); //returns in B
	echo "\n";
	echo formatBytes($filesize2,1); //returns in kB
	$lines = file_get_contents('uploaded.txt');
	$add= "<p align=\"justify\" class=\"para\"><b> {$_POST['date1']}<br />{$_POST['header1']}</b><br />{$_POST['description1']}<br /><br /><a href=\"$path1\"><img border=\"0\" src=\"/img/icon1.gif\" align=\"left\" hspace=\"4\" align=\"absmiddle\" width=\"16\" height=\"16\">Posted file</a> - Document size: $filesize2 in bytes/kb/or megabytes etc\r\n\n- Posted on ". date("D m/d/Y") . " (Automatically generated) <HR style=\"border: 1px dotted #C0C0C0\" color=\"#263E72\" align=\"justify\">
	<br />" . $lines;
	file_put_contents('uploaded.txt'); 
	echo "\nSuccess writing to file.";
	include 'find_and_replace.php' ;
} else {
	echo "ERROR.....";
}

I have no idea if that will work. But using $_FILES instead of $HTTP_POST_FILES. file_get_contents and file_put_contents looks easier than a million fwrites. You're using raw input into the file - perhaps you should consider sanitizing them. Also the use of copy - what about move_uploaded_file?

Hi Ardav, the script you rewrote did not work, unfortunately.

Here is a stripped down version of my original script. I included a comment in the multiple //////////// slashes.

<?php

require('security.php');

// DATE STAMP FUNCTION start
$today = mktime(0, 0, 0, date("m"), date("d"), date("y"));
// DATE STAMP FUNCTION end

$path1= "../uploaded/".$HTTP_POST_FILES['ufile']['name'][0];

copy($HTTP_POST_FILES['ufile']['tmp_name'][0], $path1);

echo "File Name: ".$HTTP_POST_FILES['ufile']['name'][0]."<BR/>";
echo "File Size: ".$HTTP_POST_FILES['ufile']['size'][0]."<BR/>";
echo "File Type: ".$HTTP_POST_FILES['ufile']['type'][0]."<BR/>";

echo "<P>";

$filesize1=$HTTP_POST_FILES['ufile']['name'][0];
$filesize2=$HTTP_POST_FILES['ufile']['size'][0];


if($filesize1 != 1)
{
echo "<br><b>All files have been successfully uploaded.</b>";

// start writing to file

$lines = file('uploaded.txt');
$fopen = fopen("uploaded.txt", "w+");

fwrite($fopen, ("<P align=\"justify\" class=\"para\"><b>")."");
fwrite($fopen, $_POST["date1"]."");
fwrite($fopen, ("<br>")."");
fwrite($fopen, $_POST["header1"]."");
fwrite($fopen, ("</b><br>")."");

fwrite($fopen, $_POST["description1"]."");
fwrite($fopen, ("<br><br>")."");

fwrite($fopen, ("<a href=\"$path1\"><img border=\"0\" src=\"/img/icon.gif\" align=\"left\" hspace=\"4\" align=\"absmiddle\" width=\"16\" height=\"16\">")."");

/////////////////////////////////////////////////////////////////////////////////////////////////////
//
// The line below will show the uploaded file as "Read this document - Document size 105000 bytes
// I would like it to read as ... Document size 105kb
// How/where can a function be implemented?
//
// And if a 1 meg file or bigger is uploaded, to read as Document size 1.5mb etc.
//
////////////////////////////////////////////////////////////////////////////////////////////////////

fwrite($fopen, ("Read this document</a> - Document size: $filesize2 bytes")."\r\n");

//date stamp
fwrite($fopen, "\n- Posted on ".date("D m/d/Y", $today)."");

fwrite($fopen, (" (Automatically generated)")."");

// Horizontal line
fwrite($fopen, ("<HR style=\"border: 1px dotted #C0C0C0\" color=\"#263E72\" align=\"justify\">")."");

// 1 empty line below <HR>
fwrite($fopen, ("<br>")."");

foreach ($lines as $line) { fwrite( $fopen, "$line"); }

// Success message

echo "\nSuccess writing to file.";

fclose($fopen);

// end writing to file

// find and replace function start
// open file to find \ and other weird characters

include 'find.php' ;

// find and replace function end

}

else {
echo "ERROR.....";
}

?>
Member Avatar for diafol

Hi Ardav, the script you rewrote did not work, unfortunately.

No I didn't really expect it to. There are a number of issues, a couple of which I pointed out in my post. This 'stripped down version' though is the same as the first isn't it, just without the function?

Yes Ardav, very similar. I found many functions to reformat document sizes and figured I would basically drop it at the beginning of the code with some modification, but did not work. One that I found which looked like the one I liked was:

    function formatSize( $bytes )
    {
            $types = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB' );
            for( $i = 0; $bytes >= 1024 && $i < ( count( $types ) -1 ); $bytes /= 1024, $i++ );
                    return( round( $bytes, 2 ) . " " . $types[$i] );
    }

    // now call the formatSize function and pass it a number as bytes

    echo formatSize(8763432); // will echo 8.35 MB
    echo formatSize(258); // will echo 258 B
    echo formatSize( filesize('/path/to/some/file'); // will echo out the file size of that file

---------------------
I figured I could replace "formatSize" with "filesize2" and that would've (I hoped) written the reformatted file size to file.

I posted the same message on another forum and someone told me to use / 1024. That worked with the following code:

$filesize2=$HTTP_POST_FILES[0] / 1024; // works but with many decimal numbers

but when I tried to reduce the amount of decimals with:
$filesize2=$HTTP_POST_FILES[0] / 1024, 2; // Returns an error

I get an error

Member Avatar for diafol

Look at: http://php.net/manual/en/reserved.variables.files.php

Your usage is deprecated.

Also you haven't answered the question wrt arrays, e.g. $HTTP_POST_FILES[0] - why the [0]? Are you uploading more than one file at a time?

Why aren't you using move_upload_file()?

I am using an uploading script that will allow for more than 1 file, if it is needed later on, that is why it's in an array. However, I am open to a single file version.

I am using copy instead of move_upload_file() because the server's giving me an error and is using PHP4 instead of 5. I hate to think of the fact that, if and when they do upgrade to PHP5, my script will no longer work the way it is now.

Member Avatar for diafol

OK, I don't do PHP4 anymore. Perhaps you should get a better host and update your script. Sorry, good luck.

Believe me, if it were up to me, I would definitely move them to a better hosting service. Thanks again, very much appreciated :)

@Ardav...
UPDATE: I figured it out by using the following code:

if( $filesize2 < 1024 )
		$filesize2 = round(($filesize2 / 1024),0) . ' Bytes';

	elseif( $filesize2 >= 1024 && $filesize2 < 104857 )
		$filesize2 = round(($filesize2),0) . ' Bytes';

	elseif( $filesize2 >= 104857 && $filesize2 < 1048576 )
		$filesize2 = round(($filesize2 / 1024),2) . ' KB';

	elseif( $filesize2 >= 1048576 )
		$filesize2 = round(($filesize2 / 1048576),2) . ' MB';
Member Avatar for diafol

Great! Mark as solved. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.