March 14 2011

Increasing demand of web development solutions for today’s businesses

Today is the technological age. Every sector and business industry needs to rely on the technology for upgrading and standing firm in the competitive world. Web designing and web development is not different from this. Lots and lots of changes are taking place in the industry and business people need to keep themselves updated to stand firm in the business.

Innovative ideas and new tools are required to get success. Old age talent is shifting towards the latest technology and beating the man power. Web solutions is in demand all where. Look at any sector, you will find the expansion and use of web development services that make them run their business smoothly. Internet banking, e commerce, online hotel booking, online ticket booking, etc. are all possible through the latest technology and web development.

With the growing need of IT services and web solutions there is increasing need of web development companies seen throughout the world. Businesses all over the world need top web development solutions for growing their business and to reach out internationally. If you are aiming for the fast online success and need web development services you should look for the software professionals who can help customize the services according to your requirements.

Effective web developers and talents know the trends of market and understand the market conditions. They aim high at providing the best possible services at best possible rates that can not only welfare them but their clients also. The ideal business people in the field employ better technology, tools and strategy to provide the satisfactory services.

Web development include various things like creative web designing, web redesigning, technical designing, etc. But the main part of the business involves making the website beautiful, attractive and appealing at first sight.
There are lots more that come in the category of development and designing.

These are:
•    Animations,
•    website design,
•    and flash design
•    custom programming,
•    photo website development,
•    ERP,
•    content management system (CMS)
•    internet marketing,
•    blog management,
•    search engine promotions
•    and much more

Website php development services are essential and most beneficial for the business of today to grow effectively in no time. it is therefore important that you choose the best company for your business by researching and comparing some of the top ones. The best web development can help you in increasing your credibility and reputation online which further is very effective in enhancing your overall business profits.

December 30 2010

Introductory PHP For Non-Programmers

PHP can be used for a lot of different things, and is one of the most powerful scripting languages available on the web. Not to mention it’s extremely cheap and widely used. However, one thing that PHP is lacking, and in fact most scripting languages are, is a way to update pages in real-time, without having to reload a page or submit a form.

The internet wasn’t made for this. The web browser closes the connection with the web server as soon as it has received all the data. This means that after this no more data can be exchanged. What if you want to do an update though? If you’re building a PHP application (e.g. a high-quality content management system), then it’d be ideal if it worked almost like a native Windows/Linux application.

But that requires real-time updates. Something that isn’t possible, or so you would think. A good example of an application that works in (almost) real-time is Google’s GMail (http://gmail.google.com). Everything is JavaScript powered, and it’s very powerful and dynamic. In fact, this is one of the biggest selling-points of GMail. What if you could have this in your own PHP websites as well? Guess what, I’m going to show you in this article.

How does it work?

If you want to execute a PHP script, you need to reload a page, submit a form, or something similar. Basically, a new connection to the server needs to be opened, and this means that the browser goes to a new page, losing the previous page. For a long while now, web developers have been using tricks to get around this, like using a 1×1 iframe, where a new PHP page is loaded, but this is far from ideal.

Now, there is a new way of executing a PHP script without having to reload the page. The basis behind this new way is a JavaScript component called the XML HTTP Request Object. See http://jibbering.com/2002/4/httprequest.html for more information about the component. It is supported in all major browsers (Internet Explorer 5.5+, Safari, Mozilla/Firefox and Opera 7.6+).

PHP is a server-side scripting language for creating dynamic Web pages. You create pages with PHP and HTML. When a visitor opens the page, the server processes the PHP commands and then sends the results to the visitor’s browser, just as with ASP or ColdFusion. Unlike ASP or ColdFusion, however, PHP is Open Source and cross-platform. PHP runs on Windows NT and many Unix versions, and it can be built as an Apache module and as a binary that can run as a CGI. When built as an Apache module, PHP is especially lightweight and speedy. Without any process creation overhead, it can return results quickly, but it doesn’t require the tuning of mod_perl to keep your server’s memory image small.

In addition to manipulating the content of your pages, PHP can also send HTTP headers. You can set cookies, manage authentication, and redirect users. It offers excellent connectivity to many databases (and ODBC), and integration with various external libraries that let you do everything from generating PDF documents to parsing XML.

PHP goes right into your Web pages, so there’s no need for a special development environment or IDE. You start a block of PHP code with . (You can also configure PHP to use ASP-style <% %> tags or even .) The PHP engine processes everything between those tags.

PHP’s language syntax is similar to C’s and Perl’s. You don’t have to declare variables before you use them, and it’s easy to create arrays and hashes (associative arrays). PHP even has some rudimentary object-oriented features, providing a helpful way to organize and encapsulate your code.

Although PHP runs fastest embedded in Apache, there are instructions on the PHP Web site for seamless setup with Microsoft IIS and Netscape Enterprise Server. If you don’t already have a copy of PHP, you can download it at the official Web site. You’ll also find a manual that documents all of PHP’s functions and features.

When you started reading this sentence you assumed lo acabaría en inglés. However, I didn’t finish in English. This begs the question, ‘In which language did I finish?’ Unless I tell you the language, you’d have to run around and compare the words against known words in order to learn that it was Spanish, but I’d bet you’d give up and move on first. Servers work much the same way; if you don’t let it know the language it assumes you’re speaking to someone else (the browser) and sends it along. Servers aren’t even friendly enough to give it a whack and see how it comes out.

So, what’s server-speak for “Here comes PHP!”? Well, it definitely looks foreign:

And, to say “OK, back to browser-speak.”, try

?>

Sure. Whatever. It’s no use telling the server you’re speaking PHP because you only know how to say “I speak PHP”. What’s that going to do for you? Well, imagine you were visiting a scripts site and wondering how you could put today’s date on your webpage when you come across the following little snippet:

To display the date on your webpage, find the area you want to put the date then insert the code below.

echo date(‘m/d/Y’);


Now, you’re equipped with 2 statements: “I’m going to be speaking PHP” and “Today’s date is mm/dd/YYYY”. You then edit the file you want to put the date in by inserting this code in the desired location:

Put the file back on the server and you’re date shows up exactly as the snippet said it would. Or does it?

If you got lucky, it showed up. If not, there’s a little more to learn. There’s actually more than one way to tell the server that PHP is coming and I’ve only covered one way – the other ways aren’t necessary for you to know in order to use PHP on your site. Most servers require a bit more information first – they want the name of the file to say whether PHP is there or not. To tell the server that PHP is inside the file, you need to change the extension (the part after the dot) to php. Uh, sure, the extension. Does this guy speak English? YEP! lol. If that wasn’t clear, let’s illustrate by assuming your file was called index.html when you downloaded it to edit. Before you upload that file back to the server, you need to change “html” to “php”, so that the file is called index.php. Without that change most servers won’t even look for PHP. The nice thing is that even if a file ends in “php”, the server still looks for those opening pieces saying “Here comes PHP!” before trying to read what follows in PHP and just sends everything back to the browser which is outside of PHP, so you don’t hurt anything!

December 17 2010

Basic Tutorial

Basic Tutorial
Tutorial Object

  • What PHP is, what a PHP file is, how PHP works, and what PHP can do for you.
  • What you need to get PHP up and running!
  • Basic PHP syntax.
Filter 
Order

Display #

Item Title Hits
A Short Intro to GD 87
Page Titles by Folder Names 47
Part 1.Introduction 122
Part 2.Your first PHP-enabled page 90
Part 3.Something Useful 83
Part 4.Dealing with Forms 79
Part 5.Using old code with new versions of PHP 67
Part 6.What’s next? 52
PHP Includes 15
Simple Solution for Php Includes – IFrames 29
<< Start < Prev 1 Next > End >>
Results 1 – 10 of 10
December 15 2010

Simple XML Parsing

Now, I may not be a pro at this XML parsing thing, nor at making the XML files themselves, but I do know that XML can be a really, really cool thing if used correctly. I’ve been working the past few months on a website that uses XML to communicate between client and server to grab information off of eBay. It’s a pretty nice little API system that lets you get all sorts of information about auctions and the like.

Now, I’m not going to get that detailed on this, I just want to give you a basic introduction to it all and get the ball rolling. Now, as always, I’m sure that this may not be the best way to parse data like this, but it sure does make it a lot easier for me to use the information out of an XML document.

First off, I’ll give you some sample XML:
<result>
<username>testing</username>
<password>foobarbaz</password>
<name>enygma</name>
</result>

Now, I know that’s not strictly “correctly formatted XML” but you get the idea. There it’s a hierarchical relationship in the tags – for each opening tag, there needs to be a closing tag, and inside of those, there can contain information. Usually, people pick good tag names that describe the information inside them. My example might be what you get back if you request something from a server (user information, for example). The “result” would contain the username, password and their name. Now, we get to the fun part – the parsing….

First off, you need to understand that the XML functions in PHP need to have four parts – the function to parse the opening tag, the function to parse the closing tag, the function to parse the “guts” of the tags (the information inside them), and the initial function that ties them all together. This last one is not completely necessary, but sure makes it nice to just pass it some XML and have it return the results.

In this example, I’m going to have the XML parser return the values in an array formatted like:

“username”=>testing
“password”=>foobarbaz
“name”=>enygma

This, as I’ve found out, is one of the more useful ways to use the information once you have it. The function can pass back the array of information
and you can then use it as you see fit. Now, there are going to be times when this just isnt enough – but those times are for another tutorial.
Anyway, on with the code!

——————————————————
<?
$info=”<result><username>testing</username><password>foobarbaz</password><name>enygma</name></result>”;
class parse{
function startElement($parser, $name, $attrs){
global $currentTag;
$currentTag=$name;
}

function endElement($parser, $tag){
global $currentTag;
$currentTag=”";
}

function getInfo($parser, $data){
global $currentTag;
$this->info_array[$currentTag]=$data;
}

function parseXML($data){
// make the parser to get the XML
$xml_parser = xml_parser_create();
xml_set_object($xml_parser, &$this);
xml_set_element_handler($xml_parser, “startElement”, “endElement”);
xml_set_character_data_handler($xml_parser, “getInfo”);
xml_parse($xml_parser, $data);
xml_parser_free($xml_parser);

print_r($this->info_array);
}
}

$parse=new parse;
$parse->parseXML($info);
?>
——————————————————

I used a class here just so that it’s easier to keep the XML paring to itself. This way, you can just include the file, call $parse->parseXML($info) like I do at the bottom, and get the results back. In this example, I take the XML that I gave you up at the top, and pass it through the needed functions to give me a nice array of the infomation as the output.

Let’s step through this so that we can see what these things do. First off, we have the “base function” called parseXML. This is where all the fun gets going. The XML stream (in this case, $info) is passed in as $data to the function. We then create the XML parser object with the xml_parser_create() function. This makes the object so that we can use it ($xml_parser). Now, the next function, xml_set_object, lets us use this object in the “parse” class. Otherwise, it would get confused and not understand that we want to use it inside the class and probably just freak out.

The xml_set_element_handler function is one of the cooler functions in the parser. It helps us define what function names we want to use for the initial element handler (opening tag) and the ending element handler (close tag). This allows us to make custom fucntions that do certain things based on which end of the XML tag we are on. You can name your two functions anything that you want, just so long as you change the second and third values in this function to match the function names. Those two functions do have very specific variables that they need to be passed, so you always have to define them like this:

function startElement($parser, $name, $attrs)
function endElement($parser, $tag)

If you don’t, not only with PHP complain about it, but it just flat out won’t work.

The xml_set_character_data_handler function is where the real meat of it all is, though. This is where you tell the XML parser what function to use for the data inside the XML tags. You can do all sorts of things with this one – but we chose to just add the current tag and it’s value to an array (made global in the class though the $this-> before it).

Almost done – stick with me! The xml_parse function takes in the $data that we passed to the function and ships it off to the parser ($xml_parse) to get taken care of. It then goes through the tags, calling startElement, getInfo, and endElement (in that order) for each tag. In our example, it adds the $currentTag (a global value) to the array with whatever value is inside that tag. The final function (xml_parser_free) is just mainly a good idea. It frees up the memory that the parser was using and “cleans up” the things we’ve done.

Well, I do hope that this has been a help to you in your XML-parsing needs. If you have any further questions, there are lots of other tutorials about that probably get more into specifics than this one did. And, as always, you’re more than welcome to email me at enygma@phpdeveloper.org.

December 2 2010

PHP On-The-Fly!

Introduction

PHP can be used for a lot of different things, and is one of the most powerful scripting languages available on the web. Not to mention it’s extremely cheap and widely used. However, one thing that PHP is lacking, and in fact most scripting languages are, is a way to update pages in real-time, without having to reload a page or submit a form.

The internet wasn’t made for this. The web browser closes the connection with the web server as soon as it has received all the data. This means that after this no more data can be exchanged. What if you want to do an update though? If you’re building a PHP application (e.g. a high-quality content management system), then it’d be ideal if it worked almost like a native Windows/Linux application.

But that requires real-time updates. Something that isn’t possible, or so you would think. A good example of an application that works in (almost) real-time is Google’s GMail (http://gmail.google.com). Everything is JavaScript powered, and it’s very powerful and dynamic. In fact, this is one of the biggest selling-points of GMail. What if you could have this in your own PHP websites as well? Guess what, I’m going to show you in this article.

How does it work?

If you want to execute a PHP script, you need to reload a page, submit a form, or something similar. Basically, a new connection to the server needs to be opened, and this means that the browser goes to a new page, losing the previous page. For a long while now, web developers have been using tricks to get around this, like using a 1×1 iframe, where a new PHP page is loaded, but this is far from ideal.

Now, there is a new way of executing a PHP script without having to reload the page. The basis behind this new way is a JavaScript component called the XML HTTP Request Object. See http://jibbering.com/2002/4/httprequest.html for more information about the component. It is supported in all major browsers (Internet Explorer 5.5+, Safari, Mozilla/Firefox and Opera 7.6+).

With this object and some custom JavaScript functions, you can create some rather impressive PHP applications. Let’s look at a first example, which dynamically updates the date/time.

Example 1

First, copy the code below and save it in a file called ‘script.js’:

var xmlhttp=false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
 try {
  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (E) {
   xmlhttp = false;
  }
 }
@end @*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
  xmlhttp = new XMLHttpRequest();
}

function loadFragmentInToElement(fragment_url, element_id) {
    var element = document.getElementById(element_id);
    element.innerHTML = '<em>Loading ...</em>';
    xmlhttp.open("GET", fragment_url);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            element.innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.send(null);
}

Then copy the code below, and paste it in a file called ‘server1.php’:

<?php
echo date("l dS of F Y h:i:s A");
?>

And finally, copy the code below, and paste it in a file called ‘client1.php’. Please note though that you need to edit the line that says ‘http://www.yourdomain.com/server1.php’ to the correct location of server1.php on your server.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN">
<html>
<head>
<title>Example 1</title>
<script src="script.js" type="text/javascript"></script>

<script type="text/javascript">
	function updatedate() {
		loadFragmentInToElement('http://www.yourdomain.com/server1.php', 'currentdate');
	}

</script>
</head>

<body>
	The current date is	<span id="currentdate"><?php echo date("l dS of F Y h:i:s A"); ?></span>.<br /><br />

	<input type="button" value="Update date" OnClick="updatedate();" />
</body>

</html>

Now go to http://www.yourdomain.com/client1.php and click on the button that says ‘Update date’. The date will update, without the page having to be reloaded. This is done with the XML HTTP Request object. This example can also be viewed online at http://www.phpit.net/demo/php%20on%20the%20fly/client1.php.

Example 2

Let’s try a more advanced example. In the following example, the visitor can enter two numbers, and they are added up by PHP (and not by JavaScript). This shows the true power of PHP and the XML HTTP Request Object.

This example uses the same script.js as in the first example, so you don’t need to create this again. First, copy the code below and paste it in a file called ‘server2.php’:

<?php

// Get numbers
$num1 = intval($_GET['num1']);
$num2 = intval($_GET['num2']);

// Return answer
echo ($num1 + $num2);

?>

And then, copy the code below, and paste it in a file called ‘client2.php’. Please note though that you need to edit the line that says ‘http://www.yourdomain.com/server2.php’ to the correct location of server2.php on your server.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN">
<html>
<head>
<title>Example 2</title>
<script src="script.js" type="text/javascript"></script>

<script type="text/javascript">
	function calc() {
		num1 = document.getElementById ('num1').value;
		num2 = document.getElementById ('num2').value;

		var element = document.getElementById('answer');
		xmlhttp.open("GET", 'http://www.yourdomain.com/server2.php?num1=' + num1 + '&num2=' + num2);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				element.value = xmlhttp.responseText;
			}
		}
	    xmlhttp.send(null);
	}
