IT Community - Software Programming, Web Development and Technical Support

HTTP functions in PHP

This is a discussion on HTTP functions in PHP within the PHP Programming forums, part of the Web Development category; Hi, headers_sent() Function Definition and Usage The headers_sent() function checks if / where the HTTP headers have been sent. This function ...


Go Back   IT Community - Software Programming, Web Development and Technical Support > Web Development > PHP Programming

Register FAQ Members List Calendar Mark Forums Read
  #21 (permalink)  
Old 04-07-2008, 08:44 AM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: HTTP functions in PHP

Hi,

headers_sent() Function Definition and Usage

The headers_sent() function checks if / where the HTTP headers have been sent.

This function returns TRUE if headers has been sent or FALSE if not.
__________________
Regards,
Senraj.A

Last edited by senraj : 04-07-2008 at 09:39 PM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Sponsored Links
  #22 (permalink)  
Old 04-07-2008, 08:45 AM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: HTTP functions in PHP

Hi,

headers_sent() Function Definition and Usage

You can't add more header lines using header() once the header block has already been sent.

The optional file and line parameters where added in PHP 4.3.

Example
---------

<?php
// If no headers are sent, send one
if (!headers_sent())
{
header("Location: http://www.w3schools.com/");
exit;
}
?>

<html>
<body>

...
...
__________________
Regards,
Senraj.A

Last edited by senraj : 04-07-2008 at 09:40 PM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #23 (permalink)  
Old 04-07-2008, 08:46 AM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: HTTP functions in PHP

Hi,

Another one Example of headers_sent() Function.

Using the optional file and line parameters:

<?php
// $file and $line are passed in for later use
// Do not assign them values beforehand
if (!headers_sent($file, $line))
{
header("Location: http://www.w3schools.com/");
exit;
// Trigger an error here
}
else
{
echo "Headers sent in $file on line $line";
exit;
}
?>

<html>
<body>

...
...
__________________
Regards,
Senraj.A

Last edited by senraj : 04-07-2008 at 09:42 PM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #24 (permalink)  
Old 04-07-2008, 08:46 AM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: HTTP functions in PHP

Hi,

setcookie() function Definition and Usage

The setcookie() function sends an HTTP cookie to a client.

A cookie is a variable, sent by the server to the browser. A cookie is typically a small text file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too.

The name of the cookie is automatically assigned to a variable of the same name. For example, if a cookie was sent with the name "user", a variable is automatically created called $user, containing the cookie value.

A cookie must be assigned before any other output is sent to the client.

This function returns TRUE on success or FALSE on failure.
__________________
Regards,
Senraj.A

Last edited by senraj : 04-07-2008 at 09:43 PM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #25 (permalink)  
Old 04-07-2008, 08:47 AM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: HTTP functions in PHP

Hi,

setcookie() function Definition and Usage

The value of a cookie named "user" can be accessed by $HTTP_COOKIE_VARS["user"] or by $_COOKIE["user"].

The value of the cookie will automatically be URL encoded when you send the cookie (and automatically decoded when received). If you don't want this, you can use setrawcookie() instead.

Example
-----------
Set and send cookie examples:

<?php
$value = "my cookie value";

// send a simple cookie
setcookie("TestCookie",$value);
?>

<html>
<body>

...
...
__________________
Regards,
Senraj.A

Last edited by senraj : 04-07-2008 at 09:44 PM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #26 (permalink)  
Old 04-08-2008, 07:24 AM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: HTTP functions in PHP

setrawcookie() is exactly the same as setcookie() except that the cookie value will not be automatically urlencoded when sent to the browser.
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #27 (permalink)  
Old 04-08-2008, 07:25 AM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: HTTP functions in PHP

PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() or setrawcookie() function. Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser. This is the same limitation that header() has. You can use the output buffering functions to delay the script output until you have decided whether or not to set any cookies or send any headers.
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #28 (permalink)  
Old 04-08-2008, 07:25 AM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: HTTP functions in PHP

Any cookies sent to you from the client will automatically be included into a $_COOKIE auto-global array if variables_order contains "C". If you wish to assign multiple values to a single cookie, just add [] to the cookie name.
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #29 (permalink)  
Old 04-08-2008, 07:26 AM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: HTTP functions in PHP

Depending on register_globals, regular PHP variables can be created from cookies. However it's not recommended to rely on them as this feature is often turned off for the sake of security. $HTTP_COOKIE_VARS is also set in earlier versions of PHP when the track_vars configuration variable is set.
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #30 (permalink)  
Old 04-09-2008, 11:12 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: HTTP functions in PHP

HTTP authentication

The HTTP Authentication hooks in PHP are only available when it is running as an Apache module and is hence not available in the CGI version. In an Apache module PHP script, it is possible to use the header() function to send an "Authentication Required" message to the client browser causing it to pop up a Username/Password input window. Once the user has filled in a username and a password, the URL containing the PHP script will be called again with the predefined variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE set to the user name, password and authentication type respectively. These predefined variables are found in the $_SERVER and $HTTP_SERVER_VARS arrays. Both "Basic" and "Digest" (since PHP 5.1.0) authentication methods are supported.
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #31 (permalink)  
Old 04-09-2008, 11:12 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: HTTP functions in PHP

Autoglobals, such as $_SERVER, became available in PHP 4.1.0. HTTP_SERVER_VARS has been available since PHP 3.
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #32 (permalink)  
Old 04-09-2008, 11:13 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: HTTP functions in PHP

An example script fragment which would force client authentication on a page is as follows:

