Archive for March 2011

PHP Sessions



An alternative way to make data accessible across the various pages of an entire website is to use a PHP Session.
A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.
The location of the temporary file is determined by a setting in the php.inifile called session.save_path. Bore using any session variable make sure you have setup this path.
When a session is started following things happen:
  • PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
  • A cookie called PHPSESSID is automatically sent to the user's computer to store unique session identification string.
  • A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e3443.
When a PHP script wants to retrieve the value from a session variable, PHP automatically gets the unique session identifier string from the PHPSESSID cookie and then looks in its temporary directory for the file bearing that name and a validation can be done by comparing both values.
A session ends when the user loses the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration.
Starting a PHP Session:
A PHP session is easily started by making a call to the session_start()function.This function first checks if a session is already started and if none is started then it starts one. It is recommended to put the call to session_start()at the beginning of the page.
Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session.
The following example starts a session then registers a variable called counterthat is incremented each time the page is visited during the session.
Make use of isset() function to check if session variable is already set or not.
Put this code in a test.php file and load this file many times to see the result:
<?php
   session_start();
   if( isset( $_SESSION['counter'] ) )
   {
      $_SESSION['counter'] += 1;
   }
   else
   {
      $_SESSION['counter'] = 1;
   }
   $msg = "You have visited this page ".  $_SESSION['counter'];
   $msg .= "in this session.";
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php  echo ( $msg ); ?>
</body>
</html>
Destroying a PHP Session:
A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.
Here is the example to unset a single variable:
<?php
   unset($_SESSION['counter']);
?>
Here is the call which will destroy all the session variables:
<?php
   session_destroy();
?>
Turning on Auto Session:
You don't need to call start_session() function to start a session when a user visits your site if you can set session.auto_start variable to 1 in php.inifile.
Sessions without cookies:
There may be a case when a user does not allow to store cookies on their machine. So there is another method to send session ID to the browser.
Alternatively, you can use the constant SID which is defined if the session started. If the client did not send an appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to an empty string. Thus, you can embed it unconditionally into URLs.
The following example demonstrates how to register a variable, and how to link correctly to another page using SID.
<?php
   session_start();

   if (isset($_SESSION['counter'])) {
      $_SESSION['counter'] = 1;
   } else {
      $_SESSION['counter']++;
   }
?>
   $msg = "You have visited this page ".  $_SESSION['counter'];
   $msg .= "in this session.";
   echo ( $msg );
<p>
To continue  click following link <br />
<a  href="nextpage.php?<?php echo htmlspecialchars(SID); >">
</p>
The htmlspecialchars() may be used when printing the SID in order to prevent XSS related attacks.

Como saber que navegador usa un visitante con PHP

Para hacerlo, vamos a consultar la información que el navegador nos envía como parte de su petición HTTP. Esta información es guardada en una variable. Las variables siempre comienzan con un signo de dólar ("$") en PHP. La variable que vamos a utilizar en esta situación es $_SERVER["HTTP_USER_AGENT"].

$_SERVER es una variable reservada por PHP que contiene toda la información del servidor web. Es conocida como Autoglobal (o Superglobal).

Para poder ver esta variable solo necesitamos el siguiente codigo:

<?php echo $_SERVER["HTTP_USER_AGENT"]; ?>

esto nos dara un resultado similar a:

Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)

$_SERVER es simplemente una variable que se encuentra disponible automáticamente en PHP.

Por ejemplo, si quisiéramos detectar el uso de "Internet Explorer", haríamos algo así:

   

<?php

if (strstr($_SERVER["HTTP_USER_AGENT"], "MSIE")) {

echo "Está usando Internet Explorer<br />";

}

?>

esto nos dara un resultado similar a:

Esta usando Internet Explorer

En el caso anterior estamos buscando "MSIE" dentro de $_SERVER["HTTP_USER_AGENT"]. Si la cadena fue encontrada, la función devolverá verdadero ("TRUE"), la declaración "if" se evalúa a verdadero ("TRUE") y el código adentro de las llaves {} es ejecutado. De otra manera no resulta ejecutado.