</script>
</head>

<body>
	Use the below form to add up two numbers. The answer is calculated by a PHP script, and <em>not</em> with JavaScript. What's the advantage to this? You can execute server-side scripts (PHP) without having to refresh the page.<br /><br />

	<input type="text" id="num1" size="3" /> + <input type="text" id="num2" size="3" /> = <input type="text" id="answer" size="5" />

	<input type="button" value="Calculate!" OnClick="calc();" />
</body>

</html>

When you run this example, you can add up two numbers, using PHP and no reloading at all! If you can’t get this example to work, then have a look on http://www.phpit.net/demo/php%20on%20the%20fly/client3.php to see the example online.

Any Disadvantages…?

There are only two real disadvantages to this system. First of all, anyone who has JavaScript turned off, or their browser doesn’t support the XML HTTP Request Object will not be able to run it. This means you will have to make sure that there is a non-JavaScript version, or make sure all your visitors have JavaScript enabled (e.g. an Intranet application, where you can require JS).

Another disadvantage is the fact that it breaks bookmarks. People won’t be able to bookmark your pages, if there is any dynamic content in there. But if you’re creating a PHP application (and not a PHP website), then bookmarks are probably not very useful anyway.

Conclusion

As I’ve shown you, using two very simple examples, it is entirely possible to execute PHP scripts, without having to refresh the page. I suggest you read more about the XML HTTP Request Object (http://jibbering.com/2002/4/httprequest.html) and its capabilities.

The things you can do are limitless. For example, you could create an extremely neat paging system, that doesn’t require reloading at all. Or you could create a GUI for your PHP application, which behaves exactly like Windows XP. Just think about it!

Be aware though that JavaScript must be enabled for this to work. Without JavaScript this will be completely useless. So make sure your visitors support JavaScript, or create a non-JavaScript version as well.

November 18 2010

Developing State-enabled Applications With PHP

Developing State-enabled Applications With PHPDeveloping State-enabled Applications With PHP
by: John L

Installment 1

Developing State-enabled Applications With PHP

When a user is browsing through a website and is surfing from one web page to another, sometimes the website needs to remember the actions (e.g. choices) performed by the user. For example, in a website that sells DVDs, the user typically browses through a list of DVDs and selects individual DVDs for check out at the end of the shopping session. The website needs to remember which DVDs the user has selected because the selected items needs to be presented again to the user when the user checks out. In other words, the website needs to remember the State – i.e. the selected items – of the user’s browsing activities.

However, HTTP is a Stateless protocol and is ill-equipped to handle States. A standard HTML website basically provides information to the user and a series of links that simply directs the user to other related web pages. This Stateless nature of HTTP allows the website to be replicated across many servers for load balancing purposes. A major drawback is that while browsing from one page to another, the website does not remember the State of the browsing session. This make interactivity almost impossible.

In order to increase interactivity, the developer can use the session handling features of PHP to augment the features of HTTP in order to remember the State of the browsing session. The are basically 2 ways PHP does this:

  1. Using cookies
  2. Using Sessions

The next installment discusses how to manage sessions using cookies…

Installment 2

Cookies

Cookies are used to store State-information in the browser. Browsers are allowed to keep up to 20 cookies for each domain and the values stored in the cookie cannot exceed 4 KB. If more than 20 cookies are created by the website, only the latest 20 are stored. Cookies are only suitable in instances that do not require complex session communications and are not favoured by some developers because of privacy issues. Furthermore, some users disable support for cookies at their browsers.

The following is a typical server-browser sequence of events that occur when a cookie is used:

  1. The server knows that it needs to remember the State of browsing session
  2. The server creates a cookie and uses the Set-Cookie header field in the HTTP response to pass the cookie to the browser
  3. The browser reads the cookie field in the HTTP response and stores the cookie
  4. This cookie information is passed along future browser-server communications and can be used in the PHP scripts as a variable

PHP provides a function called setcookie() to allow easy creation of cookies. The syntax for setcookie is:

int setcookie(string name, [string val], [int expiration_date], [string path], string domain, [int secure])

The parameters are:

  1. name – this is a mandatory parameter and is used subsequently to identify the cookie
  2. value – the value of the cookie – e.g. if the cookie is used to store the name of the user, the value parameter will store the actual name – e.g. John
  3. expiration_date – the lifetime of the cookie. After this date, the cookie expires and is unusable
  4. path – the path refers to the URL from which the cookie is valid and allowed
  5. domain – the domain the created the cookie and is allowed to read the contents of the cookie
  6. secure – specifies if the cookie can be sent only through a secure connection – e.g. SSL enable sessions

The following is an example that displays to the user how many times a specific web page has been displayed to the user. Copy the code below (both the php and the html) into a file with the .php extension and test it out.

[?php
//check if the $count variable has been associated with the count cookie
if (!isset($count)) {
    $count = 0;
} else {
    $count++;
}
setcookie("count", $count, time()+600, "/", "", 0);
?]

[html]
    [head]
        [title]Session Handling Using Cookies[/title]
    [/head]
    [body]
        This page has been displayed: [?=$count ?] times.
    [/body]
[/html]

The next installment discusses how to manage sessions using PHP session handling functions with cookies enabled…

Installment 3

PHP Session Handling – Cookies Enabled

Instead of storing session information at the browser through the use of cookies, the information can instead be stored at the server in session files. One session file is created and maintained for each user session. For example, if there are three concurrent users browsing the website, three session files will be created and maintained – one for each user. The session files are deleted if the session is explicitly closed by the PHP script or by a daemon garbage collection process provided by PHP. Good programming practice would call for sessions to be closed explicitly in the script.

The following is a typical server-browser sequence of events that occur when a PHP session handling is used:

  1. The server knows that it needs to remember the State of browsing session
  2. PHP generates a sssion ID and creates a session file to store future information as required by subsequent pages
  3. A cookie is generated wih the session ID at the browser
  4. This cookie that stores the session ID is transparently and automatically sent to the server for all subsequent requests to the server

The following PHP session-handling example accomplishes the same outcome as the previous cookie example. Copy the code below (both the php and the html) into a file with the .php extension and test it out.

[?php //starts a session session_start(); //informs PHP that count information needs to be remembered in the session file if (!session_is_registered("count")) { session_register("count"); $count = 0; } else { $count++; } $session_id = session_id(); ?] [html] [head] [title]PHP Session Handling – Cookie-Enabled[/title] [/head] [body] The current session id is: [?=$session_id ?] This page has been displayed: [?=$count ?] times. [/body] [/html]

A summary of the functions that PHP provides for session handling are:

  1. boolean start_session() – initializes a session
  2. string session_id([string id]) – either returns the current session id or specify the session id to be used when the session is created
  3. boolean session_register(mixed name [, mixed ...]) – registers variables to be stored in the session file. Each parameter passed in the function is a separate variable
  4. boolean session_is_registered(string variable_name) – checks if a variable has been previously registered to be stored in the session file
  5. session_unregister(string varriable_name) – unregisters a variable from the session file. Unregistered variables are no longer valid for reference in the session.
  6. session_unset() – unsets all session variables. It is important to note that all the variables remain registered.
  7. boolean session_destroy() – destroys the session. This is opposite of the start_session function.

The next installment discusses how to manage sessions using PHP session handling functions when cookies are disabled…

Installment 4

PHP Session Handling – Without Cookies

If cookies are disabled at the browser, the above example cannot work. This is because although the session file that stores all the variables is kept at the server, a cookie is still needed at the browser to store the session ID that is used to identify the session and its associated session file. The most common way around this would be to explicitly pass the session ID back to the server from the browser as a query parameter in the URL.

For example, the PHP script generates requests subsequent to the start_session call in the following format:

http://www.yourhost.com/yourphpfile.php?PHPSESSID=[actual session ID]

The following are excerpts that illustrate the discussion:

Manually building the URL:

$url = “http://www.yoursite.com/yourphppage.php?PHPSESSID=” . session_id();
[a href="[?=$url ?]“]Anchor Text[/a]

Building the URL using SID:

[a href="http://www.yoursite.com/yourphppage.php?[?=SID ?]“]Anchor Text[/a]

October 17 2010

PHP and Cookies; a Good Mix!

Introduction

Cookies have long been used in PHP scripts, and are a very useful function. But what exactly are cookies? Maybe you have used then, but you still don’t know exactly what they are. Or you are completely new to cookies? It doesn’t matter, because in this tutorial I will show you exactly what cookies are, and what they are used for.

Cookies in a nutshell

Cookies are small pieces of information that is stored on the computer of your visitors. Each browser handles it differently, but most simply store the information in a small text file. Internet Explorer has a special folder, which can be found in your C:\Windows or C:\Windows\System32 folder. You can delete all your cookies, by going to the Options and ‘Clearing Cookies’ or deleting them by hand. I don’t recommend this though.

Almost every website uses cookies. If you go to Amazon.com, you will get several cookies. The same goes for CNN.com. Even Google uses cookies! They are extremely useful for (temporarily) storing information. For example, if you have a login system for your visitors, you could save their userid and password (very heavily encrypted!) so they are automatically logged in the next time they visit your website.

Or you could remember their last visit, and highlight everything that is new. And that’s just the beginning.

Using Cookies

Using cookies in PHP is extremely easy. In fact, there is nothing to it, because of PHP’s inbuilt setcookie() function (http://php.net/setcookie). Have a look at the documentation, and then try the following example:

<?php

// Set a cookie
// Cookie name: name
// Cookie value: Dennis Pallett
// Cookie expire: in 24 hours

setcookie ('name', 'Dennis Pallett', time() + (60*60*24));
?>

If you run the code above, then a cookie will be set. That’s all. The cookie name and value are pretty obvious. The cookie expire is when the cookie expires, or goes away. Simply use the time() function (http://php.net/time) and add the number of seconds you want to have the cookie available to it. In the example I added 60*60*24=86400 seconds, or 24 hours.

If you have looked at the documentation, you probably noticed there are additional arguments. As the documentation says, the path is to limit a cookie to a specific path on your web server. This is often used when you run multiple instances of the same script in separate directories. You can safely omit this argument when it doesn’t matter if the cookie is available site-wide.

There is also the domain argument. This can be used to limit the cookie to a specific sub-domain, e.g. test.example.com. You can also safely ignore this argument, or set it to .example.com (note the beginning period, this is essential!).

Finally, there is also the secure argument. This argument is only used for cookies that are sent over a secure HTTPS connection (SSL). Just ignore this argument, unless you’re working with a secure connection.

One thing that should be mentioned is that cookies must be set, before you display any HTML/text. It’s probably best if you turn on output buffering by putting ob_start() (http://php.net/ob_start) at the top of your page.

Now that you have set a cookie, you probably want to retrieve the value as well. After all, that is the whole point of using cookies. Thankfully, as PHP is ever so easy, you can retrieve the same way as you retrieve a GET value. See the following example to retrieve the value of the previous example:

<?php
echo 'Your name is ' . $_COOKIE['name'];
?>

This should print “Your name is Dennis Pallett”. There’s nothing more to it. It’s just that easy!

Finally, one thing you probably want to do as well is remove cookies. This is as easy as setting them. Simply change the value of the cookie to FALSE, and change the expire date to -3000 seconds. See the following example:

<?php
setcookie ('name', FALSE, time()-1000);
?>

Checking if cookies are enabled

Before you start using cookies, you must make sure your visitor has cookies enabled. This can be done with a simply PHP checking script. Unfortunately, the PHP page needs to reload to check for cookies. But this can be done very transparently, and your visitor should hardly notice anything.

The following example will first set a test cookie, then reload the page, and finally check whether cookies are enabled.

<?php
error_reporting (E_ALL ^ E_WARNING ^ E_NOTICE);

// Check if cookie has been set or not
if ($_GET['set'] != 'yes') {
	// Set cookie
	setcookie ('test', 'test', time() + 60);

	// Reload page
	header ("Location: checkcookies.php?set=yes");
} else {
	// Check if cookie exists
	if (!empty($_COOKIE['test'])) {
		echo "Cookies are enabled on your browser";
	} else {
		echo "Cookies are <b>NOT</b> enabled on your browser";
	}
}
?>

Run the code above, and see what the output is. Check if cookies are enabled in your browser. If they’re not enabled, then you can enable them by going to your browser’s options. Unfortunately, this is different from each browser, so I can’t give you exact instructions. But Google can.

Storing Arrays

One feature of cookies that is often missed in articles is the ability to story arrays. Cookies can be used to store multi-dimensional arrays, which can be extremely useful to store data.

Consider the following code;

<?php
setcookie ("name[first]", "Dennis", time() + (60*60*24));
setcookie ("name[last]", "Pallett", time() + (60*60*24));
?>

You can then display these two cookies using the following code:

<?php
echo "First Name: " . $_COOKIE['name']['first'];
echo "<br />Last Name: " . $_COOKIE['name']['last'];
?>

The cookie ‘name’ is an array, and has multiple values. You can even go deeper and have multi-dimensional arrays, e.g. $_COOKIE['name']['test']['something']['value']. You could store whole arrays of data in cookies. But beware that you don’t store too much data, there are certain size limits to cookies.

In Conclusion…

Cookies are really versatile, and can be used for a lot of different purposes. Many websites use cookies, and cookies can really make your website more personalized. Using cookies in PHP isn’t hard at all, and you should be able to use them without any difficulty.

Before actively using cookies in your website, you must check whether the visitor has enabled them in their browser. If they don’t have cookies enabled, you must either redirect to a non-cookies version of your website, or you can make sure your website also works without cookies.

You can download a sample script at http://www.phpit.net/demo/php%20and%20cookies/logger.zip, where cookies are used in a (somewhat) practical way. In this example, there is a logging module, called log.php and a display module, called history.php. Basically, you include the log.php in other PHP pages, and then you can view history.php to lookup all the pages you have viewed and how often. The example uses arrays, and stores them in cookies.

The examples in this article can be downloaded at http://www.phpit.net/demo/php%20and%20cookies/examples.zip.

If you have a really unique practical way of using cookies, please let me know at dennis [AT] nocertainty [DOT] com. I’d really like to hear about interesting ways of using cookies.

May 30 2010

Your first PHP-enabled page

Create a file named hello.php and put it in your web server’s root directory (DOCUMENT_ROOT) with the following content:

Example 2-1. Our first PHP script: hello.php

<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>

Use your browser to access the file with your web server’s URL, ending with the “/hello.php” file reference. When developing locally this URL will be something like http://localhost/hello.php or http://127.0.0.1/hello.php but this depends on the web server’s configuration. If everything is configured correctly, this file will be parsed by PHP and the following output will be sent to your browser:

<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
 <p>Hello World</p>
 </body>
</html>

This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display: Hello World using the PHP echo() statement. Note that the file does not need to be executable or special in any way. The server finds out that this file needs to be interpreted by PHP because you used the “.php” extension, which the server is configured to pass on to PHP. Think of this as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things.

If you tried this example and it did not output anything, it prompted for download, or you see the whole file as text, chances are that the server you are on does not have PHP enabled, or is not configured properly. Ask your administrator to enable it for you using the Installation chapter of the manual. If you are developing locally, also read the installation chapter to make sure everything is configured properly. Make sure that you access the file via http with the server providing you the output. If you just call up the file from your file system, then it will not be parsed by PHP. If the problems persist anyway, do not hesitate to use one of the many PHP support options.

The point of the example is to show the special PHP tag format. In this example we used <?php to indicate the start of a PHP tag. Then we put the PHP statement and left PHP mode by adding the closing tag, ?>. You may jump in and out of PHP mode in an HTML file like this anywhere you want. For more details, read the manual section on the basic PHP syntax.

A Note on Text Editors: There are many text editors and Integrated Development Environments (IDEs) that you can use to create, edit and manage PHP files. A partial list of these tools is maintained at PHP Editors List. If you wish to recommend an editor, please visit the above page and ask the page maintainer to add the editor to the list. Having an editor with syntax highlighting can be helpful.

A Note on Word Processors: Word processors such as StarOffice Writer, Microsoft Word and Abiword are not optimal for editing PHP files. If you wish to use one for this test script, you must ensure that you save the file as plain text or PHP will not be able to read and execute the script.

A Note on Windows Notepad: If you are writing your PHP scripts using Windows Notepad, you will need to ensure that your files are saved with the .php extension. (Notepad adds a .txt extension to files automatically unless you take one of the following steps to prevent it.) When you save the file and are prompted to provide a name for the file, place the filename in quotes (i.e. “hello.php“). Alternatively, you can click on the ‘Text Documents’ drop-down menu in the ‘Save’ dialog box and change the setting to “All Files”. You can then enter your filename without quotes.

Now that you have successfully created a working PHP script, it is time to create the most famous PHP script! Make a call to the phpinfo() function and you will see a lot of useful information about your system and setup such as available predefined variables, loaded PHP modules, and configuration settings. Take some time and review this important information.

Example 2-2. Get system information from PHP

<?php phpinfo(); ?>

December 5 2009

Sample script with PHP-CGI

Well, as a follow-up to our PHPCGI tutorial that showed you how to install the PHP files as a CGI program on your server, we wanted to get a bit more into some of the details of using it and running scripts automatically with it. Once again, we’re going to assume that it’s a UNIX-based operating system you’re working on. This is much easier to get working than a Windows based machine (well, for me anyway) and cron just does such a good job, we’re going to stick with it. <p> Anyway, for those out there that aren’t too linux-literate and aren’t exactly sure how to set up a cron job, we’re here to help. I’m going to give you a crash course in setting them up and then show you how to get a nice little PHP script working with it. This will let you make some nice scripts and allow you to (possibly) transfer some of the admin portions of your site to a well-written PHP script in a cron job.

So, on with cron: cron is actaully the name of the daemon that any good sysadmin runs on their systems to make their lives easier. For the most part, the server you’re working on should have the cron daemon running and working properly. Otherwise, you’ll need to contact your friendly neighborhood sysadmin and get them to fix what they broke. Once you’re sure that they have it up and working (if it wasn’t in the first place), then you can go on from here.

The cron daemon looks at something called the “crontab” to get the scripts and their parameters that it needs to run. You set all of this info in one place – the script to be run and the time(s) when this needs to be done. The syntax for the crontab is pretty easy to figure out and can be accessed easily with the following command:

crontab -e

This should bring up your crontab file. Most likely, unless you’ve messed with cron stuff before (in which case you probably wouldn’t be reading this). You now have a nice clean crontab to mess with. Now, the fun of the syntax – the fields go in this order and are separated by spaces: minute, hour, day of month, month, day of week, then the script to be run. Now, this is all well and good, but how do you actually use it to make a script run? Well, it’s pretty simple really. For example:

5 0 * * * /bin/ls

would run the “ls” command every day at five minutes after midnight. There are tons of combinations that you can have for all of the times and numbers you can put in. For more info on that, check out the “man 5 crontab” command and read the info in there. Now, obviously this is kind of a silly example, but that’s all it is. Now, we’ll show you how it can actually be useful.

Say we have a site that, each night at five after midnight, you want it to send out emails to everyone that has some kind of money due by the end of the next day. We have our PHP script:

<?php
$sql=mysql_connect(“localhost”,”username”,”password”);
$fetch=mysql_query(“select * from users where balance_due>1000);
// insert more useful code here
?>

You get the idea…the code that’s in the file isn’t the important part right now. What’s important is having it set up right with the cron job. Now, if we use our example from above (and assume that PHP is already compiled as a CGI), then we can safely set this in the crontab:

5 0 * * * /usr/local/bin/php /path/to/file.php

You’ll have to substitute your locations and all when you get those pinned down, but other than that, that should be all that you need. You should now have a PHP script that updates your database nightly at 12:05 (00:05 for you 24-hr buffs, hence the 0). There are tons of neat uses for this besides getting updates to run and all, but this is one of the main ones that I’ve found it used for.
Enjoy!

www