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);
?>

Saturday, December 12, 2009

How to parse XML data using PHP

Parse XML data using PHP

XML stands for eXtensible Markup Language and is used primarily for data storage and organization. It is useful for many things but the main thing about it is that there are no predefined tags.If we want to parse an XML data to use, we need to convert that data for PHP use. The following is an example for XML parsing using PHP

A few more rules about XML and we will be on our way to our PHP code. XML documents must be well-formed. This means that there can be only one root element (the top most element), all child elements must be nested properly <p>foo <b>bar</b></p> not <p>foo <b>bar</p></b>, and all elements must have end tags.In XML, an element is also referred to as a node

A sample xml code could look like this:

<?xml version="1.0"?>
<datas>
<sample 1 />
<sample 2 />
<sample 3 />

</datas>

<?xml version="1.0"?> must be the first tag in a XML file. It is called the xml declaration and identifies the file as a XML file to a parser.

As we can see the code is easy to read and understand. We can clearly see every tag and easily read them in plain English, or whatever language we are most comfortable with.Each XML file can have it's own DTD or structure. The PHP file using the XML parser must be tailored to one particular structure or DTD

Step 1:

The $xmlData is a variable contains the XML data.If the xml data is in the XML file then read the file and store that datas in a variable.We can use file operations to get the value from the XML file .
$xmlData ='<?xml version="1.0"?>
<sections>
<section name="profile">
<subsection name="name" value="Sample name"/>
<subsection name="address" value="sample address" />
<subsection name="email" value="sample@email.com" />
</section>
<section name="personel">
<subsection name="phone" value="123456789" />
<subsection name="age" value="25" />
<subsection name="job" value="Software Professional" />
</section>
</sections>';

Step 2:

After that we can parse the XML data. For this we can use the following code.The following code will parse the XML data and create a two dimensional array of data. This function parse each tag and stores each tag value in the array.

To view the array content

/*
This function receives xml data as input and returns an array as output.
*/
function xml2array($contents, $get_attributes=1)
{
if(!$contents) return array();

if(!function_exists('xml_parser_create')) {
return array();
}
//Get the XML parser of PHP - PHP must have this module for the parser to work
$parser = xml_parser_create();
xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 );
xml_parser_set_option( $parser, XML_OPTION_SKIP_WHITE, 1 );
xml_parse_into_struct( $parser, $contents, $xml_values );
xml_parser_free( $parser );
if(!$xml_values) return;//Hmm...
//Initializations
$xml_array = array();
$parents = array();
$opened_tags = array();
$arr = array();
$current = &$xml_array;
//Go through the tags.
foreach($xml_values as $data) {
unset($attributes,$value);//Remove existing values, or there will be trouble
//This command will extract these variables into the foreach scope
// tag(string), type(string), level(int), attributes(array).
extract($data);//We could use the array by itself, but this cooler.
$result = '';
if($get_attributes) {//The second argument of the function decides this.
$result = array();
if(isset($value)) $result['value'] = $value;
//Set the attributes too.
if(isset($attributes)) {
foreach($attributes as $attr => $val) {
if($get_attributes == 1) $result['attr'][$attr] = $val;
//Set all the attributes in a array called 'attr'
/** :TODO: should we change the key name to '_attr'?
Someone may use the tagname 'attr'. Same goes for 'value' too */
}
}
} elseif(isset($value)) {
$result = $value;
}
//See tag status and do the needed.
if($type == "open") {//The starting of the tag ''
$parent[$level-1] = &$current;
if(!is_array($current) or (!in_array($tag, array_keys($current)))) {
//Insert New tag
$current[$tag] = $result;
$current = &$current[$tag];
} else { //There was another element with the same tag name
if(isset($current[$tag][0])) {
array_push($current[$tag], $result);
} else {
$current[$tag] = array($current[$tag],$result);
}
$last = count($current[$tag]) - 1;
$current = &$current[$tag][$last];
}
} elseif($type == "complete") { //Tags that ends in 1 line ''
//See if the key is already taken.
if(!isset($current[$tag])) { //New Key
$current[$tag] = $result;
} else { //If taken, put all things inside a list(array)
if((is_array($current[$tag]) and $get_attributes == 0)
//If it is already an array...
or (isset($current[$tag][0]) and is_array($current[$tag][0]) and $get_attributes == 1)) {
array_push($current[$tag],$result); // ...push the new element into that array.
} else { //If it is not an array...
$current[$tag] = array($current[$tag],$result);
//...Make it an array using using the existing value and the new value
}
}
} elseif($type == 'close') { //End of tag '
'
$current = &$parent[$level-1];
}
}
return($xml_array);
}

Working:
The xml_parser_set_option() function sets options in an XML parser.This function returns TRUE on success, or FALSE on failure.
eg: xml_parser_set_option(parser,option,value) ;
This function returns FALSE if parser does not refer to a valid parser, or if the option could not be set. Else the option is set and TRUE is returned.

There are three types of tags in the above example,sections,section and subsection. 'Sections' is the primary tag for the XML data. 'section' is the tag,with a reference name.'subsection' has the name and value parameters.The above function parse each tag and subtag and store the tag values in the array.

Step 3 :

