Monday, May 9, 2011

Number format in javascript and php

In PHP, number_format() is a built-in function for formatting of an integer or float number with grouped thousands. But, in javascript, there is no such function for formatting of a number. We need to define write own custom function in javascript which will work exactly like number_format() function in PHP.

PHP
string number_format ( float $number [, int $decimals = 0 ] )
string number_format (float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',')
Example:
<?php
$number=10527;  echo number_format($number);
// output will be 10,527
$number=1052.87;  echo number_format($number); 
//output will be 1,053
$number=105246.87;  echo number_format($number,3,'.','\''); 
//output will be 105'246.870 . Here, I have specified thousand separator as '. Default thousand separator is ,
 ?>
Note: in this function, 2nd, 3rd and 4th parameter are optional. But, if u supply 3rd parameter, 4th parameter becomes mandatory. Otherwise, it can generate warning message - Wrong parameter count.

Javascript:
<script language="javascript">
function number_format(a, b, c, d) {
 a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
 e = a + '';
 f = e.split('.');
 if (!f[0]) {
 f[0] = '0';
 }
 if (!f[1]) {
 f[1] = '';
 }
 if (f[1].length < b) {
 g = f[1];
 for (i=f[1].length + 1; i <= b; i++) {
 g += '0';
 }
 f[1] = g;
 }
 if(d != '' && f[0].length > 3) {
 h = f[0];
 f[0] = '';
 for(j = 3; j < h.length; j+=3) {
 i = h.slice(h.length - j, h.length - j + 3);
 f[0] = d + i + f[0] + '';
 }
 j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
 f[0] = j + f[0];
 }
 c = (b <= 0) ? '' : c;
 return f[0] + c + f[1];
}

Example:
 var number=105246.87;
document.write(number_format(number,1,'.','\''));
// output will be 105'246.9
</script>

Please do not hesitate to give your valuable suggestions.

Wednesday, April 20, 2011

How to use PHP code in HTML file

Many places, we feel that we can give better result if it would possible to use PHP code instead of javascript code in HTML page. Below is the way to use php code in the html page.

Html file name is "abc.html" :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Use PHP in HTML file</title>
</head>

<body> 
<!-- We can also pass the parameters to PHP as query string -->
<script src="xyz.php?uid=10&pid=string value"></script>
</body>
</html>
PHP file name is "xyz.php":
<?php
header("application/javascript");
$uid=$_GET['uid'];$pid=$_GET['pid'];
$ip=$_SERVER['REMOTE_ADDR'];
$mytime=date('m-d-Y H:i:s');
echo "document.write('Your IP is <b>$ip</b><br />Server date and time is <b>$mytime</b>');";
echo "document.write('<br />$pid');";
?>

Output :
Your IP is 127.0.0.1
Server date and time is 04-27-2011 01:01:44
string value

 Please feel free to provide your valuable feedback.

Tuesday, April 19, 2011

Enhanced Extravote plugin in joomla

Extravote is a very popular and useful 5 star rating plugin to rate an article. So, if a page contains multiple content items, it will display mulitple times on a page and works great. We can also use this plugin in third party extensions. But, there is a major issue with this plugin which has not been considered by developers.

About the issue : Just click on a star to give your rating for an article. Your vote will be counted and system will display message "Thanks for voting". If you try to vote again, system will display message "You have already voted". But, with this message, total vote will be decreased by 1. It will be corrected only when you refresh the page. If you are the first one to vote an article, you will notice that, after repeating the vote second time, you will get the message "You have already voted" and total vote become 0. I have consider the issue and debug the code. Since, this plugin is using AJAX for whole functionality, value passed to the javascript function don't change. Finally, I have change the way of implementation and it woks without any issue.
I have not only fix this issue, also enhanced its functionality.

Monday, April 4, 2011

Call plugin in third party extension of joomla

global $mainframe;
        include_once('components/com_content/models/article.php');
        include_once('components/com_content/helpers/query.php');
        $dispatcher =& JDispatcher::getInstance();
        $articleObject=new ContentModelArticle();
        $id= JRequest::getVar('content_id');
        $limitstart    = JRequest::getVar('limitstart', 0, '', 'int');
        $articleObject->setId($id);
        $item=new JObject;
        $item->text = $articleObject->getArticle(); 
        $item->params = clone($mainframe->getParams('com_content'));
        JPluginHelper::importPlugin('content');
        $results=$dispatcher->trigger('onBeforeDisplayContent', array (& $item->text, & $item->params, 0));
        echo $results[0];