PHP Code:
<?php
  
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    
header('WWW-Authenticate: Basic realm="My Realm"');
    
header('HTTP/1.0 401 Unauthorized');
    echo 
'Text to send if user hits Cancel button';
    exit;
  } else {
    echo 
"<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo 
"<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
  }
?>
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #33 (permalink)  
Old 04-09-2008, 11:14 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: HTTP functions in PHP

This example shows you how to implement a simple Digest HTTP authentication script
PHP Code:
<?php
$realm 
'Restricted area';

//user => password
$users = array('admin' => 'mypass''guest' => 'guest');


if (empty(
$_SERVER['PHP_AUTH_DIGEST'])) {
    
header('HTTP/1.1 401 Unauthorized');
    
header('WWW-Authenticate: Digest realm="'.$realm.
           
'" qop="auth" nonce="'.uniqid().'" opaque="'.md5($realm).'"');

    die(
'Text to send if user hits Cancel button');
}


// analyze the PHP_AUTH_DIGEST variable
if (!($data http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
    !isset(
$users[$data['username']]))
    die(
'Wrong Credentials!');


// generate the valid response
$A1 md5($data['username'] . ':' $realm ':' $users[$data['username']]);
$A2 md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);

if (
$data['response'] != $valid_response)
    die(
'Wrong Credentials!');

// ok, valid username & password
echo 'Your are logged in as: ' $data['username'];


// function to parse the http auth header
function http_digest_parse($txt)
{
    
// protect against missing data
    
$needed_parts = array('nonce'=>1'nc'=>1'cnonce'=>1'qop'=>1'username'=>1'uri'=>1'response'=>1);
    
$data = array();

    
preg_match_all('@(\w+)=([\'"]?)([a-zA-Z0-9=./\_-]+)\2@'$txt$matchesPREG_SET_ORDER);

    foreach (
$matches as $m) {
        
$data[$m[1]] = $m[3];
        unset(
$needed_parts[$m[1]]);
    }

    return 
$needed_parts false $data;
}
?>
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #34 (permalink)  
Old 04-09-2008, 11:16 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: HTTP functions in PHP

Please be careful when coding the HTTP header lines. In order to guarantee maximum compatibility with all clients, the keyword "Basic" should be written with an uppercase "B", the realm string must be enclosed in double (not single) quotes, and exactly one space should precede the 401 code in the HTTP/1.0 401 header line.
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #35 (permalink)  
Old 04-11-2008, 11:44 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: HTTP functions in PHP

Instead of simply printing out PHP_AUTH_USER and PHP_AUTH_PW, as done in the above example, you may want to check the username and password for validity. Perhaps by sending a query to a database, or by looking up the user in a dbm file.

Watch out for buggy Internet Explorer browsers out there. They seem very picky about the order of the headers. Sending the WWW-Authenticate header before the HTTP/1.0 401 header seems to do the trick for now.
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #36 (permalink)  
Old 04-11-2008, 11:45 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: HTTP functions in PHP

As of PHP 4.3.0, in order to prevent someone from writing a script which reveals the password for a page that was authenticated through a traditional external mechanism, the PHP_AUTH variables will not be set if external authentication is enabled for that particular page and safe mode is enabled. Regardless, REMOTE_USER can be used to identify the externally-authenticated user. So, you can use $_SERVER['REMOTE_USER'].
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #37 (permalink)  
Old 04-11-2008, 11:46 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: HTTP functions in PHP

PHP uses the presence of an AuthType directive to determine whether external authentication is in effect.
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #38 (permalink)  
Old 04-11-2008, 11:47 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: HTTP functions in PHP

Both Netscape Navigator and Internet Explorer will clear the local browser window's authentication cache for the realm upon receiving a server response of 401. This can effectively "log out" a user, forcing them to re-enter their username and password. Some people use this to "time out" logins, or provide a "log-out" button.
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #39 (permalink)  
Old 04-11-2008, 11:48 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: HTTP functions in PHP

HTTP Authentication example forcing a new name/password

PHP Code:
<?php
  
function authenticate() {
    
header('WWW-Authenticate: Basic realm="Test Authentication System"');
    
header('HTTP/1.0 401 Unauthorized');
    echo 
"You must enter a valid login ID and password to access this resource\n";
    exit;
  }
 
  if (!isset(
$_SERVER['PHP_AUTH_USER']) ||
      (
$_POST['SeenBefore'] == && $_POST['OldAuth'] == $_SERVER['PHP_AUTH_USER'])) {
   
authenticate();
  } 
  else {
   echo 
"<p>Welcome: {$_SERVER['PHP_AUTH_USER']}<br />";
   echo 
"Old: {$_REQUEST['OldAuth']}";
   echo 
"<form action='{$_SERVER['PHP_SELF']}' METHOD='post'>\n";
   echo 
"<input type='hidden' name='SeenBefore' value='1' />\n";
   echo 
"<input type='hidden' name='OldAuth' value='{$_SERVER['PHP_AUTH_USER']}' />\n";
   echo 
"<input type='submit' value='Re Authenticate' />\n";
   echo 
"</form></p>\n";
  }
?>
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #40 (permalink)  
Old 04-11-2008, 11:50 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: HTTP functions in PHP

This behavior is not required by the HTTP Basic authentication standard, so you should never depend on this. Testing with Lynx has shown that Lynx does not clear the authentication credentials with a 401 server response, so pressing back and then forward again will open the resource as long as the credential requirements haven't changed. The user can press the '_' key to clear their authentication information, however.
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote