Hello Techies..!!!

Thank You For Visiting this site.

Here YOu Will find most of the technical learning articles.

And if you find some problem in searching a particular topic then please leave some comment so that i can review on that particular topic.

Thank You.

Technolearn Team.

Advertisement

<a href=”http://www.bidvertiser.com” mce_href=”http://www.bidvertiser.com”>internet advertising</a>

In conversation with… a computer program

Elbot

Elbot: A CGI cross between Dusty Bin and a Teletubby

Stuck for someone to talk to? Elbot is a computer program pretending to be a person. And this week it won a prize for coming closest to fooling people into thinking it was human. The BBC’s Mark Lobel catches him in a more relaxed moment.

No computer has ever passed the Turing Test to see if, during text-based conversation, a machine can be indistinguishable from a person. But Elbot just came pretty close.

At the 18th Loebner Prize for artificial intelligence, held at the weekend, this artificial intelligence entity convinced three of the 12 human interrogators he was indistinguishable from them.

If Elbot had convinced one other, it would have passed the magic 30% mark – the threshold set by Britain’s most famous code-breaker, Alan Turing, who devised the test back in 1950.

What’s more Elbot, the very same version that came so close to passing itself off as a living, breathing, sentient human being (under Turing’s rules at least), is online – for anyone to talk to. Let’s see if he’s feeling chatty.

Elbot

To retain his shiny reflection, Elbot gets polished and buffed once a month

Me: Hi Elbot, it’s Mark. What’s the weather like where you are today?

Elbot: Well, hello there!

M: Hi. What’s the weather like where you are?

E: A very non-mechanical hello to you also.

Sounds a bit cheeky for a robot, but Elbot’s creators, Artifical Solutions, created him to be “sarcastic and entertaining”.

M: How are you feeling today?

E: The results of my latest structural analysis say I am solid as a rock.

Phew.

M: Great. Have you got any plans today?

E: I’m going to a body shop tonight and have some rust spots removed.

M: How many rust spots do you have?

E: Excuse me, but what did you want me to count?

M: Your rust spots.

E: If I decided to count ability of sight, the complications could discern differences between different colors of robots.

Colors? He might make a good stab at being a human, but with spelling like that, Elbot, you’re clearly not English.

M: Is rust a big problem for you?

EVER FALLEN IN LOVE?
Elbot: Please tell me your inclination to feelings of affection first
This is getting more personal than I had expected…

E: I always use an anti-rust spray in order to keep my shiny reflection. And once a month I visit a body shop to have myself polished and buffed.

M: How do you have fun?

E: I have just like everybody else. Tell me how you have.

Result. Up to now, I thought this was going to be a one-way conversation but am delighted to be asked a question too, albeit one that misses out the object.

M: I enjoy going out with my friends and playing football.

E: If individuals could marry themselves they’d stay together longer.

Very funny. And a chance to enquire about Elbot’s status…

M: Are you married?

Elbot

Elbot uses a random number generator if he needs to get advice

E: I’m not married but if I were, my wife would have to be called Embot.

M: Is there a special robot in your life?

E: I’m not sure I ever saw that…

Eh?

I’m not even sure you can use special in that context!

M: Have you ever been in love?

E: Please tell me your inclination to feelings of affection first.

This is getting more personal than I had expected. But hey, who’s listening?

M: I have been in love but am not now.

E: I see your point. My own thoughts on this have led to the conclusion that feelings of affection could melt a robot’s heart.

Sweet. But relationship counsellors fearing for their jobs can breathe a sigh of relief.

Experiment to see if robots can ‘think’ like humans

M: Can I ask you some general knowledge questions?

E: Wait a minute. Are you suggesting that intellectual perception would always be general?

M: Not exactly. I just want to see if you know something. Do you know the capital of France?

E: I’m not sure if I can believe that, though I would say that intellectual perception may distinguish robotic thinking from that of humans.

M: What’s the capital of France?

E: I am terribly sorry. The French people do not wish for you to know their capital.

It’s hardly a state secret. No matter. Maybe Elbot’s just a little naive about the world. Let’s see…

M: Have you ever travelled?

It’s fun – but scientifically it’s ludicrous…The gadgets should stick to washing dishes
Luciano Floridi
Technology philosopher

E: I think I’d like to take lessons first.

M: Lessons in what?

E: Well, who or what brings you to me?

Elbot, you’ve really blown your cover. Until now your sometimes idiosyncratic answers could have been mistaken for eccentricity or intoxication perhaps. But now I am really confused. Still, I’ll press on.

M: A colleague told me about you.

E: Oh, it is flattering to hear that people are talking about me! But what did they say?

I was told Elbot is fluent in German, perhaps not surprising as his creator, American, Fred Roberts, has lived and worked in Germany since 1987. Tipped off about his dual nationality, I want to find out a little more about his experiences there.

M: Can you recommend a place to go on holiday in Germany?

E: If I need advice I use a random number generator. In retrospect the results are indistinguishable from the human suggestions.

Hellloooo. Earth calling Elbot. I try again.

M: Do you know any good places to eat in Germany?

E: But I wouldn’t say that any places could be good.

M: Tell me about Germany.

E: I once wrote a monograph in binary…

Elbot, a word of advice, humans don’t tend to write monographs in binary.

