Monday, September 27, 2010

How to check upload file extension using JavaScript ?

The following is a simple JavaScript function to check the extension of an uploading file.
It will help to avoid checking the file extension in server, if the JavaScript is enabled in the browser.

We use a form for file uploading. The form is similar as follows.
<form name="a">
<input type="file" name="shw_image" id="shw_image" onchange="validateFileExtension(this.value)"/>
<input type="hidden" name="tmp_img" id="tmp_img" value="" />
</form>
Next using the JavaScript function we can find out the file extension. We are calling this function in the onchange event of the file filed.
The JavaScript function is as follows.
function validateFileExtension(fld)
{

document.getElementById("tmp_img").value= fld;
var ext = fld;
ext = ext.substring(ext.length-3,ext.length);
ext = ext.toLowerCase();
if((ext != 'jpg')&&(ext != 'gif')&&(ext != 'png')&&(ext != 'jpeg'))
{
alert('You selected a .'+ ext + ' file; \n please select a .jpg/.gif/.png/.jpeg image file');
document.frm.product_image.focus();
document.frm.product_image.value="";
document.getElementById("tmp_img").value="";
return false;
}
}
This function alerts a message if we select a file with the extension other than jpg, gif, png and jpeg.

Tuesday, August 17, 2010

PHP Parser to extract Filezilla FTP details

The following is a PHP program to extract FTP usernames and passwords from the filezilla xml file.
First export the filezilla FTP details using the export option in the filezilla
File - > Export

Save this file as 'FileZilla.xml'

Assign the xml file path to the variable and reun the program. It will list the ftp details . Add or change the xml_key variable to get the other details of FTP details.

Source Code
<?php
$xml_file = "FileZilla.xml";
$xml_host_key = "*FILEZILLA3*SERVERS*SERVER*HOST";
$xml_port_key = "*FILEZILLA3*SERVERS*SERVER*PORT";
$xml_user_key = "*FILEZILLA3*SERVERS*SERVER*USER";
$xml_pass_key = "*FILEZILLA3*SERVERS*SERVER*PASS";
$xml_name_key = "*FILEZILLA3*SERVERS*SERVER*NAME";
$story_array = array();
$counter = 0;
class xml_story{
var $host, $port,$user,$pass;
}
function startTag($parser, $data){
global $current_tag;
$current_tag .= "*$data";
}
function endTag($parser, $data){
global $current_tag;
$tag_key = strrpos($current_tag, '*');
$current_tag = substr($current_tag, 0, $tag_key);
}
function contents($parser, $data){
global $current_tag, $xml_host_key, $xml_port_key, $counter, $story_array,$xml_user_key,$xml_pass_key,$xml_name_key;
switch($current_tag){
case $xml_host_key:
$story_array[$counter] = new xml_story();
$story_array[$counter]->host = $data;
break;
case $xml_port_key:

$story_array[$counter]->port = $data;
//$counter++;
break;
case $xml_user_key:

$story_array[$counter]->user = $data;
// $counter++;
break;
case $xml_pass_key:

$story_array[$counter]->pass = $data;
// $counter++;
break;
case $xml_name_key:

$story_array[$counter]->name = $data;
$counter++;
break;

}
}
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startTag", "endTag");
xml_set_character_data_handler($xml_parser, "contents");
$fp = fopen($xml_file, "r") or die("Could not open file");
$data = fread($fp, filesize($xml_file)) or die("Could not read file");
if(!(xml_parse($xml_parser, $data, feof($fp)))){
die("Error on line " . xml_get_current_line_number($xml_parser));
}
xml_parser_free($xml_parser);
fclose($fp);
?>
<html>
<head>
<title>Filezilla Parser</title>
</head>
<body bgcolor="#FFFFFF">
<table width="1001" border="1">
<tr>
<td width="47"><strong>NO</strong></td>
<td width="185"><strong>Name</strong></td>
<td width="229"><strong>Host</strong></td>
<td width="221"><strong>User Name</strong></td>
<td width="125"><strong>Password</strong></td>
<td width="154"><strong>Port</strong></td>
</tr>
<?php
for($x=0;$x<count($story_array);$x++){
?>

<tr>
<td height="38"><?=$x++?></td>
<td><?=$story_array[$x]->name?></td>
<td><?=$story_array[$x]->host?></td>
<td><?=$story_array[$x]->user?></td>
<td><?=$story_array[$x]->pass?></td>
<td><?=$story_array[$x]->port?></td>
</tr>
<?php
}
?>
</table>
</body>
</html>

