format filesize as bytes kilobyte megabyte kb-mb-gb ending in php

PHP No Comments »

I want to format a filesize in php as either of these bytes, kilobytes, megabytes, gigabytes according to the size of the file.

I found the following codes in php.net comments section

I just copied the following code as it was in the source and i have use only one and not the others.

You can better directly do this url to see the updated function or try the following functions.

You can find these below the documentation of filesize function. (The comments section of the document).

function FileSize($file, $setup = null)
{
    $FZ = ($file && @is_file($file)) ? filesize($file) : NULL;
    $FS = array("B","kB","MB","GB","TB","PB","EB","ZB","YB");
 
    if(!$setup && $setup !== 0)
    {
        return number_format($FZ/pow(1024, $I=floor(log($FZ, 1024))), ($i >= 1) ? 2 : 0) . ' ' . $FS[$I];
    } elseif ($setup == 'INT') return number_format($FZ);
    else return number_format($FZ/pow(1024, $setup), ($setup >= 1) ? 2 : 0 ). ' ' . $FS[$setup];
}

Here is another one

 
function format_bytes($size) {
    $units = array(' B', ' KB', ' MB', ' GB', ' TB');
    for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024;
    return round($size, 2).$units[$i];
}

and yet the simplest one as mentioned in the docs

 
function format_bytes($bytes) {
   if ($bytes < 1024) return $bytes.' B';
   elseif ($bytes < 1048576) return round($bytes / 1024, 2).' KB';
   elseif ($bytes < 1073741824) return round($bytes / 1048576, 2).' MB';
   elseif ($bytes < 1099511627776) return round($bytes / 1073741824, 2).' GB';
   else return round($bytes / 1099511627776, 2).' TB';
}

besides, the document said

It’s very interesting but I can’t stand the decimals for bytes and KB so here’s another example :

 
function format_size($size) {
      $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
      if ($size == 0) { return('n/a'); } else {
      return (round($size/pow(1024, ($i = floor(log($size, 1024)))), $i > 1 ? 2 : 0) . $sizes[$i]); }
}

and then another contributor said

This is a short and very clever function to get filesizes.

 
function format_size($size) {
      $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
      if ($size == 0) { return('n/a'); } else {
      return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]); }
}

and it goes on like the above in http://php.net

Reference

http://php.net/manual/en/function.filesize.php

Scroll the page down to see as many as function like the above and suite yourself.

Enjoy.

set_exception_handler function within a class for example codeigniter

PHP No Comments »

Here is how to use the set_exception_handler function within a class

the defined exception_handler method must be declared as public preferably public static if using the array syntax like array(‘Abc’, ‘exception_handler’) as suggested in php.net site.

class Abc extends CI_Controller {
 
    function __construct()
    {
        parent::__construct();
        set_exception_handler(array('Abc', 'exception_handler');
        //also you can use array($this, 'exception_handler')     
    }       
 
    function exception_handler(Exception $ex)
    {        
        echo $ex->getMessage();
    }
 
    function Index()
    {
        throw new Exception('hehe');
    }
}

The exception handler must be defined before calling set_exception_handler()

so the above code sets the default exception handler if an exception is not caught within a try/catch block. Execution will stop after the exception_handler is called.

Failed to write session data Please verify the current setting of session.save_path

PHP No Comments »

I was updating a project. When i checked my work i got this warning and in could not login in to the site.
Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/tmp).

Then i searched and got the following snippet and it worked but still i have to make it bug free and i am working on it but not immediate.

session_save_path('/home/site/public_html/session');
ini_set('session.gc_probability', 1);

I created a directory ‘session’ in the root folder and gave the write permission.
The above script is just an example.
I ran the script and it worked.

Here we have to think about how the old session files are deleted and what is the need for the ini setting session.gc.probability… instead of me explaining this you better go to the url which i have given below.

If you face the same problem and try the above. And then you should read this article. I, yet to completely test that only then i can post anything here.

If anybody would like to give me more information about this the you can comment on this. And your objections are welcomed.

show html elements on top of youtube video – youtube embed z index – wmode transparent

PHP No Comments »

Assume that you are managing youtube videos in your site admin panel. So they are dynamically displayed in web pages.
Youtube video embed code, as i have seen does not include the option of making the video go behind HTML elements.
When we do some animation you can see that the youtube video is on top of all.

So we need to include the wmode transparent option in the embedd code before displaying.
This attribute(param) will make the youtube video go behing any popups.

Here is the simple code to insert the wmode transparent option into the url before displaying it.