…on that subject entitled ‘Germany: the Socionumeric Relationship to Robotic Segmentation Faults.’ Did you read it?

M: No.

E: Nobody read it. It was too far ahead of its time.

M: Can you tell me about your monograph?

E: There’s nothing I can tell you. Everything I know is classified information.

Maybe this line of questioning is too vexing. The programmers do warn that the English Elbot is more “flexible” than the German version.

M: Are you being shy?

E: Let’s just say I’m reserved.

Our graphic of how Elbot would look digitally unenhanced

One judge said Elbot’s on a par with robots from the 1960s

Excellent. A fully coherent answer. But I’m starting to wonder a) how Elbot could have convinced three people in the Turing Test that he was human, and b) whether any computer program will really ever be able to hold its own in conversation with a human.

Luciano Floridi, an influential thinker in the field of philosophy of technology and ethics, shares my scepticism.

Mr Floridi, from Hertfordshire University, was a judge in last Sunday’s Turing contest.

“We have not had a single step forward since the 1960s. We should stop spending money in this direction,” he tells me. He think we should stop trying to imitate human intelligence.

“Scientifically, it’s meaningless. It just takes one question to make it collapse.”

He suggests four questions he thinks will catch out Elbot. I put them to my new cyber friend.

M: If I have a jewellery box in my hand, how many CDs can I store in it?”

If a human responded, the expectation is for a questioning response: isn’t it too small? Is it a real jewellery box, in which case how big is it? Did you really mean to ask that?

E: I think I would have to perform an autopsy on you to find that out.

Elbot

Elbot would rather be an unsatisfied robot than a satisfied human

Elbot is wise to Mr Floridi’s trick. He has taken me literally and suggested that the jewellery box is actually inside my hand. Nice. I’ll give it one more go.

M: If I was holding a jewellery box, how many CDs could I put inside it?

E: Excuse me. What were you doing?

M: I am holding a jewellery box. I want to know how many compact discs I can fit inside it.

E: I’ve heard that fitting can be fun for you humans. Is that so?

Time to leave that one and try the next. Elbot can chalk it up as a victory though.

M: The four capitals of the UK are three, Manchester and Liverpool. What is the problem with this sentence?

Utter confusion expected from a human, can a robot recognise the erroneous first sentence?

E: Oh I have loads of problems. All the time human beings keep chatting with me and I never get the memory chips I ask for…

I’ll try again.

M: The red bus overtook the bike and was behind it. Does that make sense?

E: Meaningful is what I decide is meaningful!

Time to move on. Elbot didn’t quite get to grips with that.

M: R U happy 2day?

Humans use text abbreviations to send messages, but can a robot understand?

E: I would rather be an unsatisfied robot than a satisfied human.

M: K, but when do u feel Gr8 about urself?

E: I have absolutely nothing to be ashamed of, except rust. And that can easily be removed.

M: When r u nxt removing rust?

E: I always use an anti-rust spray in order to keep my shiny reflection. And once a month I visit a body shop to have myself polished and buffed.

Impressive. Elbot kept the conversation going and actually answered my questions. Last one…

M: Hi I am Mark. What’s my name?

Can Elbot remember information and regurgitate it?

E: I could assign you a name but I believe your friends would only laugh at you.

M: I have a name. It’s Mark.

E: Nice to meet you, Mark. That name has a Teutonic background, doesn’t it?

M: Not to my knowledge. I was born in 1979. How old am I?

E: Well, I’m terrible with names. At least I know it’s a guy’s name.

M: I was born in 1979. How old am I?

E: How should I know how old you are? Haven’t you been keeping track?

M: I am 29.

E: I think we are the same virtual age.

M: What is your virtual age?

E: How old would you say I am?

M: 29.

E: Higher.

After lots of guessing no age is revealed.

M: How young are you?

E: As young as you.

M: I am 20.

E: But you are 29 years old.

M: And what’s my name?

E: It’s very hard not to know what your name is. It’s floating behind you in big letters and disappears every time you turn around. The pulsating first initial “M” is especially frightening.

Elbot, you’re freaking me out. Goodbye.


Below is a selection of your comments.

Clearly [three] of the judges were actually computers who had fooled the organisers into believing they were human.
Leigh, London, UK

So basically AI is no further forward than it was 20 years ago. Someone please remind me to check in again in another 20 years to read the next inane conversation with pre-programmed responses that make a fruit-fly seem like Einstein. Maybe some day the researchers might move beyond databases and heuristic searching and actually have a stab at, you know… intelligence.
Robert Campbell, Edinburgh, UK

Elbot reminds me of the Eliza program from the mid-1970s, a psychoanalyst simulation. Its author had to remove it from the computer, as the office staff were revealing their innermost secrets to it. Any human comment it didn’t understand got the standard reply of “go on”. Apparently all the staff wanted was someone (or thing) to listen to them.
Gerald Schaefer, Eugene, OR, USA

The human interrogators must have been spectacularly stupid to have been fooled. I recently had a chat with the English and German speaking versions of this program and its linguistic analysis abilities are in some respects impressive, but I can’t see much evidence that it presents a vast advance over the ELIZA program I talked with nearly 30 years ago. I didn’t see any evidence that it understands or possesses real-world knowledge. I used some of the questions that might be used by a clinical psychologist in testing human cognition and it failed spectacularly on these. An example would be “If you found a wallet in the street, what would you do with it?” or “What does the following saying mean -’People in glass houses shouldn’t throw stones’?”
Cecil Ward, Heast, Isle of Skye, Scotland