It will list the FTP host ,FTP username , FTP password and port etc.

Saturday, June 12, 2010

Find out the page loading time using php

If you need to know how long your site takes to load, we can use php script. Using the php microtime() we can find the loading time of a webpage. If the webpage loading time is high we can check the page using this code that where it takes too long time to load.

insert the following code at the top of the PHP page

<?php
$starttime = microtime();
$startarray = explode(" ", $starttime);
$starttime = $startarray[1] + $startarray[0];
?>

also put the following code at the bottom of the page

<?php
$endtime = microtime();
$endarray = explode(" ", $endtime);
$endtime = $endarray[1] + $endarray[0];
$totaltime = $endtime - $starttime;
$totaltime = round($totaltime,10);
echo "Time To Load: ".$totaltime;
?>

Now when you access your webpage it will show the time taken to load.

For example :

Time To Load: 0.015601

Saturday, May 8, 2010

php_error_log

Error log is the file contains the listing of errors that occured on our PHP server.By default, PHP error logging is turned off. If you need to have a PHP error log, your can turn PHP error logging on, and they will write to your /logs/php_error_log. Disk space used by the php_error_log IS COUNTED toward your total disk usage, so you should leave php error logging turned off if you do not need it.
By default your php.ini file contains:
        log_errors = Off
You cans Change this value to
        log_errors = On
It will write the error details in to the errorlog file located in /logs/php_error_log.

For all accounts created after August 31, 2002, php_error_log is turned Off by default.

Thursday, April 15, 2010

What is Cookie?

Cookies are pieces of data created when you visit a website, and contain a unique, anonymous number. They are stored in the cookie directory of your hard drive, and do not expire at the end of your session.

Cookies let us know when you return to our website and what pages or services you use when you're there. Our cookies aren't used to store or collect any personal information. It only lets us know that someone with your unique cookie has returned to our website.

By using cookies we will be able to see how our website is being used. This means we'll be able to identify the most popular areas of our website and make it easier for you to access them. Cookies help us to be more efficient as we can learn what information is important to our customers and what isn't.

How cookies work


A cookie is nothing but a small text file that's stored in your browser.That means this file is stored in the user machine.It contains some data:

1. A name-value pair containing the actual data
2. An expiry date after which it is no longer valid
3. The domain and path of the server it should be sent to

As soon as you request a page from a server to which a cookie should be sent, the cookie is added to the HTTP header. Server side programs can then read out the information and decide that you have the right to view the page you requested or that you want your links to be yellow on a green background.

So every time we visit the site the cookie comes from, information about you is available. This is very nice sometimes, at other times it may somewhat endanger your privacy. Fortunately more and more browsers give you the opportunity to manage your cookies (deleting the one from the big ad site, for example).

Cookies can be read by JavaScript too. They're mostly used for storing user preferences.

name-value


Each cookie has a name-value pair that contains the actual information. The name of the cookie is for your benefit, you will search for this name when reading out the cookie information.

If you want to read out the cookie you search for the name and see what value is attached to it. Read out this value. Of course you yourself have to decide which value(s) the cookie can have and to write the scripts Expiry date

Each cookie has an expiry date after which it is trashed. If you don't specify the expiry date the cookie is trashed when you close the browser. This expiry date should be in UTC (Greenwich) time in the format created by the Date.toGMTString() method Domain and path

Each cookie also has a domain and a path. The domain tells the browser to which domain the cookie should be sent. If you don't specify it, it becomes the domain of the page that sets the cookie, in the case of this page www.quirksmode.org. Please note that the purpose of the domain is to allow cookies to cross sub-domains. My cookie will not be read by search.quirksmode.org because its domain is www.quirksmode.org . When I set the domain to quirksmode.org, the search sub-domain may also read the cookie. I cannot set the cookie domain to a domain I'm not in, I cannot make the domain www.microsoft.com . Only quirksmode.org is allowed, in this case.

