Sunday, December 19, 2010

session using php - sample code

A session is similar as a variable that resides in the server. The sesion variable is a global variable that can be used in all pages in a website. We can hold the userids, user email , privilages etc in the session.

The following is a sample code for session hanling. We can use an object oriented programming to handle the session.

Step 1 :
The SessionManager class is the session handler file. It contains the functions to create session, to store content to session, view the session content, delete session etc.

<?php
class SessionManager
{
public function __construct()
{

}

public function getSession($name = 'admin')
{
return $this->hasSession() ? ($_SESSION[$name]) : null;
}

public function hasSession($name = 'admin')
{
return (isset($_SESSION[$name]));
}

public function createSession($content,$name = 'admin', $override = false)
{
if(!$this->hasSession() || ($this->hasSession() && $override) )
{
$_SESSION[$name] = $content;
session_write_close();
return true;
}
else
{
return false;
}
}

public function destroySession ($name = 'admin')
{
$_SESSION[$name] = null;
unset($_SESSION[$name]);

return true;
}
}
?>
The createSession function creates the session . If we pass the session name it will create a session with the passing name, otherwise it will create session with tha name as 'admin'.
The 'hasSession' function checks whether the session is existing or not. It will return true, if the session exists.The 'getSession' function returns the informations stored in the session.

The 'destroySession' function destroys the session details.

Step 2:
Create an object for the SessionManager. Here we are using conditions to display how these functions are working.


<?php
session_start();
include_once 'SessionManager.class.php';
$sess = new SessionManager();
extract($_GET);
if($type==1)
{
$advalue = array('adid'=>1,'adname'=>'main admin','privilage'=>'super','lastlogin'=> time());
$sess->createSession($advalue);
}
else if($type==2)
{
echo "<pre>";
print_r($sess->getSession());
echo "</pre>";
}
else if($type==3)
{
$sess->destroySession();
}
?>
<a href="?type=1"> Create Session </a> <br>
<a href="?type=2">View Session</a> <br>
<a href="?type=3"> Delete Session </a> <br>


Here we are storing an array in the session.

Wednesday, November 24, 2010

Creating an RSS feed with PHP and MySQL

What is RSS feed ?

RSS (most commonly expanded as Really Simple Syndication) is a family of web feed formats used to publish frequently updated works—such as blog entries, news headlines, audio, and video—in a standardized format. An RSS document (which is called a "feed", "web feed", or "channel") includes full or summarized text, plus metadata such as publishing dates and authorship. Web feeds benefit publishers by letting them syndicate content automatically. They benefit readers who want to subscribe to timely updates from favored websites or to aggregate feeds from many sites into one place. RSS feeds can be read using software called an "RSS reader", "feed reader", or "aggregator", which can be web-based, desktop-based, or mobile-device-based.
http://en.wikipedia.org/wiki/RSS_feed

RSS is a technology that is being used by millions of web users around the world to keep track of their favorite websites.
Using RSS feed we can share our website content with the rest of the Internet.

The RSS format is based on XML that is built using standardised tags. Following is an example of RSS document.
<rss version="2.0">
<channel>
<title>RSS Feed</title>
<description>RSS Feed</description>
<link>http://mywebsite.com</link>
<lastBuildDate>Wed, 24 Nov 2010 09:47:31 +0100</lastBuildDate>
<language>en-us</language>
<copyright>Copyright (C) 2010 mywebsite.com</copyright>

<item>
<title>Sample title one</title>
<link>http://mywebsite.com/news1.html</link>
<description>This is the description of the smaple title one</description>
<pubDate>Wed, 10 Nov 2010 11:04:12 +0100</pubDate>
</item>
<item>
<title>Sample title two</title>
<link>http://mywebsite.com/news2.html</link>
<description>This is the description of the smaple title two</description>
<pubDate>Wed, 10 Nov 2010 11:03:24 +0100</pubDate>
</item>
<item>
<title>Sample title three</title>
<link>http://mywebsite.com/news3.html</link>
<description>This is the description of the smaple title three</description>
<pubDate>Wed, 10 Nov 2010 11:01:53 +0100</pubDate>
</item>
</channel>
</rss>

We can generate an RSS feed similar as the above sample using PHP and MySQL.

In this example we are listing the latest articles from the database are feed. For that we need a database table . If not not created, we can create a table using the following code..