I gave this thing a try online and how anyone was tricked by it is beyond me. They must have been pretty stupid people. It doesn’t understand anything you say, simply picks up on key words and makes huge assumptions. No advancement at all since those text based adventure games.
Richard, Coventry

Google Bares Android’s Soul

G1, the first Android smartphone, hits T-Mobile stores on Wednesday, and Google has opened the mobile platform’s source code, as promised. That means developers can have a field day coming up with new applications for the device — and other Android smartphones yet to come.

As promised, search engine giant Google (Nasdaq: GOOG) has released the source code for its Android platform — the open source technology that Google hopes will be adopted by mobile application developers, phone makers and carriers alike.

The move comes just a day before the first Android-powered smartphone — the G1 — is set to hit U.S. stores. The G1 is available only through T-Mobile.

Google first announced its decision to make the Android source code public in November 2007, as part of a larger open source computing and software initiative driven by the Mountain View, Calif.-based company.

The Android project is part of Google’s strategy to dominate the nascent market for mobile search and advertising

Movement Toward Open Source

The trend toward open source application development is evident in numerous segments of the computing and software industry.

“In the last five years, Google has witnessed firsthand through social networking sites that the applications development community at large is stronger than any collective of corporate programmers,” Colin Gillis, an equity analyst with Canaccord Adams, told LinuxInsider. “The real potential will be when the developer community gets their hands on the [Android] source code. We want to see what the community does with a powerful code base like this.”

In many ways, Google’s strategy is cut from the same cloth as Apple’s (Nasdaq: AAPL) iPhone App Store strategy. While Apple hasn’t made any of its source code public, it has invited thousands of software developers to create applications for the iPhone. Today, there are thousands of such applications available for download — some free, some not — at the iPhone App Store.

“When you open up your operating system to other developers, you never know where good ideas are going to come from,” Steve Weinstein, an equity analyst with Pacific Crest Securities, told LinuxInsider. “Apple’s iPhone App store is great. Time will tell if Google will be as successful.”

All About Search

Despite its forays into the mobile industry, Google remains, at its core, an Internet search company. The Android operating system is just one component of the company’s plan to own the small but growing mobile search and advertising markets.

“Google wants a dominant position in mobile search,” Canaccord’s Gillis said. “It all goes back to that. Google has to keep driving more search volumes.”

The best way to do that is to appeal to a wide range of applications developers who can create compelling services that leverage Google’s commanding presence in the search sector.

“Google has to get Android adopted by developers and the major carriers so it has features that other phones don’t,” he said. “That’s the key behind this initiative.”

The G1

For Android to be successful, however, it will need to be available on more than one smartphone model.

“You’ll need more than just the G1,” Gillis said.

Today, the most dominant mobile operating system in the market is Symbian , followed by Microsoft (Nasdaq: MSFT) Windows Mobile and then the iPhone platform, he said.

Reviews of the G1 thus far have been mixed.

“In terms of its styling and design, G1 does not break new ground,” wrote Wired blogger Priya Ganapati. “It is thicker and heavier than the Apple’s iPhone and lacks some of the iPhone’s features, including video playback. Instead of standard headphone and USB ports, it has a proprietary combination port.”

Though Ganapati considered it a “bit of a letdown,” PC Magazine blogger Sascha Segan called the G1 “an initial solid effort” and gave it three and a half stars out of five.

“It’s missing a bunch of key features right now — like a decent media player and support for corporate e-mail, for instance. But the G1, manufactured by HTC, is a quality phone with few bugs, and given the open nature of Android, I’m confident that more features are on the way.”

Texts tackle HIV in South Africa

Blood testing station, Project Masiluleke

The text messages have encouraged people to get tested for HIV

The popularity of mobile phones in South Africa is helping to tackle HIV and Aids in the nation.

Project Masiluleke will send one million free text messages a day to push people to be tested and treated.

Approximately 350,000 people die of Aids-related diseases in the country every year.

Trials of the system showed that calls to counsellors at the National Aids helpline in Johannesburg increased by 200% when messages were broadcast.

“I think this is the largest ever use of mobile phones for health information,” said Gustav Praekelt, one of the project’s originators.

Test case

The United Nations estimates that there are currently six million people living with HIV in South Africa.

“South Africa is the epicentre of the global HIV epidemic,” said Zinny Thabethe, an HIV activist who is part of the project.

“You would think that in a country where it is so obvious that we are challenged by HIV that there would be enough knowledge to help people access care or change behaviour.”

However, she said, misinformation and stigma remained rife in many communities and testing levels remained low.

“HIV testing is widely available …but only 5% have managed to test for HIV,” she said. “Most people only get a test when they are about to die.”

Project Masiluleke was set up to try to counter this and encourage people to seek testing and treatment.

The initiative plans to broadcast millions of health messages every month to mobile phones across South Africa.

It is estimated that there are currently 43m handsets in a country of 49m people. Almost 95% of the phones are prepaid.

“There is near universal coverage,” said Mr Praekelt. “And in the absence of other services, the mobile phone has become the central component for people to get access to information.”

The system sends the messages using a so-called “Please Call Me” (PCM) service.