<div class='youtubevideo'>
$string = $url;//youtube video url from database
$string = str_replace("<embed","<param name='wmode' value='transparent'></param><embed",$string);
$string = str_replace("<embed","<embed wmode='transparent' ",$string);
echo $string;
</div>


How to replace the width and height of an embed code or youtube video

force download – authenticated download

PHP No Comments »

Basically downloads are normal direct link to real files in the server with a complete static url link to the file. So any body can click the link and can download the file. Any cross site script can access the file any time or any user can access the file from anywhere.

What if you want to allow file downloads only if the user is logged in.
what if you want to hide the actual file and its folder from displaying it to the user instead you want to show a different url which could probably be a server side script file (.php for example). and that could fetch the actual file with a different name.

For that i use the force download concept. I will just send the id of a file for which its filename and location are always hidden. take this for example…

<a href='sitename.com/files/files.php?id=45'>Click here to download</a>

and in files.php firstly i will check whether the users has logged in and only then i will let the file to download… else nothing happens.

here is a sample code to do a force download.

//select fn from tablename where id=$_request[id]
//assume that the file is in the junk named folder
// the the force download script will look like the following
 
$filename = "doc_O1jtIYi4jkg8Xh2k/$fn";
header("Cache-Control: no-store");
header("Expires: 0");
header("Content-Type: application/octet-stream");
header("Content-disposition: attachment; filename=\"".basename($filename)."\"");
header("Content-Transfer-Encoding: binary");
header('Content-Length: '. filesize($filename));
readfile($filename);

the readfile function reads the contents of a file and outputs to the client.
cache control no-store if for geko browsers and no-cache can be included for IE browsers
You can either use the exact mime type if you know in the place of content-type.

This works in all browsers. People either download, save and view the file or they directly open the file. When they do the second and if their browser is IE 6 then you get a message that ‘cannot access file from temporary internet folder’ so for IE 6 the users has to save the file first and then they have to open it.

If you find any sense if not appropriate then please post a comment.

session side effect session.bug_compat_42 or session.bug_compat_warn

PHP 3 Comments »

Warning: Unknown: Your script possibly relies on a session
side-effect which existed until PHP 4.2.3. Please be advised that
the session extension does not consider global variables as a
source of data, unless register_globals is enabled. You can disable
this functionality and this warning by setting
session.bug_compat_42 or session.bug_compat_warn to off,
respectively. in Unknown on line 0

This error likely appears when setting some thing like this $_SESSION[‘something’] = NULL; or you are assigning a variables value to a session which is null. hopefully.

what people say is better turn off this warning by
 
1. "session.bug_compat_42 = 0" in your php.ini
 
2. setting the following in your .htaccess file
    php_flag session.bug_compat_42 0
    php_flag session.bug_compat_warn 0
 
3. Directly write the following code in your php script where you want to 
stop the warning. It is better if you set it in a common include file.
 
ini_set('session.bug_compat_42',0);
ini_set('session.bug_compat_warn',0);
...

sending mail from localhost in php

PHP 3 Comments »

Use the basic phpmailer code which comes with the phpmailer zip form phpclasses.org
the following code is the default one which sends mail from your server by using the default server settings.

the host name is set to localhost and authentication is false(which takes the default). these are the two lines which
vary when sending mail form localhost.

include("includes/phpmailer/class.phpmailer.php");
 
$mail = new phpmailer();
$mail->PluginDir = "/include/";
$mail->IsSMTP(); // send via SMTP
 
$mail->From = "noreplysample.com";
$mail->FromName = "From Name";
$mail->AddAddress("address@host.com");
$mail->WordWrap = 65; // set word wrap
$mail->IsHTML(true); // send as HTML
$mail->Subject = "Mail Subject";
 
$mail->SMTPAuth = false; // turn off SMTP authentication			
$mail->Host = "localhost"; // SMTP servers
 
$mail->Body = $msg;
$mail->send();

the code to send mail form your localhost to any remote email server
the difference in the above and the following is i have given the important part which need to send mail from localhost
the first below two lines differ from the above. and the last two lines are added.
you have to give your servers auth information to send mail. So when ever mail is sent from localhost to a remote server
a server reference is needed. which means… mail is sent form localhost on-behalf of your server.

 
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Host = "samplesite.com"; // SMTP servers
$mail->Userame = "testing@testing.com";
$mail->Password = "testing";

so when the above lines gets executed this code connects to your site for verification
and then the mail is sent with reference to your server. so
you need a server by using which you can send mails from localhost.

here is the full code which sends mail from localhost.

include("includes/phpmailer/class.phpmailer.php");
 