CREATE TABLE `articles` (
`id` int(11) unsigned NOT NULL auto_increment,
`title` varchar(255) NOT NULL default '',
`link` varchar(255) NOT NULL default '',
`introtext` mediumtext NOT NULL,
`created` datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

RSS feeds are using XML tags. So we are going to generate the XML tags using PHP.

Step 1 : Creating the header

header("Content-Type: application/rss+xml; charset=ISO-8859-1");

The first step is that , we need to tell PHP that what type of data we would like to output. In the header function we are specify that the content type is " application/rss+xml ". This will output a XML formated data into the browser.

Step 2 : Setup a Database connecction

Create a database connection to fetch the datas from the database.

DEFINE ('DB_USER', 'dbusername');
DEFINE ('DB_PASSWORD', 'dbpassword');
DEFINE ('DB_HOST', 'dbroot');
DEFINE ('DB_NAME', 'dbname');

$connection = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('Could not connect to database');
mysql_select_db(DB_NAME) or die ('Error.. Could not connecct to database');
$query = "SELECT * FROM articles ORDER BY id DESC";
$result = mysql_query($query) or die ("Error.. Could not execute query");

Step 3 : Add RSS Feed Information

Next add the information about our RSS feed such as the title of it, the description, and a link to the the site.
Also add the xml version, rss version etc.

$rssfeed = '<?xml version="1.0" encoding="UTF-8"?>';
$rssfeed .= '<rss version="2.0">';
$rssfeed .= '<channel>';
$rssfeed .= '<title>RSS Feed</title>';
$rssfeed .= '<description>RSS Feed</description>';
$rssfeed .= '<link>http://mywebsite.com</link>';
$rssfeed .= '<lastBuildDate>Wed, 24 Nov 2010 09:47:31 +0100</lastBuildDate>';
$rssfeed .= '<language>en-us</language>';
$rssfeed .= '<copyright>Copyright (C) 2010 mywebsite.com</copyright>';
Step 4 : Adding RSS Items

Next, we need to extract our data by looping through our MySQL database to create the <item> tags.

while($row = mysql_fetch_array($result))
{
extract($row);
$rssfeed .= '<item>';
$rssfeed .= '<title>' . $title . '</title>';
$rssfeed .= '<link>http://mywebsite.com/news'.$id.'.html</link>';
$rssfeed .= '<description>[CDATA[' .$introtext . ']]</description>';
$rssfeed .= '<pubDate>' . $created . '</pubDate>';
$rssfeed .= '</item>';
}

Make sure you escape any characters that might cause your XML to invalidate, these characters include <, >, & - I like to enclose any content that may contain HTML inside a CDATA section.

Step 5: Close Channel, RSS tags and output the rssfeed.

$rssfeed .= '</channel>';
$rssfeed .= '</rss>';

echo $rssfeed;


Step 6: Validate your feed

Validate your feed using FeedValidator.org.


Full Source Code:
<?php
header("Content-Type: application/rss+xml; charset=ISO-8859-1");
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', '');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'fourjmktg9908_iapc');
$connection = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('Could not connect to database');
mysql_select_db(DB_NAME) or die ('Error.. Could not connecct to database');
$query = "SELECT * FROM jos_content ORDER BY id DESC";
$result = mysql_query($query) or die ("Error.. Could not execute query");

$rssfeed = '<?xml version="1.0" encoding="UTF-8"?>';
$rssfeed .= '<rss version="2.0">';
$rssfeed .= '<channel>';
$rssfeed .= '<title>RSS Feed</title>';
$rssfeed .= '<description>RSS Feed</description>';
$rssfeed .= '<link>http://mywebsite.com</link>';
$rssfeed .= '<lastBuildDate>Wed, 24 Nov 2010 09:47:31 +0100</lastBuildDate>';
$rssfeed .= '<language>en-us</language>';
$rssfeed .= '<copyright>Copyright (C) 2010 mywebsite.com</copyright>';
while($row = mysql_fetch_array($result)) {
extract($row);
$rssfeed .= '<item>';
$rssfeed .= '<title>' . $title . '</title>';
$rssfeed .= '<link>http://mywebsite.com/news'.$id.'.html</link>';
$rssfeed .= '<description>[CDATA[' .$introtext . ']]</description>';
$rssfeed .= '<pubDate>' . $created . '</pubDate>';
$rssfeed .= '</item>';
}
$rssfeed .= '</channel>';
$rssfeed .= '</rss>';
echo $rssfeed;
?>

Save this file as index.php and save it in the folder named 'feed'. Now we can directly access the rss feeds from the browser using the link ' http://mywebsite.com/feed '

Monday, November 22, 2010

How to resize youtube embed video using regular expression ?

When we are creating a web application that let the user insert video embeds coming from YouTube or from Vimeo, or what ever else, there is the problem of the embed size. Most probably they will directly insert the embed code, that they are copied from youtube. This size of object tag (iframe, embed, object) may affect our design. If we are creating a video gallery we need to resize the embed code video into our size. In PHP we can use regular expression to resize the embed code.

Sample Code
<?php
//eg :
$video = "<object width="640" height="385">

<param value="http://www.youtube.com/v/bIx5vDn28eE?fs=1&amp;hl=en_US" name="movie" />

<param value="true" name="allowFullScreen" />

<param value="always" name="allowscriptaccess" /><embed width="640" height="385" allowfullscreen="true" allowscriptaccess="always" type="application/x-shockwave-flash" src="http://www.youtube.com/v/bIx5vDn28eE?fs=1&amp;hl=en_US"></embed></object>";


// our prefered size : width="208" height="103"
// regular exression to change the height and width
$pattern = "/height=\"[0-9]*\"/";
$video = preg_replace($pattern, "height='103'", $video);
$pattern = "/width=\"[0-9]*\"/";
$video = preg_replace($pattern, "width='208'", $video);
echo $video;

?>
The above code will resize the embed video into the size we are given.

If we want to add the 'wmode' in the video we can assign that value along with the width parameter.

eg :
$video = preg_replace($pattern, "width='208' wmode='transparent'", $video);

Thursday, November 18, 2010

How to check a radio button list is checked or not using javascript?

How to check a radio button list is checked or not using javascript ?


Radio Buttons are work in groups .If we have a set of radio buttons on a form , they are unchecked by default. We want an alert message if the radio buttons are not checked on submit.

Radio buttons are stored as an array, so we have to loop the array elements to see if one is checked or not.

To determine whether a particular button is pressed the syntax required is:
test = document.formName.radioGroupName[indexNumber].checked;

This will result a TRUE or False value . If the radio button is checked it will result a TRUE value, otherwise FALSE.

Sample Code

<script language="javascript">

function validate()

{

var flag = false;

for(var i =0 ;i<document.frmgraph.cond1.length; i++)

{

if(document.frmgraph.cond1[i].checked)

flag = true;

}

if(flag == false)

{

alert("Please select the group");

return false;

}

return true;

}

</script>

<form id="frmgraph" name="frmgraph" method="post" onsubmit="return validate();">

Male <input type="radio" name="cond1" id="cond1" value="male" />

Female <input type="radio" name="cond1" id="cond1" value="female" />

<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" />

</form>



In this function the javascript will alert a message if the radio button is not checked.

Wednesday, November 17, 2010

New PHP V6 features

PHP is already popular, used in millions of domains (according to Netcraft), supported by most ISPs and used by household-name Web companies like Yahoo! The upcoming versions of PHP aim to add to this success by introducing new features that make PHP more usable in some cases and more secure in others. Are you ready for PHP V6? If you were upgrading tomorrow, would your scripts execute just fine or would you have work to do? This article focuses on the changes for PHP V6 — some of them back-ported to versions PHP V5.x — that could require some tweaks to your current scripts.

If you're not using PHP yet and have been thinking about it, take a look at its latest features. These features, from Unicode to core support for XML, make it even easier for you to write feature-filled PHP applications.

New PHP V6 features

PHP V6 is currently available as a developer snapshot, so you can download and try out many of the features and changes listed in this article.

Improved Unicode support
Much improved for PHP V6 is support for Unicode strings in many of the core functions. This new feature has a big impact because it will allow PHP to support a broader set of characters for international support. So, if you're a developer or architect using a different language, such as the Java™ programming language, because it has better internationalization (i18n) support than PHP, it'll be time to take another look at PHP when the support improves.

Unicode support at present can be set on a per request basis. This equates to PHP having to store both Unicode and non-Unicode variants of class, method and function names in the symbol tables. In short - it uses up more resources. Their decision is to make the Unicode setting server wide, not request wide. Turning Unicode off where not required can help performance and they quote some string functions as being up to 300% slower and whole applications 25% slower as a result. The decision to move it to the php.ini in my mind does take the control away from the user, and puts it into the hands of the Web Host.

If you compile PHP yourself or are responsible for this on your servers then you may be interested to know that PHP 6 will require the ICU libs (regardless if Unicode is turned on or off). The build system will bail out if the required ICU libs cannot be found. In a nutshell, you'll have another thing to install if you want to compile PHP.

Namespaces
Namespaces are a way of avoiding name collisions between functions and classes without using prefixes in naming conventions that make the names of your methods and classes unreadable. So by using namespaces, you can have class names that someone else might use, but now you don't have to worry about running into any problems. Listing 1 provides an example of a namespace in PHP.
You won't have to update or change anything in your code because any PHP code you write that doesn't include namespaces will run just fine. Because the namespaces feature appears to be back-ported to V5.3 of PHP, when it becomes available, you can start to introduce namespaces into your own PHP applications.


Listing 1. Example of a namespace

<?php
// I'm not sure why I would implement my own XMLWriter, but at least
// the name of this one won't collide with the one built in to PHP
namespace NathanAGood;
class XMLWriter
{
// Implementation here...
}

$writer = new NathanAGood::XMLWriter();

?>

Web 2.0 features

Depending on how you use PHP and what your scripts look like now, the language and syntax differences in PHP V6 may or may not affect you as much as the next features, which are those that directly allow you to introduce Web 2.0 features into your PHP application.

SOAP

SOAP is one of the protocols that Web services "speak" and is supported in quite a few other languages, such as the Java programming language and Microsoft® .NET. Although there are other ways to consume and expose Web services, such as Representational State Transfer (REST), SOAP remains a common way of allowing different platforms to have interoperability. In addition to SOAP modules in the PHP Extension and Application Repository (PEAR) library, a SOAP extension to PHP was introduced in V5. This extension wasn't enabled by default, so you have to enable the extension or hope your ISP did. In addition, PEAR packages are available that allow you to build SOAP clients and servers, such as the SOAP package.

Unless you change the default, the SOAP extension will be enabled for you in V6. These extensions provide an easy way to implement SOAP clients and SOAP servers, allowing you to build PHP applications that consume and provide Web services.

If SOAP extensions are on by default, that means you won't have to configure them in PHP. If you develop PHP applications and publish them to an ISP, you may need to check with your ISP to verify that SOAP extensions will be enabled for you when they upgrade.

XML

As of PHP V5.1, XMLReader and XMLWriter have been part of the core of PHP, which makes it easier for you to work with XML in your PHP applications. Like the SOAP extensions, this can be good news if you use SOAP or XML because PHP V6 will be a better fit for you than V4 out of the box.

The XMLWriter and XMLReader are stream-based object-oriented classes that allow you to read and write XML without having to worry about the XML details.

Things removed

In addition to having new features, PHP V6 will not have some other functions and features that have been in previous versions. Most of these things, such as register_globals and safe_mode, are widely considered "broken" in current PHP, as they may expose security risks. In an effort to clean up PHP, the functions and features listed in the next section will be removed, or deprecated, from PHP. Opponents of this removal will most likely cite issues with existing scripts breaking after ISPs or enterprises upgrade to PHP V6, but proponents of this cleanup effort will be happy that the PHP team is sewing up some holes and providing a cleaner, safer implementation.

Features that will be removed from the PHP version include:

* magic_quotes
* register_globals
* register_long_arrays
* safe_mode
* ereg removed from the core
* long variables (i.e. $HTTP_*_VARS)
* <?


magic_quotes

Citing portability, performance, and inconvenience, the PHP documentation discourages the use of magic_quotes. It's so discouraged that it's being removed from PHP V6 altogether, so before upgrading to PHP V6, make sure that all your code avoids using magic_quotes. If you're using magic_quotes to escape strings for database calls, use your database implementation's parameterized queries, if they're supported. If not, use your database implementation's escape function, such as mysql_escape_string for MySQL or pg_escape_string for PostgreSQL. Listing 2 shows an example of magic_quotes use.

Using magic_quotes (discouraged)
<?php
// Assuming magic_quotes is on...
$sql = "INSERT INTO USERS (USERNAME) VALUES $_GET['username']";
?>



After preparing your PHP code for the new versions of PHP, your code should look like that in Listing 3.

Using parameterized queries (recommended)

<?php
// Using the proper parameterized query method for MySQL, as an example
$statement = $dbh->prepare("INSERT INTO USERS (USERNAME) VALUES ?");
$statement->execute(array($_GET['username']));
?>


Now that support for magic_quotes will be completely removed, the get_magic_quotes_gpc() function will no longer be available. This may affect some of the older PHP scripts, so before updating, make sure you fix any locations in which this functions exists.

register_globals

The register_globals configuration key was already defaulted to off in PHP V4.2, which was controversial at the time. When register_globals is turned on, it was easy to use variables that could be injected with values from HTML forms. These variables don't really require initialization in your scripts, so it's easy to write scripts with gaping security holes. The register_globals documentation (see Resources) provides much more information about register_globals. See Listing 4 for an example of using register_globals.

Using register_globals (discouraged)

<?php
// A security hole, because if register_globals is on, the value for user_authorized
// can be set by a user sending them on the query string
// (i.e., http://www.example.com/myscript.php?user_authorized=true)
if ($user_authorized) {
// Show them everyone's sensitive data...
}
?>

If your PHP code uses global variables, you should update it. If you don't update your code to get prepared for newer versions of PHP, consider updating it for security reasons. When you're finished, your code should look like Listing 5.

Being specific instead (recommended)

<?php
function is_authorized() {
if (isset($_SESSION['user'])) {
return true;
} else {
return false;
}
}

$user_authorized = is_authorized();
?>

register_long_arrays

The register_long_arrays setting, when turned on, registers the $HTTP_*_VARS predefined variables. If you're using the longer variables, update now to use the shorter variables. This setting was introduced in PHP V5 — presumably for backward-compatibility — and the PHP folks recommend turning it off for performance reasons. Listing 6 shows an example of register_long-arrays use.

Using deprecated registered arrays (discouraged)

<?php
// Echo's the name of the user value given on the query string, like
// http://www.example.com/myscript.php?username=ngood
echo "Welcome, $HTTP_GET_VARS['username']!";
?>


If your PHP code looks like that shown in Listing 6, update it to look like that in Listing 7. Shut off the register_long_arrays setting if it's on and test your scripts again.

Using $_GET (recommended)


<?php
// Using the supported $_GET array instead.
echo "Welcome, $_GET['username']!";
?>

safe_mode

The safe_mode configuration key, when turned on, ensures that the owner of a file being operated on matches the owner of the script that is executing. It was originally a way to attempt to handle security when operating in a shared server environment, like many ISPs would have. (For a link to a list of the functions affected by this safe_mode change, see Resources.) Your PHP code will be unaffected by this change, but it's good to be aware of it in case you're setting up PHP in the future or counting on safe_mode in your scripts.

PHP tags

Microsoft Active Server Pages (ASP)-style tags — the shorter version of the PHP tags — are no longer supported. To make sure this is not an issue for your scripts, verify that you aren't using the <% or %> tags in your PHP files. Replace them with .

FreeType 1 and GD 1

The PHP team is removing support for both FreeType 1 and GD 1, citing the age and lack of ongoing developments of both libraries as the reason. Newer versions of both of these libraries are available that provide better functionality. For more information about FreeType and GD, see Resources.

ereg

The ereg extension, which supports Portable Operating System Interface (POSIX) regular expressions, is being removed from core PHP support. If you are using any of the POSIX regex functions, this change will affect you unless you include the ereg functionality. If you're using POSIX regex today, consider taking the time to update your regex functions to use the Perl-Compatible Regular Expression (PCRE) functions because they give you more features and perform better. Table 1 provides a list of the POSIX regex functions that will not be available after ereg is removed. Their PCRE replacements are also shown.

'var' to alias 'public'

PHP4 used 'var' within classes. PHP5 (in its OO move) caused this to raise a warning under E_STRICT. This warning will be removed in PHP6 and instead 'var' will mean the same thing as 'public'. This is a nice move but I if anyone has updated their scripts to work under E_STRICT in PHP5 it will be a redundant one for them.




PHP Engine Additions

64 bit integers
A new 64 bit integer will be added (int64). There will be no int32 (it is assumed unless you specify int64)

breaking to a label
No 'goto' command will be added, but the break keyword will be extended with a static label - so you could do 'break foo' and it'll jump to the label foo: in your code. We can jump the execution into a labeled point.

<?php
for ($i = 0; $i < 9; $i++) { if (true) { break blah; } echo "not shown"; blah: echo "iteration $i\n"; } ?>



ifsetor()

It looks like we won't be seeing this one, which is a shame. But instead the ?: operator will have the 'middle parameter' requirement dropped, which means you'd be able to do something like this: "$foo = $_GET['foo'] ?: 42;" (i.e. if foo is true, $foo will equal 42). This should save some code, but I personally don't think it is as 'readable' as ifsetor would have been.

foreach multi-dim arrays
syntactic sugar
This is a nice change - you'll be able to foreach through array lists, i.e. "foreach( $a as $k => list($a, $b))".


<?php
$a = array(
array(1, 2),
array(3, 4)
);
foreach( $a as $k => list($a, $b)) {
// blah
}
?>

{} vs []
You can currently use both {} and [] to access string indexes. But the {} notation will raise an E_STRICT in PHP5.1 and will be gone totally in PHP6. Also the [] version will gain substr and array_slice functionality directly - so you could do "[2,]" to access characters 2 to the end, etc. Very handy.

improvements to []

For both strings and arrays, the [] operator will support substr()/array_slice() functionality.
• [2,3] is elements (or characters) 2, 3, 4
• [2,] is elements (or characters) 2 to the end
• [,2] is elements (or characters) 0, 1, 2
• [,-2] is from the start until the last two elements in the array/string
• [-3,2] this is the same as substr and array_slice()
• [,] doesn't work on the left side of an equation (but does on the right side)




Resources
http://www.ibm.com/developerworks/opensource/library/os-php-future/
http://www.corephp.co.uk/archives/19-Prepare-for-PHP-6.html
http://www.php.net/~derick/meeting-notes.html

Monday, November 15, 2010

How to send email from your joomla component

Many times you will have the need to send emails from your joomla component. Users want to be notified immediately of changes on their sites, when a new article has been submitted, or a blog comment has been posted. Joomla provides email notifications to site administrator when a user has registered on their site.If you want to create a component and that component needs an email functionality, you dont need to create a custom email function for the component. Joomla provides a very helpful class for this.Thats JMail.


# Set the variables for the email message
$subject = "Subject for the email message";
$body = "Body of the email message";
$to = "user@domainname.com";
$from = array("admin@domainname.com", "Administrator");


# Invoke JMail Class

$mailSender = JFactory::getMailer();

# Set the sender array
$mailSender->setSender($from);

# Add the recipient - We can assign a single email address or an array of addresses

$mailSender->addRecipient($to);
$mailSender->setSubject($subject);
$mailSender->setBody($body);

# If you would like to send as HTML, include this line.
$mailSender->isHTML();
# Send the mail
if (!$mailSender ->Send())
{
echo "there is an error with the mail";
}


That's all for sending a simple email.If you would like to add carbon copy recipients, include the following before sending the email.



$mailSender->addCC("carboncopy@domainname.com");

# Add a blind carbon copy

$mailSender->addBCC("blindcopy@domainname.com");


It also has the option to add attachments.


If the file is in the server we can give the path.


$file = JPATH_SITE."/path/filename.doc";


$mailSender->addAttachment($file);


If we want to send an user uploaded file, then we have to give the option to upload the file.

The code is as follows.



Change the enctype of the form.


<form action="index.php" enctype="multipart/form-data" method="post" name="adminForm">

Add a file field within the form.



<input class="text_area" id="attachment" maxlength="250" name="attachment" size="32" type="file">









get the attached file.




$attachment = JRequest::getVar('attachment', null, 'files', 'array' );



$name_of_uploaded_file = $attachment['name'];
$config =& JFactory::getConfig();
$upload_folder = $config->getValue('config.tmp_path').DS;
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $attachment ['tmp_name'];

jimport('joomla.filesystem.file');
$uploaded = JFile::upload($tmp_path, $path_of_uploaded_file);
$mailSender->addAttachment($path_of_uploaded_file);






There are several more methods available in JMail.

You should also check out JMailHelper.

It provides several functions to help you secure input from users before passing it along in an email.

Adding sortable columns to a joomla component

Most of the joomla components have listing of data. And some of them dont have a sorting option in the listing. This tutorial explains that how to add a sortable column in a joomla component. To explain this we are taking the component 'com_profiler'.


The joomla the component 'com_profiler' is very helpful in profile making. It has a user listing in the administrator side. It lists the users list with name, username, groups, email etc. But this section doesnt have a sorting field. Usually you cant sort any fields in 'com_profiler' user list. This section explains how to add a sorting field in the admin section of comprofiler. Now we are going to change the username field in to a 'sorting' field.


Usually the user listing is generated by the comprofiler html page and comprofiler controller page. Path for these pages are as follows.


administrator/components/com_comprofiler/admin.comprofiler.html.php

administrator/components/com_comprofiler/admin.comprofiler.controller.php


Step 1 : Modify the admin.comprofiler.html.php


In admin.comprofiler.html.php there is a function named 'showUsers'. This function generates the list of users. In the showuser function we will add the 'ordering' code



global $mainframe;

$filter_order = $mainframe->getUserStateFromRequest( $option.'filter_order', 'filter_order', 'u.username', 'cmd' );

$filter_order_Dir = $mainframe->getUserStateFromRequest( $option.'filter_order_Dir', 'filter_order_Dir', 'asc','word' );
$lists1['order_Dir'] = $filter_order_Dir;

$lists1['order'] = $filter_order;


So the page will look like as

function showUsers( &$rows, &$pageNav, $search, $option, &$lists, &$pluginColumns ) {

HTML_comprofiler::secureAboveForm('showUsers');

// table ordering

global $mainframe;

$filter_order = $mainframe->getUserStateFromRequest( $option.'filter_order', 'filter_order', 'u.username', 'cmd' );

$filter_order_Dir = $mainframe->getUserStateFromRequest( $option.'filter_order_Dir', 'filter_order_Dir', 'u.username','word' );
$lists1['order_Dir'] = $filter_order_Dir;

$lists1['order'] = $filter_order;

outputCbTemplate( 2 );

outputCbJs( 2 );


Step 2 : Setting the Order Link

After that we can set the sorting link to the username field. Place the following code instead of the 'Usernmae' Title.


<?php echo JHTML::_( 'grid.sort', 'UserName', 'u.username', $lists1['order_Dir'], $lists1['order']); ?>

So the code will look like as follows.


<th width="15%" class="title"><?php echo CBTxt::T('Name'); ?></th>

<th width="10%" class="title">

<?php echo JHTML::_( 'grid.sort', 'UserName', 'u.username', $lists1['order_Dir'], $lists1['order']); ?></th>

<th width="5%" class="title" nowrap="nowrap"><?php echo CBTxt::T('Logged In'); ?></th>

Step 3 : Add the Hidden Fields


Also add the hidden fields to post the sorting field and sorting direction to the controller page. Add the following code before the end of the form


<input type="hidden" name="filter_order" value="<?php echo $lists1['order']; ?>" />

<input type="hidden" name="filter_order_Dir" value="<?php echo $lists1['order_Dir']; ?>" />

now the code will look like as follows.


<input type="hidden" name="option" value="<?php echo $option;?>" />

<input type="hidden" name="task" value="showusers" />

<input type="hidden" name="boxchecked" value="0" />

<input type="hidden" name="filter_order" value="<?php echo $lists1['order']; ?>" />

<input type="hidden" name="filter_order_Dir" value="<?php echo $lists1['order_Dir']; ?>" />
<?php

echo cbGetSpoofInputTag( 'user' );

?>

</form>

Step 4 : Modify the controller code (admin.comprofiler.controller.php)


The controller grabs the data from the database.


So we need to modify the function to list based on the order.


The controller contains a function named 'showUsers'.Edit the function to get the post values submitted from the listng page. Use the post method to assign the values. After placing the code the function will look like as


function showUsers( $option ) {

global $_CB_database, $_CB_framework, $_POST, $_PLUGINS, $_CB_TxtIntStore;

if(isset($_POST['filter_order']))

     $filter_order = $_POST['filter_order'];

else

     $filter_order = "u.username";



if(isset($_POST['filter_order_Dir']))

      $filter_order_Dir = $_POST['filter_order_Dir'];

else

     $filter_order_Dir = "asc";

Also modify the search query to get the ordered data.Add the ' ORDER BY' clause in the search query. After adding the ' ORDER BY ' clause the code will look like as the follow.


$query = "SELECT DISTINCT u.*, g.name AS groupname, ue.approved, ue.confirmed"

. $queryFrom

. " ORDER BY $filter_order $filter_order_Dir "

. "\n LIMIT " . (int) $pageNav->limitstart . ", " . (int) $pageNav->limit

;

That's all. Now in the user listing of the admin panel we have the 'user name ' filed as link. Now we can list the data's either in ascending order or by descending order.

Wednesday, November 10, 2010

Twitter Application development


What is twitter


Twitter is a status-updating or microblogging social networking website. It is a breakthrough in social networking because it takes communication into another level. Before, a person can only update his status (e.g. what he's doing, where he is) at a certain time. But with Twitter and its mobile integration, he can update his status almost all throughout the day and get in touch with people that matters to him the most.



But the functions of Twitter do not stop there. It is now used by various fields. Business, for example, has used Twitter to get in touch with customers on a personal level. It is also a nice place to meet people from different parts of the world that shares the same interests. Furthermore, its possibilities to promote new technology, news and products can't be denied.

Twitter have been used by companies, bloggers and agencies to promote their brand


Advantages and disadvantages of using Twitter for Internet Marketing


Advantages of twitter


Your Internet marketing can be done free of cost if you use Twitter wisely. Your target market is out there for you to seek and understand. Understand from their tweets, their passion and interests. Do your research on your target market by following the tweets of your target market for better understanding. Identify the strategies used by your competitors by following their tweets as well.

Twitter allows you to network efficiently and with large groups of people. Twitter and its third party applications allow you to segregate and interact with your target markets effectively. You can direct your Internet marketing campaigns at relevant groups efficiently by using Twitter

Twitter allows you to communicate directly with your target market instantly. Normally, the process of communication takes time. For example, if you have a Website, the communication would be via polls, which are not personal or though contact forms which are time consuming and impersonal as well. With twitter, you can expect instant communication with your target market. You may have just posted a tweet, but a reply from your target market could come in an instant as well. Twitter helps you to gather real time intelligence from your very own target market as well as obtain valuable feedback. The speed of communication is just fantastic with Twitter. Moreover, your near approach helps to builds lasting relationship as you will come cross as a company that cares for its consumers instead of just hard selling.


Disadvantages of twitter


Twitter is the number one site for spammers. You will have to filter and weed out spammers from your lists from time to time, if you want to have a good gauge of your target market. Otherwise, the followers total will be an inflated number which will not help in your Internet marketing campaigns. Filtering spam tweets is a lot of hard work. Other means of Internet marketing may seem feasible in the long run.



Twitter has no applications rather than other sites like Facebook, Friendster and MySpace. It also has no groups, videos, blogs, classified ads, forums, marketplace and other unique and popular social networking menus. You can only upload one picture, which is your avatar and must be small, compare to other social networks which you can upload pictures as many as you want. You also cannot upload music files here on Twitter, but you can upload on the other social networks.


What does twitter do for businesses?


Twitter is a communication platform that helps businesses stay connected to their customers. As a business, you can use it to quickly share information with people interested in your company, gather real-time market intelligence and feedback, and build relationships with customers, partners and other people who care about your company. As an individual user, you can use Twitter to tell a company (or anyone else) that you've had a great—or disappointing—experience with their business, offer product ideas, and learn about great offers.

How does it work?


Twitter lets you write and read messages of up to 140 characters, or the very length of this sentence, including all punctuation and spaces. The messages are public and you decide what sort of messages you want to receive—Twitter being a recipient driven information network. In addition, you can send and receive Twitter messages, or tweets, equally well from your desktop or your mobile phone.

When you combine messages that are quick to write, easy to read, public, controlled by the recipient and exchangeable anywhere, you’ve got a powerful, real-time way to communicate. And real-time communication is turning out to be ground-breaking for users and businesses alike.


How do businesses use Twitter?


Twitter connects you to your customers right now, in a way that was never before possible. For example, let’s say you work for a custom bike company. If you run a search for your brand, you may find people posting messages about how happy they are riding your bikes in the French Alps—giving you a chance to share tips about cyclist-friendly cafes along their route.

Others may post minor equipment complaints or desired features that they would never bother to contact you about—providing you with invaluable customer feedback that you can respond to right away or use for future planning. Still others may twitter about serious problems with your bikes—letting you offer customer service that can turn around a bad situation.

You don’t have to run a bike shop or a relatively small company to get good stuff out of Twitter. Businesses of all kinds, including major brands, increasingly find that listening and engaging on the service leads to happier customers, passionate advocates, key product improvements and, in many cases, more sales.


A key benefit


One of Twitter’s key benefits is that it gives you the chance to communicate casually with customers on their terms, creating friendly relationships along the way—tough for corporations to do in most other mediums.

But Twitter isn’t just about useful immediacy. The conversational nature of the medium lets you build relationships with customers, partners and other people important to your business. Beyond transactions, Twitter gives your constituents direct access to employees and a way to contribute to your company; as marketers say, it shrinks the emotional distance between your company and your customers. Plus, the platform lends itself to integration with your existing communication channels and strategies. In combination, those factors can make Twitter a critical piece of your company’s bigger digital footprint.

For instance, let’s say you run a big retail website. In addition to learning more about what your customers want, you can provide exclusive Twitter coupon codes, link to key posts on your blog, share tips for shopping online, and announce specials at store locations. And you can take things a step further by occasionally posting messages about fun, quirky events at your HQ, giving others a small but valuable connection with the people in your company.

Tip: Companies sometimes worry that twittering might require a lot of staff time or even hiring new people to maintain an account. In fact, Twitter works best for businesses when you start slow, devoting a few minutes a day to see whether and how it’s valuable to you.


Twitter Application development


We need to use the Twitter API and Twitter Content to develop a Service to search, display, analyze, retrieve, view, and submit information to or on Twitter


Twitter API


http://dev.twitter.com/pages/api_overview

Face book Application Development

Facebook is one of the fastest growing social networking websites and is quickly becoming a powerful and cost effective portal, ideal for organizations to create that ‘brand connection’ in the Web2.0 world.

http://www.facebook.com


What are Facebook applications?


Facebook applications are the software programs that allow users to connect, interact and entertain themselves and their ‘friends’.

Most Facebook users today use 3rd party Facebook applications to add some fun and personality to their Facebook profile. Their purpose is to generate content that the user finds is relevant or of interest to them.

There is virtually an application for everything, ranging from a Facebook application that reminds a user when their favorite band is coming to town to a slide show of a collection of sentimental photos. The great thing about Facebook applications is that if it is to be added to a profile, the users listed as a individual’s ‘friends’ are sent an option of also using it. The application then circulates at such a rapid rate exposure is viral.


Now a day’s most company’s developing facebook applications like gaming, interactive interfaces to promote their products etc.

http://www.facebook.com/apps/directory.php


Many site are integrated their facebook features into their sites

http://developers.facebook.com/showcase/


Facebook Application Development


We can create an application completely focused on our business brand. Think of a travel application that links to booking information on our website or a product catalogue of our latest products. All applications are designed to generate maximum interest on our business and draw continual international traffic to our website.

http://developers.facebook.com/


How to create a Facebook  Application


To create an application we need to register our application with facebook. Also we need to install the facebook developer kit.  Using the facebook application we can access information about the facebook profile even the non public information. For example if a facebook user register with our site , we can use facebook login for registering. If the user login with facebook we can collect the public information of the user including the emailid. So no need to confirm the email again, because it Is already confirmed by facebook. Also we can collect address, phone no, gender etc.


Tutorials to develop a Facebook application

http://developers.facebook.com/


Scope of facebook social plug-in   


A reader on your site, who is logged into her Facebook account, can now give your story a “Thumbs up” by simply clicking this Like button. She will also have to option to publish a snippet of your blog story on to her Facebook profile.

Then you have the Activity widget that shows in near real-time how people are interacting with your stories. If the user is logged into Facebook, the activity widget will show the activity of her friends on your web site else it’ll show everyone’s activity.

However, the most exciting social plug in for Facebook in the new recommendations engine. It shows a list of most popular stories on your blog as determined by the count of Facebook users who have “liked” that story.


To get started, we need to add our domain name to Facebook.


http://www.facebook.com/insights/


We basically need to verify that we are the actual owner of the domain and we can do this by simply adding a unique HTML META tag to our blog header.

Facebook will check the tag in our blog and once it’s verified, we can link the reports to either our Facebook profile or any Facebook page, if we own one.

Once everything is in place, we can revisit the Facebook Insights page to get detailed sharing stats of our blog pages. It will even tell us the top countries / cities of users who are interacting with our stories including the demographics.


If you have a forum or a blog site that requires registration, you may also explore the Sign-on widget that will let user registers on your site using their Facebook ID

This new tools from makes it possible for websites to allow you to connect with your friends and their likings. It helps you get first hand views and reviews from friends about the new movie which is the talk of the town, or the menu in any restaurant or the latest news. Not that it doesn’t allow strangers to give their feedback but it makes it possible for your friends to stand prominently.


The plugins makes it possible to show your action in the following ways you can either ‘like’ content, or you can ‘recommend’ such contents.  This makes it possible for you to connect with any content that you like publicly.


Alternately the tool also helps to remove or ‘unlike’ any new content or previously liked content. Another possible way is through the activity feed. This lets you know what your friends are doing with their likes and recommendations while visiting a particularly popular website.


Social plugins

All social plugins are extensions of Facebook and are specifically designed so none of our data is shared with the sites on which they appear.

We can add these plugins into our site by adding a group of code into our website.


Facebook  Plugins


1: Like Button


The Like button lets a user share your content with friends on Facebook. When the user clicks the Like button on your site, a story appears in the user's friends' News Feed with a link back to your website.


http://developers.facebook.com/docs/reference/plugins/like


2: Activity Feed


The Activity Feed plugin displays the most interesting recent activity taking place on your site. Since the content is hosted by Facebook, the plugin can display personalized content whether or not the user has logged into your site. The activity feed displays stories both when users like content on your site and when users share content from your site back to Facebook.


http://developers.facebook.com/docs/reference/plugins/activity


3: Comments


The Comments Box easily enables your users to comment on your site's content — whether it's for a web page, article, photo, or other piece of content. Then the user can share the comment on Facebook on their Wall and in their friends' streams.


http://developers.facebook.com/docs/reference/plugins/comments


Sample code

<div id="fb-root"></div><script src="http://connect.facebook.net/en_US/all.js#appId=APP_ID&amp;xfbml=1"></script><fb:comments xid="1234" width="425"></fb:comments>


4: Facepile


The Facepile plugin shows the Face book profile pictures of the user's friends who have already signed up for your site.

You can specify the maximum number of rows of profile pictures to display. The plugin dynamically sizes its height; for example, if you specify a maximum of four rows, and there are only enough friends to fill two rows, the height of the plugin will be only what is needed for two rows of profile pictures. The plugin doesn't render if the user is logged out of Facebook or doesn't have friends who have signed up for your site using Facebook.


Sample code

<div id="fb-root"></div><script src="http://connect.facebook.net/en_US/all.js#appId=APP_ID&amp;xfbml=1"></script><fb:facepile max-rows="5" width="600"></fb:facepile>


http://developers.facebook.com/docs/reference/plugins/facepile


5: Like Box


The Like Box is a social plugin that enables Facebook Page owners to attract and gain Likes from their own website. The Like Box enables users to:



  • See how many users already like this page, and which of their friends like it too

  • Read recent posts from the page

  • Like the page with one click, without needing to visit the page


http://developers.facebook.com/docs/reference/plugins/like-box


6: Live Stream


The Live Stream plugin lets users visiting your site or application share activity and comments in real time. Live Stream works best when you are running a real-time event, like live streaming video for concerts, speeches, or webcasts, live Web chats, webinars, massively multiplayer games.


http://developers.facebook.com/docs/reference/plugins/live-stream


7: Login Button


The Login Button shows profile pictures of the user's friends who have already signed up for your site in addition to a login button.

You can specify the maximum number of rows of faces to display. The plugin dynamically sizes its height; for example, if you specify a maximum of four rows of faces, and there are only enough friends to fill two rows, the height of the plugin will be only what is needed for two rows of faces.


http://developers.facebook.com/docs/reference/plugins/login


8: Recommendations


The Recommendations plugin shows personalized recommendations to your users. Since the content is hosted by Facebook, the plugin can display personalized recommendations whether or not the user has logged into your site. To generate the recommendations, the plugin considers all the social interactions with URLs from your site. For a logged in Facebook user, the plugin will give preference to and highlight objects her friends have interacted with.


http://developers.facebook.com/docs/reference/plugins/recommendations

Replace a string in the mysql database using REPLACE function

Many times we have the need to change the values of database fields. If our table contains thousands of records, its not possible to manually edit the records. So we can use MySQL REPLACE function to replace the string. The syntax to use the replace function is as follows.


UPDATE `table_name` SET `field_name` = REPLACE(`field_name`, 'Keyword to be replaced', 'Replacement String');

For example if we have changed the website name , we also need to change the datas in the downloads table (if we have).


Now we can use a single sql query with REPLACE function , and it will affect the whole records.


UPDATE `tbl_downloads` SET `sitename` = REPLACE(`sitename`, 'www.old-sitename.com', 'www.new-sitename.com');

now all the datas with 'old-sitename' will replace with the new-sitename

Romove the title from the vimeo video.

Usually we are using iframe to embedd a vimeo video.

It similar as the follow.


<iframe src="http://player.vimeo.com/video/123456789" width="400" height="300" frameborder="0"></iframe><p><a href="http://vimeo.com/123456789">Video Title</a> from <a href="http://vimeo.com/user123456">vimeo user</a> on <a href="http://vimeo.com">Vimeo</a>.</p>

While embedding with the iframe code the video title also with the video


If we want to remove the title and video owner name from the vimeo video , we can use embedd code .


The code will similar as the follow.



<object width="400" height="300"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=123456789&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portr ait=0&amp;color=&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=123456789&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portr ait=0&amp;color=&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="400" height="300"></embed></object><p><a href="http://vimeo.com/123456789">Video Title</a> from <a href="http://vimeo.com/user123456">vimeo user</a> on <a href="http://vimeo.com">Vimeo</a>.</p>

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