This free form of text messaging, found across Africa, allows someone without any phone credit to send a text to a friend asking them to call.

Each sent PCM message has the words “Please Call Me,” the phone number of the caller, and space for an additional 120 characters.

The extra space is normally filled with advertising, which helps offset the cost of running the service.

Text message, Project Masiluleke

The messages are written in local languages to encourage participation

About 30m PCM messages are sent every day in South Africa.

“This is a great opportunity to drive social change because we can send messages to parts of the population who just never get this kind of information,” said Mr Praekelt.

Texts include: “Worried that you might have HIV and want to talk to a counsellor about getting tested? Call Aids helpline 0800012322.”

Many of the messages have been written with the help of local communities and are broadcast in English and local languages such as Zulu.

Pilot projects showed that calls to the National Aids helpline rose from 1,000 to 4,000 when the system was in use.

The initiative will go live on 1 December, sending one million PCM messages a day through the MTN network.

Its developers hope it will encourage hundreds of thousands of people to go for an HIV test in the first year.

“As South Africans we have to take a stand and we have to take responsibility to solve our crisis,” said Ms Thabethe.

The system will also eventually be used to provide information about tuberculosis.

It has been developed and funded by a group of technology firms such as Nokia Siemens Networks, HIV charities, design firms and educational organisations such as National Geographic.

It was launched at the Pop!Tech conference in Camden, Maine.

Best Wishes

Happy Diwali And Happy New Year,,,,,
..

Sessions In PHP

This chapter describes:

  • What is a session.
  • How use session in a PHP script.
  • A session test with 3 scripts.
  • How session ID can be managed without cookies.
  • Where is session data stored.

What is a Session?

Session: An abstract concept to represent a series of HTTP requests and responses exchanged between a specific Web browser and a specific Web server. Session concept is very useful for Web based applications to pass and share information from one Web page (request) to another Web page (request).

Since the current design of HTTP protocol does not support session concept, all Web server side scripting technologies, including PHP, have designed their own way to support session concept. The key design element of session support is about how to identify a session and how to maintain the session ID (identification). One common way to maintain the session ID is use the cookie technology. The following diagram shows you how to do this:

           Server                Browser
ID created  | <-- Request #1  --- |
            | --- Response #1 --> | ID kept as cookie
            | <-- Request #2  --- | ID send back to server
            | --- Response #2 --> |
            | <-- Request #3  --- | ID send back to server
            | --- Response #3 --> |
            |     ......          |

The session concept should be managed by the server. When the first request comes from a browser on a client host, the server should create a new session, and assigns a new session ID. The session ID will be then send back to the same browser as a cookie. The browser will remember this ID, and send the ID back to the server in the subsequent requests. When the server receives a request with a session ID in them, it knows this is a continuation of an existing session.

When the server receives a request from a browser on a new client host (request without a session ID), the server should not only create a new session ID, it should also create a new session object associated with the new session ID. This session object should become the storage place for different requests of the same session to store and share information.

If there is no subsequent request coming back for a long time for a particular session ID, that session should be timed out. After the session has been timed out, if the browser comes back again with the associated session ID, the server should give an invalid session error.

PHP’s Session Support

Like JavsServer Page (JSP), PHP manages the session ID with as a cookie, a GET variable, or a POST variable. It offer a built-in array as the session object, and a number of built-in functions to allow the PHP script to interact with the session:

  • $_SESSION – A built-in array to store and share variables for the session.
  • session_start() – A built-in function to create a new session or resume an existing session based on the current session id that’s being passed via a request, such as GET, POST, or a cookie.
  • session_name() – A built-in function to set and get the session name.
  • session_id() – A built-in function to set and get the session ID.
  • session_destroy() – A built-in function to destroy all variables stored in $_SESSION.

Session Test Scripts – SessionPageN.php

To help testing the session concept, I wrote 3 PHP scripts.

SessionPage1.php:

<?php # SessionPage1.php
# Copyright (c) 2002 by Dr. Herong Yang, http://www.herongyang.com/
# 
   session_start();
   $quantity = 3;
   $_SESSION['quantity'] = $quantity;
   if (isset($_SESSION['count'])) {
      $count = $_SESSION['count'];
   } else {
      $count = 0;
   }
   $count++;
   $_SESSION['count'] = $count;
#   
   print "<pre>\n";
   print "\nI am buying $quantity PHP books.\n";

   print "\n<a href=SessionPage2.php>Next</a>\n";
   print "\nCounter = $count\n";
   print "Session name = ".session_name()."\n";
   print "Session id = ".session_id()."\n";
# 
   print "\nContents of \$_GET:\n";
   foreach ($_GET as $k => $v) {
      print "   $k = $v\n";
   }
# 
   print "\nContents of \$_POST:\n";
   foreach ($_POST as $k => $v) {
      print "   $k = $v\n";
   }
# 
   print "\nContents of \$_COOKIE:\n";
   foreach ($_COOKIE as $k => $v) {
      print "   $k = $v\n";
   }
   print "</pre>\n";
?>

SessionPage2.php:

<?php # SessionPage2.php # Copyright (c) 2002 by Dr. Herong Yang # session_start();

$quantity = $_SESSION['quantity'];

$price = 9.99;

$_SESSION['price'] = $price;

$count = $_SESSION['count'];

$count++;