Saturday, April 2, 2011

FFMPEG - a boon from open source community

FFMPEG an open source software is a product of Google summer of code. It is very useful in the manipulation of video, audio and image. Benefits of FFMPEG are below:
  • Extract n number of thumbnails from video and vice-versa
  • Convert types of video and audio
  • Extract audio and video for specific duration from audio/video
  • Extract audio from video
  • Mix audio and video
  • Extract thumbnails from an image
It is very useful for web applications because in many cases, we need to render light weight images and videos.
Click here to download ffmpeg software
Click here to download ffmpeg help and list of commands
Click here to download ffmpeg FAQ
Click here to download ffmpeg commands with examples
Click here to download supported  file formats and codecs for Audio and video files 


    Wednesday, March 23, 2011

    Forcing to download a zip file in all browsers

    Friends,
    Have you ever gotten a chance to force the browser for downloading a zip file? Hopefully yes. You will not get any issue unless and untill it contains multiple zip files i.e. nested zip files. Behavior is also different for IE and firefox. Below is the code to download a zip file(may be single level or nested)

    <?php
     ob_clean();
     $yourfile="rnd_source.zip"; // file which is stored on the server
     $dfile="rnd.zip";  // name of the file which will be downloaded
     $fp = @fopen($yourfile, 'rb');
     if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE"))
     {
            header('Content-Type: "application/x-zip-compressed"');
            header('Content-Disposition: attachment; filename="'.$dfile.'"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header("Content-Transfer-Encoding: binary");
            header('Pragma: public');
            header("Content-Length: ".filesize($yourfile));
    }
    else
    {
            header('Content-Type: "application/x-zip-compressed"');
            header('Content-Disposition: attachment; filename="'.$dfile.'"');
            header("Content-Transfer-Encoding: binary");
            header('Expires: 0');
            header("Content-Length: ".filesize($yourfile));
    }

    fpassthru($fp);
    fclose($fp);
    ?>
    Provide your valuable comments please.............if you get any issue or wanna anything to share.

    Friday, January 28, 2011

    how to configure Phpmyadmin and use mysql on terminal in UBUNTU/LINUX

    To configure phpmyadmin, use synaptic Package manager.

    To run mysql on terminal, simply go to terminal and write command as below:

    aanand@aanand-desktop:~$ mysql --user=root --password=root
    Here, you can user the user and password as you have supplied during installation.

    Now, you will see messages as below:


    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 26
    Server version: 5.0.51a-3ubuntu5.7 (Ubuntu)

    Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

    mysql>

    Your system is ready to run mysql commands and execute queries.
    To test, you can write commands like
    mysql>show databases;
    mysql>use test;
    mysql>show tables;
    To get the help, use help command as below:
    mysql>\h;
    mysql>\help;

    Sunday, January 16, 2011

    The best way to handle date and time in PHP and MySQL

    Usually we use date() function with their different formats. When we have to store the date in table, we convert the date in yyyy-mm-dd format if data-type of column is Date or yyyy-mm-dd HH:mm:ss format if data-type of column is datetime . In the same way, before use of these values, after fetching, need to convert these according to our required format. But, doing all the above process, we have to use explode() and list() function many times. But, using strtotime() is the best way to handle date in different formats.
    strtotime() is a function that converts a date which is in string format into unix timestamp. Please select the data-type as timestamp instead date or datetime when define table structure.
    At the time of saving, we have to just pass the date value which is in string format as argument of strtotime() function and get  the timestamp as output of this function. Now, we can save this timestamp in the table.
    At the time of using this value, after fetching pass this timestamp value in the date() function as second parameter. Format will be as below:
    <?php 
    //Before saving the value in table,
    $timestamp_field_value=strtotime('2010-12-23 12:55:32');
    //After fetching the value from table,
    echo date('Y-m-d',$timestamp_field_value);
    ?>

    Sunday, January 9, 2011

    How do we upload large files on server using PHP

    Though PHP presents a very versatile and user friendly interface for handling file uploads, the default installation is not geared for working with files in excess of 2 Mega Bytes. This article is an aid to configuring PHP for handling such large file transfers.
    Windows Apache Web Server Configuration: Installation Guide for Apache 2.0.x Web Server - WAMP
    The php.ini file contains all the configuration settings for your installation. Sometimes these setting might be overridden by directives in apache .htaccess files or even with in the scripts themselves but for the moment let's just concentrate on the ini file.
    This file contains the following settings that we need to modify
    • file_uploads [ default is on]
    • upload_max_filesize [default is 2mb, 4 times more than size of file to be uploaded]
    • max_input_time [default is 60, increase it to 300]
    • memory_limit [default is 128M, increase it to 256M]
    • max_execution_time [default is 30, increase it to  500]
    • post_max_size [default is 8MB, it should be greater than upload_max_filesize]
    The first one is fairly obvious if you set this off, uploading is disabled for your installation. We will cover the rest of the configuration settings in detail below.
    upload_max_filesize and post_max_size
    Files are usually POSTed to the webserver in a format known as 'multipart/form-data'. The post_max_size sets the upper limit on the amount of data that a script can accept in this manner. Ideally this value should be larger than the value that you set for upload_max_filesize.
    It's important to realize that upload_max_filesize is the sum of the sizes of all the files that you are uploading. post_max_size is the upload_max_filesize plus the sum of the lengths of all the other fields in the form plus any mime headers that the encoder might include. Since these fields are typically small you can often approximate the upload max size to the post max size.
    According to the PHP documentation you can set a MAX_UPLOAD_LIMIT in your HTML form to suggest a limit to the browser. Our understanding is that browsers totally ignore this directive and the only solution that can impose such a client side restriction is Rad Upload Applet
    memory_limit
    When the PHP engine is handling an incoming POST it needs to keep some of the incoming data in memory. This directive has any effect only if you have used the --enable-memory-limit option at configuration time. Setting too high a value can be very dangerous because if several uploads are being handled concurrently all available memory will be used up and other unrelated scripts that consume a lot of memory might effect the whole server as well.
    max_execution_time and max_input_time
    These settings define the maximum life time of the script and the time that the script should spend in accepting input. If several mega bytes of data are being transfered max_input_time should be reasonably high. You can override the setting in the ini file for max_input_time by calling the set_time_limit() function in your scripts.
    Special Notes:
    Apache Settings
    The apache webserver has a LimitRequestBody configuration directive that restricts the size of all POST data regardless of the web scripting language in use. Some RPM installations sets limit request body to 512Kb. You will need to change this to a larger value or remove the entry altogether.
    Other Options
    If you expect to handle a large number of concurrent file transfers on your website consider using a perl or java server side component. PHP happens to be our favorite web programming language as well but perl is just slightly ahead when it comes to file handling.
    Most installations of perl as an apache module can accept up to 32 megabytes out of the box. Compare this against the 2MB default for PHP. The downside is that perl coding takes just a bit more effort than PHP but it's worth it.
    Installing & Configuring Web Servers Using Apache

    Sunday, January 2, 2011

    How to configure PHP on IIS server


    1. Install IIS (Required Windows CD to install IIS server).
    2. Go to Control Panel > add/Remove programs windows components > select IIS
    3. Go to Start > control panel > performance & maintenance > Internet Information Services > websites > default websites ---right click--->Select stop
    4. Download PHP from PHP website
    5. Extract the downloaded zip folder (for example php5)and then  see the directory structure.
    6. Copy php5\dev\php5ts.dll  to C:\windows\system32\
    7. Copy php5\php.int-dist to c:\windows\ and rename it as php.ini
    8. Copy all files from php5\ext\ to c:\windows\sysem32\ or change the path variable to php5\ext\
    9. Open the file php.ini from c:\windows\ and make  changes like  extension-dir=c:\php5\ext
    10. Remove the semicolon which is prefixed from the line extensions=php_gd2.dll
    11. As point 9, we can enable the extensions as per our requirements. Above extensions will enable GD library.
    12. Save the modified php.ini file and close it.
    13. Go to Start > control Panel > performance & maintenance > administrative tool  > IIS > website > Default website ---right click---> properties ---click--->SAPI filter tab ---click--->Add button ----create a new filter [filter name PHP] [Extension: c:\php5\php5isabpi.dll] > OK
    14. Home directory tab > configuration button ---click on add button > Executable ---click on Browse button to select the file (c:\php5\php5isapi.dll)
    15. Provide .php as extension > ok >ok
    16. Go to Start > control Panel > performance & maintenance > administrative tool  > IIS > website > default website ---right click--->start
    Beginning PHP 5.3 (Wrox Programmer to Programmer)

    Q. What is Path environment variable?
    A: A path environment variable contains a list of directories paths in which windows will look for things. To set the path variable,
    Go to start > control panel > system > advanced > environment variables
    Add your new path and click on save

      Important queries based formulas to watch performance of a MySQL based application

      (1) Session Vs global status variables value select G.variable_name,G.variable_value GlobalValue,S.variable_value SessionValue from (selec...