$mail = new phpmailer();
$mail->PluginDir = "/include/";
$mail->IsSMTP(); // send via SMTP
 
$mail->From = "noreplysample.com";
$mail->FromName = "From Name";
$mail->AddAddress("address@host.com");
$mail->WordWrap = 65; // set word wrap
$mail->IsHTML(true); // send as HTML
$mail->Subject = "Mail Subject";
 
$mail->SMTPAuth = true; 						
$mail->Host = "samplesite.com"; // SMTP servers
$mail->Userame = "testing@samplesite.com";
$mail->Password = "testing";
 
$mail->Body = $msg;
$mail->send();

the from address should be a valid domain string. else mostly your mail will not be sent.

replace width and height of html element using regular expression

PHP 8 Comments »

php code to replace the width and height of any html tag using php and regular expression.

i had a youtube listing for the admin where i display 10 per page but usually the object tag width and height will be around 400×350 approximately.
but i want to show the youtube video small in the admin section so that it will match the size of each row which will have edit, delete buttons…
here i wished the width and height to be around 100×80.

so when i display the youtube object tag code from the data base i used the following regular expression to replace the original width and height with my preferred value.

and here is the code to do the width and height replacement. it works for me and hope for you too…

$pattern = "/height=\"[0-9]*\"/";
$string = preg_replace($pattern, "height='120'", $rs['url']);
$pattern = "/width=\"[0-9]*\"/";
$string = preg_replace($pattern, "width='200'", $string);
echo $string;

we have another alternate for the above …

you can write the above code in one line by using alternation

 
$pattern = '/(width|height)="[0-9]*"/i';
//

you can use single-quotes instead of double-quotes to reduce the need to escape characters like double-quotes and backslashes.

the input was like this…

<object width="425" height="344">
<param name="movie" value="http://www.youtube.com/v/GwQMnpUsj8I&hl=en&fs=1">
</param><param name="allowFullScreen" value="true">
</param><param name="allowscriptaccess" value="always">
</param><embed src=http://www.youtube.com/v/GwQMnpUsj8I&hl=en&fs=1 
type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344">
</embed></object>

and the output will be like this…

<object width="200" height="120">
<param name="movie" value="http://www.youtube.com/v/GwQMnpUsj8I&hl=en&fs=1">
</param><param name="allowFullScreen" value="true">
</param><param name="allowscriptaccess" value="always">
</param><embed src=http://www.youtube.com/v/GwQMnpUsj8I&hl=en&fs=1 
type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="200" height="120">
</embed></object>

there are two width and height attributes which got replaced… one is in the first line and next is for the embed tab inside.

dirname() and __FILE__ to find parent and current folder of a path or php script

PHP No Comments »

__FILE__ is a magic constant along with __LINE__ and some more which i have not yet used.

dirname() is a function which returns the directory name of a path.

as we combine these two we get something interesting… at least for me.

my problem was to find the current directory of the executing php script. i was not comfortable using dirname($_SERVER[‘PHP_SELF’]) because i got only the folder name and not the complete path…

and then i was gazing the pages online to find what could be the alternat… then it is all this __FILE__ and dirname functions which gives the complete parent folder path which i was in need of many times.

to get current director’s full abs path we can use the following
dirname(__FILE__)
and the parent directory full abs path we can use the following
dirname(dirname(__FILE__))
and it can go further…

$dir = str_replace ( “\”,/, dirname ( _FILE_ ) )
// for Windows based systems

another use of __FILE__ is for debugging purpose while using queries.

i have many queries executed for a page and if there was an error at any point then i have to waste time to find at which place it is unless you append some text like this to find the location (mysql_error().”while this query”)…

so i tried using similar to this to get the line number of the error occured.

mysql_query($query) or showError('status.php',mysql_error(),__LINE__,__FILE__);

if an error occured i will set the error in a session in the showError function and then i will redirect to a status page where it displays the error, line number and the filename where the error occured. and then clear the err string session to make it ready for the next error status…

the following urls are good resources for dirname and __FILE__
php.net manual for function dirname

PHP Magic Constants

SERVER variable of DOCUMENT_ROOT in windows hosting

PHP No Comments »

One of my projects was uploaded to a windows hosting and i found server of document root was not working. So i searched and i found the following gimmick of using it in windows hosting.

<?php
if ( ! isset($_SERVER['DOCUMENT_ROOT'] ) )
  $_SERVER['DOCUMENT_ROOT'] = str_replace( '\\', '/', substr(
    $_SERVER['SCRIPT_FILENAME'], 0, 0-strlen($_SERVER['PHP_SELF']) ) );
?>
Entries RSS