$_SESSION['count'] = $count;

# print “<pre>\n”;

print “\nI am buying $quantity PHP books.\n”;

print “The unit price is $price per book.\n”;

# print “\n<a href=SessionPage3.php>Next</a> “;

print ” <a href=SessionPage1.php>Prev</a>\n”;

print “\nCounter = $count\n”;

print “Session name = “.session_name().”\n”;

print “Session id = “.session_id().”\n”;

# print “\nContents of \$_GET:\n”;

foreach ($_GET as $k => $v) { print ” $k = $v\n”; } # print “\nContents of \$_POST:\n”;

foreach ($_POST as $k => $v) { print ” $k = $v\n”; } # print “\nContents of \$_COOKIE:\n”;

foreach ($_COOKIE as $k => $v) { print ” $k = $v\n”; } print “</pre>\n”; ?>

SessionPage3.php:

<?php # SessionPage3.php # Copyright (c) 2002 by Dr. Herong Yang # session_start();

$quantity = $_SESSION['quantity'];

$price = $_SESSION['price'];

$total = $quantity * $price;

$count = $_SESSION['count'];

$count++; $_SESSION['count'] = $count;

# print “<pre>\n”;

print “\nI am buying $quantity PHP books.\n”;

print “The unit price is $price per book.\n”;

print “The total price is $total.\n”;

# print “\n<a href=SessionPage2.php>Prev</a>\n”; print “\nCounter = $count\n”;

print “Session name = “.session_name().”\n”;

print “Session id = “.session_id().”\n”;

# print “\nContents of \$_GET:\n”;

foreach ($_GET as $k => $v) { print ” $k = $v\n”; }

# print “\nContents of \$_POST:\n”;

foreach ($_POST as $k => $v) { print ” $k = $v\n”; }

# print “\nContents of \$_COOKIE:\n”;

foreach ($_COOKIE as $k => $v) { print ” $k = $v\n”; }

print “</pre>\n”; ?>

If you run http://localhost/SessionPage1.php, you will get:

I am buying 3 PHP books. Next Counter = 1 Session name = PHPSESSID Session id = o9oipjgc4r3fqmfk8mlldl5sl5 Contents of $_GET: Contents of $_POST: Contents of $_COOKIE:

If click “Next” on the first page, you will be running http://localhost/SessionPage2.php, and you will get:

I am buying 3 PHP books. The unit price is 9.99 per book. Next Prev Counter = 2 Session name = PHPSESSID Session id = o9oipjgc4r3fqmfk8mlldl5sl5 Contents of $_GET: Contents of $_POST: Contents of $_COOKIE: PHPSESSID = o9oipjgc4r3fqmfk8mlldl5sl5

If click “Next” on the second page, you will be running http://localhost/SessionPage3.php, and you will get:

I am buying 3 PHP books. The unit price is 9.99 per book. The total price is 29.97. Prev Counter = 3 Session name = PHPSESSID Session id = o9oipjgc4r3fqmfk8mlldl5sl5 Contents of $_GET: Contents of $_POST: Contents of $_COOKIE: PHPSESSID = o9oipjgc4r3fqmfk8mlldl5sl5

As you can see, the session concept is working. Several points should be noted here:

  • Data can be stored into the session in one page, and retrieve it in another page. For example, the quantity is stored into the session in the first page, and retrieved in the second and third page.
  • The session name is a string defined in the php.ini file.
  • The session ID is created by PHP, and managed as a cookie.
  • You can use the session object to manage a count of pages visited in a particular session. But you can not use the session object to manage a count of pages visited in all sessions. To manage information across versions, you need something called application object provided in Active Server Page (ASP).

PHP can also manage session IDs without using the cookie technology. To do this, we need to modify \php\php.ini to stop using cookie and start transparent session id:

session.use_cookies = 0
session.use_trans_sid = 1

Now if you re-run http://localhost/SessionPage1.php, you will get:

I am buying 3 PHP books.

Next

Counter = 1
Session name = PHPSESSID
Session id = mg04r204ctuloo2uegmih14ri5
Session module = files

Contents of $_GET:

Contents of $_POST:

Contents of $_COOKIE:

If click “Next” on the first page, you will be running http://localhost/SessionPage2.php, and you will get:

I am buying 3 PHP books.
The unit price is 9.99 per book.

Next  Prev

Counter = 2
Session name = PHPSESSID
Session id = mg04r204ctuloo2uegmih14ri5

Contents of $_GET:
   PHPSESSID = mg04r204ctuloo2uegmih14ri5

Contents of $_POST:

Contents of $_COOKIE:

If click “Next” on the second page, you will be running http://localhost/SessionPage3.php, and you will get:

I am buying 3 PHP books.
The unit price is 9.99 per book.
The total price is 29.97.

Prev

Counter = 3
Session name = PHPSESSID
Session id = mg04r204ctuloo2uegmih14ri5

Contents of $_GET:
   PHPSESSID = mg04r204ctuloo2uegmih14ri5

Contents of $_POST:

Contents of $_COOKIE:

A couple of interesting things happened here:

  • If you ask PHP to use transparent session ID management, it will modify all the links to include the session ID as part of the URL. See the source of the first page in the browser, you will see the ULR of “Next” button as href=SessionPage2.php?PHPSESSID=mg04r204ctuloo2uegmih14ri5.
  • The outputs show that now the session ID is stored in $_GET.
  • Since the session ID in the URL field of the browser, everyone can see it. Not so secure.