Comonent/com_content/view/category/tmpl/default

i have customize this com_content, so here is code

/* default.php */
defined('_JEXEC') or die('Restricted access');
$cparams =& JComponentHelper::getParams('com_media');
?>
params->get('show_page_title', 1)) : ?>


escape($this->params->get('page_title')); ?>











category->description; ?>
category->image) : ?>
<?php echo $this->category->image;?>


View holydays in category->title;?>>





$this->items =& $this->getItems();
echo $this->loadTemplate('items');
?>

access->canEdit || $this->access->canEditOwn) :
echo JHTML::_('icon.create', $this->category , $this->params, $this->access);
endif; ?>

Backup Recovery / Export to CSV

<?php
ini_set('date.timezone', 'Asia/Calcutta');

$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'bdname';
$table = 'tblname';
$file = 'Backup';

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");

$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field'].",";
$i++;
}
}
$csv_output .= "\n";

$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].",";
}
$csv_output .= "\n";
}

$filename = $file."_".date("d_m_Y_h_i_s_a",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>

WideImage - PHP library for image manipulation

WideImage is an object-oriented library for image manipulation. It requires PHP 5.2+ with GD2 extension. The library provides a simple way to loading, manipulating and saving images in the most common image formats.

Download / Homepage

Usage;
<?php
    WideImage::load('big.png')->resize(50, 30)->saveToFile('small.jpg');
    WideImage::load('pic.jpg')->crop('center', 'center', 90, 50)->output('png');
?>


It seems pretty good and has good documentation. I am going to use it for my next project.

Usage

PHP is a general-purpose scripting language that is especially suited for web development. PHP generally runs on a web server, taking PHP code as its input and creating web pages as output. It can also be used for command-line scripting and client-side GUI applications. PHP can be deployed on most web servers, many operating systems and platforms, and can be used with many relational database management systems. It is available free of charge, and the PHP Group provides the complete source code for users to build, customize and extend for their own use.

PHP primarily acts as a filter, taking input from a file or stream containing text and/or PHP instructions and outputs another stream of data; most commonly the output will be HTML. It can automatically detect the language of the user. From PHP 4, the PHP parser compiles input to produce bytecode for processing by the Zend Engine, giving improved performance over its interpreter predecessor.

Originally designed to create dynamic web pages, PHP's principal focus is server-side scripting, and it is similar to other server-side scripting languages that provide dynamic content from a web server to a client, such as Microsoft's ASP.NET system, Sun Microsystems' JavaServer Pages, and mod_perl. PHP has also attracted the development of many frameworks that provide building blocks and a design structure to promote rapid application development (RAD). Some of these include CakePHP, PRADO, Symfony and Zend Framework, offering features similar to other web application frameworks.

The LAMP architecture has become popular in the web industry as a way of deploying web applications. PHP is commonly used as the P in this bundle alongside Linux, Apache and MySQL, although the P may also refer to Python or Perl.

As of April 2007, over 20 million Internet domains were hosted on servers with PHP installed, and PHP was recorded as the most popular Apache module. Significant websites are written in PHP including the user-facing portion of Facebook, Wikipedia (MediaWiki), Yahoo!, MyYearbook, and Tagged.

Tools to make your website work better

Site-Perf – get an accurate, realistic, and helpful estimation of your site’s loading speed. The script fully emulates natural browser behavior downloading your page with all the images, CSS, JS and other files – just like a regular user. A unique feature is that site-perf.com allows to measure packet loss ratio with reasonable precision.

2. Customer Focus Calculator – will analyze the words on your page and determine if your copy is more about yourself or your customer. This tool will measure if you are we-we-ing all over yourself.

3. BT Buckets – Engage your users with a free segmentation and behavioral targeting tool.

4. 4Q from IPerceptions – developed with web analytics evangelist Avinash Kaushik. When evaluating how you website is doing obviously it helps to get your customers’ opinions. This free tool helps you answer four important questions:

* How satisfied are my visitors?
* What are my visitors at my website to do?
* Are they completing what they set out to do?
* If not, why not?
* If yes, what did they like best about the online experience?

5. What’s the Buzz? – a keyword research tool with one simple aim: to find out who’s talking about a certain keyword. To do that, it does five things:

* It displays the Technorati Blog Popularity Chart, showing how popular the keyword has been blogged about in the past 90 days
* It displays the Google Trends chart for the keyword
* It finds blog posts tagged with the keyword
* It finds blog posts containing the keyword (a straight-forward search)
* It finds social bookmarks tagged with the keywords

6. Bad Neighborhood Link Checker – scan the links on your website, and on the pages that your website is linking to, and flag possible problem areas.

7. Backlink Social Celebrity SEO Tool – discover who bookmarked a webpage and who linked to that webpage. The bookmarks are searched for in the various social bookmarking services, such as del.icio.us, Raw Sugar, and others. The backlinks are found using Google and Yahoo!.

8. Webbed-O-Meter 2.0 – can help track how effective you are at inspiring consumer generated content online, call it buzz marketing, social media marketing or viral marketing.

9. Website Grader – provides a score that incorporates things like website traffic, SEO, social popularity and other technical factors. It also provides some basic advice on how the website can be improved from a marketing perspective.

10. Spider Simulator – help you find out for yourself how a search engine reacts to your pages and what can be done to boost your visibility.

11. Spider Test – Shows the source code of a page, all outbound links, and common words and phrases.

12. Google Analytics – web analytics with new “enterprise features” and a ton of plugins and hacks.

13. Google Website Optimizer – Free A/B and Multivariate Testing

14. Yahoo! Analytics – still in beta, but incredibly powerful. It is currently available with Yahoo! Merchant Solutions Standard, Professional, and Yahoo! Store plans.

15. Microsoft adCenter Analytics – by invitation only, but you can apply at the link provided.

16. Piwik – This is an open source web analytics solution.

17. Linkscape – allows access to link information on more than 30+ billion web pages across 200+ million domains.

18. BacklinkAnalysis – Get a look at what keywords websites are linking to you with.

19. Trifecta – Measures metrics to estimate the relative popularity and importance of Page, Blog or Domain.

20. Firebug – this plugin for Firefox provides a number of development tools. For the purposes of analysis, Firebug will allow you to monitor and debug HTML, CSS, and JavaScript from within your browser.

21. YSlow for Firebug – YSlow will analyze your page to make suggestions for how you can speed up the page. YSlow is integrated with Firebug.

22. Google Webmaster Tools – see which phrases your ranking well for, what pages are causing problems for Google when crawling your site, which pages are getting the most links, rss subscribers, etc.

23. Morgue File – offers free high resolution digital stock photography for either corporate or public use.

24. OpenAds – for sites that want to serve and track advertising.

25. Sitescore – analyzes the quality of incoming and outgoing links, keyword density, page titles, plagiarism, popularity rank, the usage of popups and the effectiveness of site’s structure. Sitescore also grades the printability, readability, spiderability and usability of the page as well as spelling and W3C compliance. This is no longer available for free, sorry.

26. mon.itor.us – use this to monitor uptime, website performance and other hosting abnormalities.

27. Orangoo Spell Check – spell check your website.

28. The Scrutinizer – offers 283 tools to test your website in one place.

29. Product Indexation Check – use this handy tool to check how many of your category or product pages are included in the major search engines.

30. Kamplye – allows your visitors to give feedback on your site, via a little button that sits at the edge of each webpage.

31. Google’s Free Custom Search Engine – create your own custom search engine, indexing your website or add additonal websites as well.

32. Feng-GUI – generates heatmaps for your website (upload a screenshot) by simulating human vision during the first five seconds of viewing your website.

33. Scrutinizer browser – a web browser, based upon the Adobe AIR toolkit and the WebKit browser, that offers a simulation of the human visual system. Using this simulation, you can get a better idea of how users interact with your site design.

PHP echo vs print vs printf

PHP use mainly echo , print and prinf to output data to browser.

eg:
echo "Hello World ";
echo "Hello"," World";


print "Hello World";
print ("Hello World");


printf ("Hello Word");


Lets see these functions prototype

int print(argument)
void echo (string argument1 [, .... string argumentN])
boolean printf(string format [, mixed args])


now whats difference between echo and print
echo is faster because it doesn't return any value while print return '1' if data is printed successfully
and also we cannot join strings using "," when using print


printf is for blending static and dynamic information like in C Language

eg:
printf("My Age is %d",22);

Protect table and field names with backticks - Solution - Codeignter Active Record

I found a bug with the codeigniter related to Protecting identifiers - I am not sure is it is a bug.

Protecting identifiers means:
In many databases it is advisable to protect table and field names - for example with backticks( ` ) in MySQL. Active Record queries are automatically protected.

In codeigniter it states like, it is protecting the field names and table names with backticks when using active record class. 

In my case it looks like, it is working fine until we use a select statement with the second parameter to false. 

for eg: $this->db->select('select count(*) as visit_count',FALSE);

Here the second parameter is 'FALSE' and from the next sql statements, it will avoid the escaping of field names with back ticks.

Example of sql that escaped with backticks: select `firstname`, `lastname`, `date` from `tablename`

Example of sql that nto escaped with backticks: select firstname, lastname, date from tablename

For solving this issue I have modified the 'select' function in the system/database/DB_active_rec.php

I have just added two lines to the function which is in color and now it is working with out any problems.

function select($select = '*', $escape = NULL)
{
// Set the global value if this was sepecified
$old_val = $this->_protect_identifiers;
if (is_bool($escape))
{
$this->_protect_identifiers = $escape;
}

if (is_string($select))
{
$select = explode(',', $select);
}

foreach ($select as $val)
{
$val = trim($val);

if ($val != '')
{
$this->ar_select[] = $val;

if ($this->ar_caching === TRUE)
{
$this->ar_cache_select[] = $val;
$this->ar_cache_exists[] = 'select';
}
}
}
$this->_protect_identifiers = $old_val;
return $this;
}

Php Web Development India Articles on Articlesbase.com

Hello Readers ! !

Kindly Find Following Links for Php Website Design Website Development Articles on Articlesbase.com

Indian Php Web Development Article on Articlesbase.com

Php Web Development India Article on Articlesbase.com

These are very useful and most rated Php Web Development India Articles on Articlesbase.com provides information on various Php Web Development India Services to the User and Clients.

Thanks & Regards

www.WeTheDevelopers.com

Php Web Designers Developers Programmers Articles on Prlog.org

Hello Readers ! !

Kindly Find Following Links for Php Web Designers Developer Programmers Articles on Prlog.org

Php Web Designers Developer Programmers Article on Prlog.org


Php Web Development Company in India Article on Prlog.org


These are very useful and most rated Php Articles on Prlog.org provides information on various Php Web Development Services to the User and Clients.

Thanks & Regards

www.WeTheDevelopers.com

How PHP Works ??

Lets see how PHP works

how php works


  • Apache is a web server  application, ie it can host webpages .
  • When a user enters an Url in Browser , the browser send a request to the apache server with that file name. 
  • Apache identifies the requested  Page or file in the File System of Server. (where the file resides)
  • If its a PHP page it use PHP engine interpret the php file and generates an output
    (Sometime The PHP file will read some entries from the database server or will send a mail using the mail server)
  • The output is HTML form and Apache send it back to Web Browser
  • The webbrowser will show the HTML Code is browser in a Formatted way
    (Check the View Source Code option in Browser to see the HTML Code)