The path gives you the chance to specify a directory where the cookie is active. So if you want the cookie to be only sent to pages in the directory cgi-bin, set the path to /cgi-bin. Usually the path is set to /, which means the cookie is valid throughout the entire domain. This script does so, so the cookies you can set on this page will be sent to any page in the www.quirksmode.org domain (though only this page has a script that searches for the cookies and does something with them).

document.cookie


Cookies can be created, read and erased by JavaScript. They are accessible through the property document.cookie. Though you can treat document.cookie as if it's a string, it isn't really, and you have only access to the name-value pairs.

If I want to set a cookie for this domain with a name-value pair 'ppkcookie1=testcookie' that expires in seven days from the moment I write this sentence, I do
document.cookie = 'ppkcookie1=testcookie; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=/'
1. First the name-value pair ('ppkcookie1=testcookie')
2. then a semicolon and a space
3. then the expiry date in the correct format
('expires=Thu, 2 Aug 2001 20:47:11 UTC')
4. again a semicolon and a space
5. then the path (path=/)
This is a very strict syntax, don't change it! (Of course the script manages these dirty bits for you)

Also, even though it looks like I'm writing this whole string to the string document.cookie, as soon as I read it out again I only see the name-value pair:

We are giving some examples about the cookies operation.

createCookie


function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}

When calling createCookie() you have to give it three bits of information: the name and value of the cookie and the number of days it is to remain active. In this case the name-value pair should become ppkcookie=testcookie and it should be active for 7 days.

readCookie


function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; }


To read out a cookie, call this function and pass the name of the cookie. Put the name in a variable. First check if this variable has a value (if the cookie does not exist the variable becomes null, which might upset the rest of your function), then do whatever is necessary.

eraseCookie


Erasing is extremely simple.

function eraseCookie(name) {
createCookie(name,"",-1);
}
The browser, seeing that the expiry date has passed, immediately removes the cookie.

Friday, February 19, 2010

Add read more link without cutting the word

Many times we have the need to display a short description about web page content. If the string is large and we would like to display only few words and put a link like 'more info', then we have to split the string carefully. We are using substr function to display such content. The problem with substr is , the substr function takes the string up to the limit even the limit is a character in the word. We can avoid such problems by modifying the substr function.

Here the sample code
<?php
$strDes="its a sample text. ";
echo substr($strDes,0,strrpos(substr($strDes,0,64),' '))
?>
... read more
It shows a description without splitting any word.

Tuesday, January 12, 2010

How To Find File Extension Using PHP?

Find the file extension using php

If you wanted to rename a file upload you would still need to keep the extension. We can use these functions to find out the file extensions. Once found it can be appended to the end of a random number or a timestamp (or other naming system you choose) to use as the file name. There are several ways determine a file extension using PHP.These methods will return any file extension no matter how long or short it is.

First Method


First is using the combination of strrpos() and substr() function like this :For example, if $fileName is sample.jpg then strrpos($fileName, '.') will return the last location a dot character in $fileName. So substr($fileName, strrpos($fileName, '.') + 1) equals to substr($fileName, 16) which return 'jpg'.
<?php
echo "<br> First method</br>";
$fileName = "sample.php";
$ext = substr($fileName, strrpos($fileName, '.') + 1);
echo $ext;
?>

Second Method


The second is using strrchr() and substr() :

$ext = substr(strrchr($fileName, '.'), 1);

<?
echo "<br>Second method</br>";
echo $ext = substr(strrchr($fileName, '.'), 1);
?>

strrchr($fileName) returns '.jpg' so substr(strrchr($fileName, '.'), 1) equals to substr('.jpg', 1) which returns 'jpg'

Third Method

Using the pathinfo function we can get the file path details. It returns the extension also.
<?
echo "<br>Third method</br>";
// get the path info
$fileinfo = pathinfo($fileName);
// will show the extension
echo $fileinfo['extension'];
?>

Fourth Method

<?
echo "<br>Fourth method</br>";
$filename = strtolower($fileName) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
echo $exts;
?>
Basically what the code is doing is first using strtolower to change the extension (and the whole file name) into lower case, just to keep it clean. Next we are splitting the filename into an array using split. By splitting it at the [.] the extension will be the last element in the array, which we then return.

Fifth Method

<?
echo "<br>Fifth method</br>";
$fileDet = explode('.', $filename);
echo end($fileDet);
?>