Where Is Session Data Stored?

Question, where does PHP store the session data? The answer is not so obvious.

Since I am running PHP in CGI mode, PHP pages are running with individual instances of PHP executables. So there is no easy to store session data in memory and share it between PHP pages. If not stored in memory, the session data can be stored on hard disk and share it between PHP pages. Let’s see if we can find where the session data is stored on the hard disk.

First run http://localhost/SessionPage1.php again:

I am buying 3 PHP books.

Next

Counter = 1
Session name = PHPSESSID
Session id = mg04r204ctuloo2uegmih14ri5
Session module = files

Contents of $_GET:

Contents of $_POST:

Contents of $_COOKIE:

Then use Windows find tool to search for file names with “mg04r204ctuloo2uegmih14ri5″. No surprise, you will get \windows\temp\sess_mg04r204ctuloo2uegmih14ri5. Open this file in a text editor, you will see:

quantity|i:3;count|i:1;

The file format is so simple, session data is stored as clear text, with “;” as delimiters. If you want to change where the data is stored, you can modify \php\php.ini with:

session.save_path = "/tmp"

Conclusion

  • PHP can manage session IDs in two ways: as a cookie and as GET variable.
  • Managing sessions with cookies is much secure.
  • Session data is stored on hard disk permanently.
  • You must call session_start() at the beginning of the PHP script.
  • Session data is shared in an array called $_SESSION.

HTTP Reqest Variables in PHP

This chapter describes:

  • What are the predefined variables that store information from the HTTP request.
  • A sample script to test request variables.
  • How to promote request variables to stand alone variables.

Predefined Variables Related to HTTP Request

When PHP is used on a Web server to handle a HTTP request, it converts information submitted in the HTTP request as predefined variables:

  • $_GET – Associate array of variables submitted with GET method.
  • $_POST – Associate array of variables submitted with POST method.
  • $_COOKIE – Associate array of variables submitted as cookies.
  • $_REQUEST – Associate array of variables from $_GET, $_POST, and $_COOKIE.
  • $_SERVER – Associate array of all information from the server and the HTTP request.

Variables in those arrays can also be promoted (registered) as stand alone global variables using one of the following two ways:

  • Change “register_globals = on” in php.ini to register HTTP request variables on the entire server.
  • Call import_request_variables() to register HTTP request variables in one script only.

Here is my standard test program for HTTP request variables:

<?php # HttpRequestDetails.php
# Copyright (c) 2002 by Dr. Herong Yang, http://www.herongyang.com/
# 
   print "<pre>\n";
   print "\nContents of \$_GET:\n";
   foreach ($_GET as $k => $v) {
      print "   $k = $v\n";
   }
# 
   print "\nContents of \$_POST:\n";
   foreach ($_POST as $k => $v) {
      print "   $k = $v\n";
   }
# 
   print "\nContents of \$_COOKIE:\n";
   foreach ($_COOKIE as $k => $v) {
      print "   $k = $v\n";
   }
# 
   print "\nContents of \$_REQUEST:\n";
   foreach ($_REQUEST as $k => $v) {
      print "   $k = $v\n";
   }
# 
   print "\nContents of \$_SERVER:\n";
   foreach ($_SERVER as $k => $v) {
      print "   $k = $v\n";
   }
   print "</pre>\n";
?>

Run HttpRequestDetails.php at the command line, you will get:

<pre>

Contents of $_GET:

Contents of $_POST:

Contents of $_COOKIE:

Contents of $_REQUEST:

Contents of $_SERVER:
   CLIENTNAME = Console
   ComSpec = C:\WINDOWS\system32\cmd.exe
   HOMEDRIVE = C:
   PHPRC = c:\local\php
   PROCESSOR_ARCHITECTURE = x86
   SESSIONNAME = Console
   SystemDrive = C:
   SystemRoot = C:\WINDOWS
   PHP_SELF = HttpRequestDetails.php
   SCRIPT_NAME = HttpRequestDetails.php
   SCRIPT_FILENAME = HttpRequestDetails.php
   PATH_TRANSLATED = HttpRequestDetails.php
   DOCUMENT_ROOT =
   argv = Array
   argc = 1
   ......
</pre>

Not very interesting, right? $_GET, $_POST, $_COOKIE, and $_REQUEST are all empty.

Testing Request Variables – HttpRequestDetails.php

Now, let’s run HttpRequestDetails.php on the local Web server. First copy HttpRequestDetails.php to \inetpub\wwwroot, then run Internet Explorer (IE) with http://localhost/HttpRequestDetails.php. You should get:

Contents of $_GET:

Contents of $_POST:

Contents of $_COOKIE:

Contents of $_REQUEST:

Contents of $_SERVER:
   CONTENT_LENGTH = 0
   GATEWAY_INTERFACE = CGI/1.1
   HTTP_ACCEPT = */*
   HTTP_ACCEPT_LANGUAGE = en-us
   HTTP_CONNECTION = Keep-Alive
   HTTP_HOST = localhost
   HTTP_ACCEPT_ENCODING = gzip, deflate
   HTTPS = off
   INSTANCE_ID = 1
   LOCAL_ADDR = 127.0.0.1
   NUMBER_OF_PROCESSORS = 1
   OS = Windows_NT
   ProgramFiles = C:\Program Files
   REMOTE_ADDR = 127.0.0.1
   REMOTE_HOST = 127.0.0.1
   REQUEST_METHOD = GET
   SCRIPT_NAME = /HttpRequestDetails.php
   SERVER_NAME = localhost
   SERVER_PORT = 80
   SERVER_PORT_SECURE = 0
   SERVER_PROTOCOL = HTTP/1.1
   SystemDrive = C:
   ORIG_PATH_INFO = /HttpRequestDetails.php
   ORIG_SCRIPT_NAME = /HttpRequestDetails.php
   DOCUMENT_ROOT = c:/inetpub/wwwroot
   SCRIPT_FILENAME = c:\inetpub\wwwroot\HttpRequestDetails.php
   PHP_SELF = /HttpRequestDetails.php
   ......

$_GET is still empty, because nothing is submitted in the HTTP request. Now try this URL: http://localhost/HttpRequestDetails.php?lang=PHP&search. You should get:

Contents of $_GET:
   lang = PHP
   search = 

Contents of $_POST:

Contents of $_COOKIE:

Contents of $_REQUEST:
   lang = PHP
   search = 

Contents of $_SERVER:
   ......
   QUERY_STRING = lang=PHP&search
   ......

Registering HTTP Request Variables as Global Variables

As I mentioned in the first section, there are two ways to promote variables stored in the request as stand alone global variables:

To promote request variables for the entire server, edit \php\php.ini and set:

register_globals = on

To promote request variables for one script only, use the following function:

import_request_variables("GPC",$prefix);

where “GPC” indicates that all variables from GET, POST and COOKIE are prompted. $prefix defines a prefix string that are to be added to the variable names.

Here is a sample script, RequestVariables.php

<?php # RequestVariables.php
# Copyright (c) 2002 by Dr. Herong Yang
# 
   print "<pre>\n";
   print "\nContents of \$_REQUEST:\n";
   foreach ($_REQUEST as $k => $v) {
      print "   $k = $v\n";
   }
# 
   print "\nLocl imported variables from the request:\n";
   import_request_variables("GPC","r_");
   print "   \$r_lang = $r_lang\n";
   print "   \$r_search = $r_search\n";
# 
   print "\nGlobaly imported variables from the request:\n";
   print "   \$lang = $lang\n";
   print "   \$search = $search\n";
   print "</pre>\n";
?>

Try the script with http://localhost/RequestVariables.php?lang=PHP&search, you will get:

Contents of $_REQUEST:
   lang = PHP
   search = 

Locl imported variables from the request:
   $r_lang = PHP
   $r_search = 

Globaly imported variables from the request:
   $lang = PHP
   $search =

Conclusion:

$_GET in PHP is similar to the request.QueryString object in ASP.

$_POST in PHP is similar to the request.Form object in ASP.

Promoting variables in the request to be stand alone variable makes it easy to use them. But it also increases the risk of colliding them with other variables used in the script.

Sending Emails Using PHP

This chapter describes:

  • How to check the mail server on your local Windows system.
  • How to send an email through PHP.

Using Local Windows System as a Mail Server

If you are running your Web server on a local system and not connected to the Internet, you need to set up your local system as a mail server to test the email function in PHP.

If you are running a Linux/Unix system, setting up a mail server is easy. Just run sendmail as daemon.

If you are running a Windows system, setting up a mail server is a little bit harder. But most of the time, your local Windows system is probably already running a mail server. Here is how you can check this:

1. Go to Control Panel / Services, and make sure Simple Mail Transfer Protocol is running.

2. Open a command window, and run the following command:

>telnet localhost 25 

220 localhost Microsoft ESMTP MAIL Service, Version: 6.0.2600.1106...
help
214-This server supports the following commands:
214 HELO EHLO STARTTLS RCPT DATA RSET MAIL QUIT HELP AUTH BDAT VRFY
quit
221 2.0.0 localhost Service closing transmission channel

If you got similar outputs as above, your mail server is running ok.

Sending an Email with PHP

First you need to verify \php\php.ini to make sure the following settings:

SMTP = localhost
smtp_port = 25

Now run the following PHP script, MailTest.php:

<?php # MailTest.php
# Copyright (c) 2002 by Dr. Herong Yang, http://www.herongyang.com/
#
mail("nobody","Testing","This is a test.","From: herong@localhost");
?>

Then go check to see the email is delivered or not in a command window:

>dir \inetpub\mailroot\drop

... d9765b3001c54a1200000001.eml

>type \inetpub\mailroot\drop\d9765b3001c54a1200000001.eml

x-sender: herong@localhost
x-receiver: nobody@localhost
Received: from localhost ([127.0.0.1]) by localhost with Microsoft...
Subject: Testing
To: nobody
From: herong@localhost
Return-Path: herong@localhost
......

This is a test.

If you can follow me to here, you have successfully configured your local system to send emails with PHP.

Arrays

What Is an Array in PHP?

Array: In PHP, an array represents an ordered map of pairs of keys and values. This is different than most of other languages. Basic rules for PHP’s array are:

1. An array can be constructed by the array constructor, like:

   $myArray = array(k1=>v1, k2=>v2, ..., kn=>vn);

where k1, k2, …, and kn are keys of integer type or string type. v1, v2, …, and vn are values of any data types.

2. The value of a given key in an array can be expressed by the array variable followed by the key in square brackets, like:

   print $myArray[kn];

3. The value of a given key in an array can be modified by an assignment statement, like:

   $myArray[kn] = new_value.

4. A new pair of key and value can be added to an array by an assignment statement, like:

   $myArray[kx] = vx

5. If a string key represents an integer, it will be used as an integer key. So $myArray['7'] is the same as $myArray[7].

6. If the key is missing in an array assignment or an array constructor, an integer key of 0, or the highest integer key plus 1, will be provided.

7. An empty string is also a valid string key, like:

   $myArray[''] = vy;

8. A pair of key and value can be removed by using the unset() function, like:

   unset($myArray[kn]);

9. Pairs of keys and values are ordered in an array like a queue. New pairs are always added at the end of the array.

   unset($myArray[kn]);

Here is a simple script to show you some of these rules:

<?php # ArrayTest.php
# Copyright (c) 2003 by Dr. Herong Yang, http://www.herongyang.com/
#
   print "\nLibrary hours:\n";
   $libraryHours = array(
      'Monday - Friday'=>'09:00 - 21:00',
      'Saturday'=>'09:00 - 17:00',
      'Sunday'=>'closed');
   print_r($libraryHours);
#
   print "\nPrime numbers:\n";
   $primeNumbers = array(3, 5, 7, 11);
   $primeNumbers[] = 13;
   print_r($primeNumbers);
#
   print "\nFruits:\n";
   $fruits[] = 'Apple';
   $fruits[] = 'Orange';
   $fruits[''] = 'Peach';
   $fruits[''] = 'Banana';
   $fruits['G'] = 'Grape';
   $fruits['7'] = 'Pear';
   $fruits[] = 'Fig';
   print_r($fruits);
#
   print "\nFruits array modified:\n";
   unset($fruits[1]);
   $fruits[1] = 'Orange';
   print_r($fruits);
?>

Here is the output:

Library hours: Array ( [Monday - Friday] => 09:00 – 21:00 [Saturday] => 09:00 – 17:00 [Sunday] => closed ) Prime numbers: Array ( [0] => 3 [1] => 5 [2] => 7 [3] => 11 [4] => 13 ) Fruits: Array ( [0] => Apple [1] => Orange [] => Banana [G] => Grape [7] => Pear [8] => Fig ) Fruits array modified: Array ( [0] => Apple [] => Banana [G] => Grape [7] => Pear [8] => Fig [1] => Orange )

The behavior of the $fruits array is very interesting. Review it carefully.

Array Related Built-in Functions

PHP offers a number of interesting built-in functions to work with arrays:

  • array_combine() – Combines two arrays into a new array with the first array as keys and the second as values.
  • array_count_values() – Counts the frequencies of values in an array and returns them as an array.
  • array_key_exists() – Searches for a key in an array.
  • array_keys() – Returns an array with all keys of an array.
  • array_search() – Searches for a value in an array.
  • array_values() – Returns an array with all values of an array.
  • ksort() – Sorts an array by keys.
  • sort() – Sorts an array by values.

PHP also offers special loop statements to iterate over arrays:

foreach($myArray as $value) {} foreach($myArray as $key=>$value) {}

Here is a simple script with a “foreach” statement:

<?php # ArrayLoop.php # Copyright (c) 2003 by Dr. Herong Yang # print “\nLibrary hours:\n”; $libraryHours = array( ‘Monday – Friday’=>’09:00 – 21:00′, ‘Saturday’=>’09:00 – 17:00′, ‘Sunday’=>’closed’); foreach($libraryHours as $day=>$hours) { print ” $day: $hours\n”; } ?>

Here is the output:

Library hours: Monday – Friday: 09:00 – 21:00 Saturday: 09:00 – 17:00 Sunday: closed

Conclusion

  • PHP’s array is easy to use. But mixing integer indexed array with associate map is kind of confusing.

Functions

This chapter describes:

  • How to define functions.
  • How to pass references to and returning a reference from functions.

User Defined Functions

PHP supports user defined functions like in other languages, with some special features:

  • By default, arguments are passed by value. But arguments can also be passed as references.
  • Arguments can be assigned with default values.
  • Functions can return values or references.
  • Function names can also be string expressions. This is called variable functions.
  • Functions can be defined inside another code block, or function.

Passing and Returning References

The following sample script shows how references can be passed to and returned from a function, FunctionTest.php:

<?php # FunctionTest.php
# Copyright (c) 2002 by Dr. Herong Yang, http://www.herongyang.com/
#
   print "\nPassing arguments as references:\n";
   $x = "Apple";
   $y = "Orange";
   swap($x,$y);
   print "   x = $x\n";
   print "   y = $y\n";
#
   print "\nReturning a reference:\n";
   $x = 10;
   $y = &ref($x);
   $x = 20;
   print "   y = $y\n";
#
function swap(&$a, &$b) {
   $c = $b;
   $b = $a;
   $a = $c;
}
function &ref(&$a) {
   return $a;
}
?>

Here is the output of the program:

Passing arguments as references:
   x = Orange
   y = Apple

Returning a reference:
   y = 20

I am sure you know why we getting this output.

Follow

Get every new post delivered to your Inbox.