After execuitng the above function, it returns all the wanted and unwanted datas.So we have to filter the datas. We are using the following the function to filter the datas.
$result = xml2array($xmlData, $get_attributes=1);
/*
The array '$result' contains all parsed datas. So we have to refined the datas
as our need. For that purpose we will iterate the '$result' array. We are using
seperate iteration for each section.
*/
$datalength = sizeof($result['sections']['section'][0]['subsection']);
$ary_profile = array();
for($x = 0;$x
The data from the XML data is now held in $result and can be accessed using a standard PHP loop.

The following is the output for the above function

Final Output
Array (
[0] => Sample name

[1] => sample address

[2] => sample@email.com

)
Array (
[0] => 123456789

[1] => 25

[2] => Software Professional

)

Sunday, November 22, 2009

Finding Database Size using php & mysql

The dbsize of mysql can be retrieved using the query "show table status'.

Follow the steps to find the DB size
Step 1:
Getting connection with the databse
<?php

$db = mysql_connect("hostname", "username","password"); //getting the mysql db connection by passing correct hostname,username and passowrd
mysql_select_db("dbname",$db); //there we pass the db name for which we want the size to be calculated. This is like calling "use dbanme";
?>
Step 2:
The dbsize is the total of Index_length and Data_lenth columns of all the tables present in the database selected.
We will find the size with the below function


<?php
{
$sql = "SHOW TABLE STATUS";
$result = mysql_query($sql); // This is the result of executing the query
while($row = mysql_fetch_array($result))// Here we are to add the columns 'Index_length' and 'Data_length' of each row
{
$total = $row['Data_length']+$row['Index_length'];
}
echo($total); // here we print the file size in bytes
}
?>

Wednesday, September 2, 2009

SEO Don’ts

Bad Techniques:

Bad search engine optimization techniques can get you blacklisted from a search engine. Some techniques that are considered spam are cloaking, invisible text, tiny text, identical pages, doorway pages, refresh tags, link farms, filling comment tags with keyword phrases only, keyword phrases in the author tag, keyword density to high, mirror pages and mirror sites.
While these techniques might work to give you a higher ranking for short time in the long run they will hurt you.
Google has a good article on Google information for webmasters that is very imformative if you are considering Getting a SEO Company to so work on your website.

A Few SEO Don’ts — Flash and Splash


Along with any list of Do’s come the Don’ts. As far as SEO is concerned, two of these items are splash pages (often consisting of a flash animation) and all flash web sites.

Yes, flash is pretty! Full flash web sites can actually be amazing to look at — their own bit of interactive artwork. But unfortunately the search engines don’t get along well with Flash. Although there is talk of possible advancement in this area, for the most part the search engines cannot read Flash.

All that great content that you wrote for your site will not be seen by the search engines if it’s embedded into a Flash web site. As far as the search engines are concerned, your all flash web site might as well be invisible. And if the search engines can’t see your site content, a good chunk of potential customers will miss out on what you have to offer, too.

Equally as “pointless” are splash pages. Once very popular, the splash page should no longer be an important feature of any site. While splash pages used to serve as an introduction into a web site (often with a flash animation), it is no longer seen as helpful, and often times might actually annoy visitors.

For one — it’s an extra click to get into your content. Worse is when you don’t give a “skip intro” option or set of links into your main site content — because you’re essentially forcing your visitors to sit through the full animation. If you’re lucky, this will only annoy them… if not — they’ll just leave without giving your main web site a shot. And without an html link pointing into your site, the search engines have no way to continue either (unless you made use of a sitemap.xml file — but still…)

A good alternative to both issues is to make use of a flash header. There’s no problem to include a flash animation at the top of your main site, or as a feature within the content area, etc. Because this is an addition to your web site, as opposed to a full separate element.

More SEO tips - The do’s and do not’s

  • Do not target common keywords like “shop” or “design”
  • Do not copy any content from other pages
  • Add new content from time to time to keep your site on top
  • Monitor and analyze your keywords performance and study your competitor
  • Try to avoid flash and scripts to keep your code clean
  • Use not more than 5 to 7 words for your meta keywords
  • Use unique and relevant meta keywords for every single page
  • Create landing pages, optimized for specific keywords
  • Don’t spam your meta tags with keywords, focus on your main keywords
  • Provide unique and useful content. Seriously, this is crucial!
  • Use text for your navigation and not images
  • Integrate a blog for fresh content and social marketing possibilities
  • Once again, take your time researching the right keywords for your site
Don’t wait too long to implement SEO. Whether you’re launching a new Web site or upgrading your current site, SEO considerations should be part of the discussion from day one.

Don’t make your web site uncrawlable. This can result from an incorrect robots.txt file, having session IDs or too many variables in your URLs, using a convoluted navigation menu that spiders can’t (or won’t) follow, or developing an all-Flash, all-graphic, or all-AJAX site.

Don’t target overly general keywords. A real estate agency in Wichita has no shot at ranking for the phrase “real estate;” a lawyer in Fresno has no shot at ranking for the word “lawyer.” Optimize for relevant, specific keywords that will bring targeted traffic.

Don’t stuff keywords in your meta tags, image alt tags, etc. That is so 1996-97. Today, it’s called spam.

Don’t stuff keywords in your page footer with lightly-colored or hidden text. That is so 1998-99. Today, it’s also called spam.

Don’t have the same title element on every page. Variety is the spice of life and, combined with relevance, is a pre-requisite to avoiding duplicate content issues and Google’s supplemental index.