Rectangle 27 3

PHP doesn't know what it is, it just sees text out of the <?php ?> tags, so it sends it as output.

Didn't work. Still getting the same error.

For me this error is almost always a space or carriage return that is outputted before any attempt by php to write or change the response header.

Thanks. I put the include in the main PHP block and it worked.

PHP - setcookie(); not working ( Cannot modify header information - he...

php setcookie
Rectangle 27 3

the echo is right after I've set it, but normally the page refreshes and I'm not logged in. When I test it at localhost without the domain setting it works perfectly. So there's something wrong with that part I guess...

setcookie does not work (PHP) - Stack Overflow

php setcookie
Rectangle 27 4

Agree, that cookie example works good, possible problem can be the wrong last parameter domain name, or cookies are disabled in browser.

This is so weird. 10 minutes ago I tested this on TWO different computers and test2.php both outputed "abcb", even though I had "abc" as cookie value. Anyways, it works now. Btw, I do have cookies enabled. But I don't mind it not working on mine, as long as it works on others. :) Thanks for the help anyway.

Thanks. Yet you can try to delete that cookie manually from browser cache and try to revisit again test1 and test2.php. Good luck!

php - setcookie() doesn't work properly? - Stack Overflow

php setcookie
Rectangle 27 3

$_COOKIE[] with that new cookie will be available only with next request

setcookie does not work (PHP) - Stack Overflow

php setcookie
Rectangle 27 9

For those reading through wanting to use this method in PHP scripts. Here is a working example using 256bit Rijndael (not AES).

function encrypt($text, $salt) 
{ 
    return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $salt, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)))); 
} 

function decrypt($text, $salt) 
{ 
    return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $salt, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))); 
}
setcookie("PHPSESSION", encrypt('thecookiedata', 'longsecretsalt'));
$data = decrypt($_COOKIE['PHPSESSION'], 'longsecretsalt');

Update: use CBC mode instead of ECB!

The proposed function is vulnerable to manipulation, as it has no ciphertext integrity protection. See ipsec.pl/node/1085 for details.

php - What encryption algorithm is best for encrypting cookies? - Stac...

php security cookies encryption remember-me
Rectangle 27 9

For those reading through wanting to use this method in PHP scripts. Here is a working example using 256bit Rijndael (not AES).

function encrypt($text, $salt) 
{ 
    return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $salt, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)))); 
} 

function decrypt($text, $salt) 
{ 
    return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $salt, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))); 
}
setcookie("PHPSESSION", encrypt('thecookiedata', 'longsecretsalt'));
$data = decrypt($_COOKIE['PHPSESSION'], 'longsecretsalt');

Update: use CBC mode instead of ECB!

The proposed function is vulnerable to manipulation, as it has no ciphertext integrity protection. See ipsec.pl/node/1085 for details.

php - What encryption algorithm is best for encrypting cookies? - Stac...

php security cookies encryption remember-me
Rectangle 27 1

Have you tried using PHP session_start(), placing data in the session and modifying it? This script will help you make the test. If that works, you can almost certainly use PHP setcookie() to preserve client state.

<?php // RAY_session_test.php
error_reporting(E_ALL);


// DEMONSTRATE HOW PHP SESSIONS WORK
// MAN PAGE HERE: http://php.net/manual/en/function.session-start.php


// START THE SESSION (DO THIS FIRST, UNCONDITIONALLY, IN EVERY PHP SCRIPT ON EVERY PAGE)
session_start();

// INITIALIZE THE SESSION ARRAY TO SET A DEFAULT VALUE
if (empty($_SESSION["cheese"])) $_SESSION["cheese"] = 1;

// SEE IF THE CORRECT SUBMIT BUTTON WAS CLICKED
if (isset($_POST['fred']))
{
    // ADD ONE TO THE CHEESE
    $_SESSION['cheese']++;
}

// RECOVER THE CURRENT VALUE FROM THE SESSION ARRAY
$cheese = $_SESSION['cheese'];


// END OF PROCESSING SCRIPT - CREATE THE FORM USING HEREDOC NOTATION
$form = <<<ENDFORM
<html>
<head>
<title>Session Test</title>
</head>
<body>
Currently, SESSION["cheese"] contains: $cheese<br/>
<form method="post">
<input type="submit" value="increment this cheese" name="fred"  />
<input type="submit" value="leave my cheese alone" name="john" />
</form>
</body>
</html>
ENDFORM;

echo $form;

but this will all be on server...right? i want to maintain cookie on client side

PHP sessions use cookies to find the server-side data. So this is a very easy way to see if the device is acting like a well-behaved browser, accepting and returning the cookies.

java - cookie based login system in android - Stack Overflow

java php android session-cookies httpurlconnection
Rectangle 27 2

When setting a cookie on a page that redirects, the cookie must be set after the call to header('Location: ....');

<?php 
header('Location: http://www.example.com/'); 
setcookie('asite', $site, time()+60*60, '/', 'site.com'); 
?>

i changed the order of the cookie part of script and placed the cookie unsetting after the header(), as you said, but i'm still getting the same error/ warning

Redirecting a php page based on header(location) command not working; ...

php header location warnings redirect
Rectangle 27 9

Time is bigger than int, so I think result is negative, and then cookie is set into past, what means, it is deleted. Set time to 3 years instead of 100.

That was exactly the problem, thank you very much!

php - setcookie does not work - Stack Overflow

php setcookie
Rectangle 27 2489

How can you find out where the premature output occured?

Functions that send/modify HTTP headers must be invoked before any output is made. summary Otherwise the call fails:

Some functions modifying the HTTP header are:

header
header_remove
session_start
session_regenerate_id
setcookie
setrawcookie
  • Whitespace before <?php or after ?>
<html>
<?php

To understand why headers must be sent before output it's necessary to look at a typical HTTP response. PHP scripts mainly generate HTML content, but also pass a set of HTTP/CGI headers to the webserver:

HTTP/1.1 200 OK
Powered-By: PHP/5.3.7
Vary: Accept-Encoding
Content-Type: text/html; charset=utf-8

<html><head><title>PHP page output page</title></head>
<body><h1>Content</h1> <p>Some more output follows...</p>
and <a href="/"> <img src=internal-icon-delayed> </a>

The page/output always follows the headers. PHP has to pass the headers to the webserver first. It can only do that once. After the double linebreak it can nevermore amend them.

When PHP receives the first output (print, echo, <html>) it will flush all collected headers. Afterwards it can send all the output it wants. But sending further HTTP headers is impossible then.

The header() warning contains all relevant information to locate the problem cause:

Here "line 100" refers to the script where the header() invocation failed.

The "output started at" note within the parenthesis is more significant. It denominates the source of previous output. In this example it's auth.php and line 52. That's where you had to look for premature output.

Intentional output from print and echo statements will terminate the opportunity to send HTTP headers. The application flow must be restructured to avoid that. Use functions and templating schemes. Ensure header() calls occur before messages are written out.

print
echo
printf
vprintf
trigger_error
ob_flush
ob_end_flush
var_dump
print_r
readfile
passthru
flush
imagepng
imagejpeg

Unparsed HTML sections in a .php file are direct output as well. Script conditions that will trigger a header() call must be noted before any raw <html> blocks.

<!DOCTYPE html>
<?php
    // Too late for headers already.

Use a templating scheme to separate processing from output logic.

  • The actual output logic and intermixed HTML output should follow last.

If the warning refers to output in line 1, then it's mostly leading whitespace, text or HTML before the opening <?php token.

<?php
# There's a SINGLE space/newline before <? - Which already seals it.

Similarly it can occur for appended scripts or script sections:

?>

<?php

PHP actually eats up a single linebreak after close tags. But it won't compensate multiple newlines or tabs or spaces shifted into such gaps.

Linebreaks and spaces alone can be a problem. But there are also "invisible" character sequences which can cause this. Most famously the UTF-8 BOM (Byte-Order-Mark) which isn't displayed by most text editors. It's the byte sequence EF BB BF, which is optional and redundant for UTF-8 encoded documents. PHP however has to treat it as raw output. It may show up as the characters in the output (if the client interprets the document as Latin-1) or similar "garbage".

In particular graphical editors and Java based IDEs are oblivious to its presence. They don't visualize it (obliged by the Unicode standard). Most programmer and console editors however do:

There it's easy to recognize the problem early on. Other editors may identify its presence in a file/settings menu (Notepad++ on Windows can identify and remedy the problem), Another option to inspect the BOMs presence is resorting to an hexeditor. On *nix systems hexdump is usually available, if not a graphical variant which simplifies auditing these and other issues:

An easy fix is to set the text editor to save files as "UTF-8 (no BOM)" or similar such nomenclature. Often newcomers otherwise resort to creating new files and just copy&pasting the previous code back in.

There are also automated tools to examine and rewrite text files (sed/awk or recode). For PHP specifically there's the phptags tag tidier. It rewrites close and open tags into long and short forms, but also easily fixes leading and trailing whitespace, Unicode and UTF-x BOM issues:

phptags  --whitespace  *.php

It's sane to use on a whole include or project directory.

If the error source is mentioned as behind the closing ?> then this is where some whitespace or raw text got written out. The PHP end marker does not terminate script executation at this point. Any text/space characters after it will be written out as page content still.

It's commonly advised, in particular to newcomers, that trailing ?> PHP close tags should be omitted. This eschews a small portion of these cases. (Quite commonly include()d scripts are the culprit.)

It's typically a PHP extension or php.ini setting if no error source is concretized.

  • It's occasionally the gzip stream encoding setting or the ob_gzhandler.
extension=

If another PHP statement or expression causes a warning message or notice being printeded out, that also counts as premature output.

In this case you need to eschew the error, delay the statement execution, or suppress the message with e.g. isset() or @() - when either doesn't obstruct debugging later on.

If you have error_reporting or display_errors disabled per php.ini, then no warning will show up. But ignoring errors won't make the problem go away. Headers still can't be sent after premature output.

So when header("Location: ...") redirects silently fail it's very advisable to probe for warnings. Reenable them with two simple commands atop the invocation script:

error_reporting(E_ALL);
ini_set("display_errors", 1);
set_error_handler("var_dump");

Speaking of redirect headers, you should often use an idiom like this for final code paths:

exit(header("Location: /finished.html"));

Preferrably even a utility function, which prints a user message in case of header() failures.

PHPs output buffering is a workaround to alleviate this issue. It often works reliably, but shouldn't substitute for proper application structuring and separating output from control logic. Its actual purpose is minimizing chunked transfers to the webserver.

The output_buffering= setting nevertheless can help. Configure it in the php.ini or via .htaccess or even .user.ini on modern FPM/FastCGI setups. Enabling it will allow PHP to buffer output instead of passing it to the webserver instantly. PHP thus can aggregate HTTP headers.

It can likewise be engaged with a call to ob_start(); atop the invocation script. Which however is less reliable for multiple reasons:

Both approaches therefore may become unreliable - in particular when switching between development setups and/or production servers. Which is why output buffering is widely considered just a crutch / strictly a workaround.

See also the basic usage example in the manual, and for more pros and cons:

If you didn't get the headers warning before, then the output buffering php.ini setting has changed. It's likely unconfigured on the current/new server.

You can always use headers_sent() to probe if it's still possible to... send headers. Which is useful to conditionally print an info or apply other fallback logic.

if (headers_sent()) {
    die("Redirect failed. Please click on this link: <a href=...>");
}
else{
    exit(header("Location: /user.php"));
}

If your application is structurally hard to fix, then an easy (but somewhat unprofessional) way to allow redirects is injecting a HTML <meta> tag. A redirect can be achieved with:

<meta http-equiv="Location" content="http://example.com/">

Or with a short delay:

<meta http-equiv="Refresh" content="2; url=../target.html">

This leads to non-valid HTML when utilized past the <head> section. Most browsers still accept it.

As alternative a JavaScript redirect can be used for page redirects:

<script> location.replace("target.html"); </script>

While this is often more HTML compliant than the <meta> workaround, it incurs a reliance on JavaScript-capable clients.

Both approaches however make acceptable fallbacks when genuine HTTP header() calls fail. Ideally you'd always combine this with a user-friendly message and clickable link as last resort. (Which for instance is what the http_redirect() PECL extension does.)

Both setcookie() and session_start() need to send a Set-Cookie: HTTP header. The same conditions therefore apply, and similar error messages will be generated for premature output situations.

(Of course they're furthermore affected by disabled cookies in the browser, or even proxy issues. The session functionality obviously also depends on free disk space and other php.ini settings, etc.)

  • And of course many specific cases have been covered on Stack Overflow as well.
  • One of the more thorough explanations is HTTP Headers and the PHP header() Function - A tutorial by NicholasSolutions (Internet Archive link). It covers HTTP in detail and gives a few guidelines for rewriting scripts.

Also regular notepad.exe is tricky. I use NetBeans normally that doesn't add BOM, even if file is encoded so. Editing a file later in notepad messes things up, especially towards IIS as webserver. It seems as apache discards the (unitentionally added) BOM.

Removing the closing ?> from the end of a php files is usually a good practice which helps minimizing these errors as well. Unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.

Strange thing, I moved my file from cPanel Linux Hosting to VPS. Before it was working properly but here it showed this error.(I had some html code before header). Why?

But it worked on the other server!?

How to fix "Headers already sent" error in PHP - Stack Overflow

php header
Rectangle 27 165

This error message gets triggered when anything is sent before you send HTTP headers (with setcookie or header). Common reasons for outputting something before the HTTP headers are:

Accidental whitespace, often at the beginning or end of files, like this:

<?php
// Note the space before "<?php"
?>

To avoid this, simply leave out the closing ?> - it's not required anyways.

  • Byte order marks at the beginning of a php file. Examine your php files with a hex editor to find out whether that's the case. They should start with the bytes 3F 3C. You can safely remove the BOM EF BB BF from the start of files.
  • Explicit output, such as calls to echo, printf, readfile, passthru, code before <? etc.
  • A warning outputted by php, if the display_errors php.ini property is set. Instead of crashing on a programmer mistake, php silently fixes the error and emits a warning. While you can modify the display_errors or error_reporting configurations, you should rather fix the problem. Common reasons are accesses to undefined elements of an array (such as $_POST['input'] without using empty or isset to test whether the input is set), or using an undefined constant instead of a string literal (as in $_POST[input], note the missing quotes).

Turning on output buffering should make the problem go away; all output after the call to ob_start is buffered in memory until you release the buffer, e.g. with ob_end_flush.

However, while output buffering avoids the issues, you should really determine why your application outputs an HTTP body before the HTTP header. That'd be like taking a phone call and discussing your day and the weather before telling the caller that he's got the wrong number.

How to fix "Headers already sent" error in PHP - Stack Overflow

php header
Rectangle 27 5

I finally went for a similar solution to the one that Sascha provided, however with some little adjusting, since I'm setting the cookies explicitly in PHP:

// excecute this code if user has not authorized the application yet
// $facebook object must have been created before

$accessToken = $_COOKIE['access_token']

if ( empty($accessToken) && strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') ) {

    $accessToken = $facebook->getAccessToken();
    $redirectUri = 'https://URL_WHERE_APP_IS_LOCATED?access_token=' . $accessToken;

} else {

    $redirectUri = 'https://apps.facebook.com/APP_NAMESPACE/';

}

// generate link to auth dialog
$linkToOauthDialog = $facebook->getLoginUrl(
    array(
        'scope'         =>  SCOPE_PARAMS,
        'redirect_uri'  =>  $redirectUri
    )
);

echo '<script>window.top.location.href="' . $linkToOauthDialog . '";</script>';

What this does is check if the cookie is available when the browser is safari. In the next step, we are on the application domain, namely the URI provided as URL_WHERE_APP_IS_LOCATED above.

if (isset($_GET['accessToken'])) {

    // cookie has a lifetime of only 10 seconds, so that after
    // authorization it will disappear
    setcookie("access_token", $_GET['accessToken'], 10); 

} else {

  // depending on your application specific requirements
  // redirect, call or execute authorization code again
  // with the cookie now set, this should return FB Graph results

}

So after being redirecting to the application domain, a cookie is set explicitly, and I redirect the user to the authorization process.

In my case (since I'm using CakePHP but it should work fine with any other MVC framework) I'm calling the login action again where the FB authorization is executed another time, and this time it succeeds due to the existing cookie.

After having authorized the app once, I didn't have any more problems using the app with Safari (5.1.6)

this worked for me!! thanks!! .. i was having this problem with Safari 5.1.7.... now it's solved!

javascript - Safari 3rd party cookie iframe trick no longer working? -...

javascript facebook iframe safari
Rectangle 27 5

I finally went for a similar solution to the one that Sascha provided, however with some little adjusting, since I'm setting the cookies explicitly in PHP:

// excecute this code if user has not authorized the application yet
// $facebook object must have been created before

$accessToken = $_COOKIE['access_token']

if ( empty($accessToken) && strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') ) {

    $accessToken = $facebook->getAccessToken();
    $redirectUri = 'https://URL_WHERE_APP_IS_LOCATED?access_token=' . $accessToken;

} else {

    $redirectUri = 'https://apps.facebook.com/APP_NAMESPACE/';

}

// generate link to auth dialog
$linkToOauthDialog = $facebook->getLoginUrl(
    array(
        'scope'         =>  SCOPE_PARAMS,
        'redirect_uri'  =>  $redirectUri
    )
);

echo '<script>window.top.location.href="' . $linkToOauthDialog . '";</script>';

What this does is check if the cookie is available when the browser is safari. In the next step, we are on the application domain, namely the URI provided as URL_WHERE_APP_IS_LOCATED above.

if (isset($_GET['accessToken'])) {

    // cookie has a lifetime of only 10 seconds, so that after
    // authorization it will disappear
    setcookie("access_token", $_GET['accessToken'], 10); 

} else {

  // depending on your application specific requirements
  // redirect, call or execute authorization code again
  // with the cookie now set, this should return FB Graph results

}

So after being redirecting to the application domain, a cookie is set explicitly, and I redirect the user to the authorization process.

In my case (since I'm using CakePHP but it should work fine with any other MVC framework) I'm calling the login action again where the FB authorization is executed another time, and this time it succeeds due to the existing cookie.

After having authorized the app once, I didn't have any more problems using the app with Safari (5.1.6)

this worked for me!! thanks!! .. i was having this problem with Safari 5.1.7.... now it's solved!

javascript - Safari 3rd party cookie iframe trick no longer working? -...

javascript facebook iframe safari
Rectangle 27 1

Sessions in PHP are started by using the session_start( ) function. Like the setcookie( ) function, the session_start( ) function must come before any HTML, including blank lines, on the page. It will look like this: <?php session_start( );?><html><head> ....... etc The session_start( ) function generates a random Session Id and stores it in a cookie on the user's computer (this is the only session information that is actually stored on the client side.) The default name for the cookie is PHPSESSID, although this can be changed in the PHP configuration files on the server (most hosting companies will leave it alone, however.) To reference the session Id in you PHP code, you would therefore reference the variable $PHPSESSID (it's a cookie name; remember that from Cookies?)

How do PHP sessions work? (not "how are they used?") - Stack Overflow

php session
Rectangle 27 1

Sessions in PHP are started by using the session_start( ) function. Like the setcookie( ) function, the session_start( ) function must come before any HTML, including blank lines, on the page. It will look like this: <?php session_start( );?><html><head> ....... etc The session_start( ) function generates a random Session Id and stores it in a cookie on the user's computer (this is the only session information that is actually stored on the client side.) The default name for the cookie is PHPSESSID, although this can be changed in the PHP configuration files on the server (most hosting companies will leave it alone, however.) To reference the session Id in you PHP code, you would therefore reference the variable $PHPSESSID (it's a cookie name; remember that from Cookies?)

How do PHP sessions work? (not "how are they used?") - Stack Overflow

php session
Rectangle 27 0

1: Have you set the length of the cookie correctly? Ensure it is set into the future using

2: I would also recommend, instead of deleting the cookie why not make it true or false. This would probably resolve your error with relation to deletion.

Personally I have never had any problem with setCookie in a similar usage to yours (mobile sites), but I always just use mobileEnabled and then set that to true or false, if it doesn't exist the PHP defaults to whatever they are using, if it does exist it means that client has a preference and uses whatever they have it set to.

I tried changing the value to "" instead of deleting the cookie by changing the cookie time to time() - 60, but had no luck.

I had a look through the HTTP Headers and see that the Set-Cookie parameter is not passed the second time around as against the first execution.Find that quite strange.

php - setcookie does not work the second time around - Stack Overflow

php cookies setcookie
Rectangle 27 0

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST.

php - setcookie isn't working - Stack Overflow

php cookies setcookie
Rectangle 27 0

You cannot set a cookie from one domain to another. Cookies are only working for domain you are using and purposely designed that way to protect cookie security.

But you can redirect user from domain1 to domain2 and set the domain2 cookie.

Set PHP cookies from DOMAIN1 to DOMAIN2 - Stack Overflow

php cookies set setcookie
Rectangle 27 0

Check your brower's cookies. Some browsers (firefox and chrome) have addons that allow you to see cookies as they come in so you can debug.

EDIT: The problem is 6000. That is wrong. use this: time() + 6000

Yeah I've been using a Chrome add-on but resorted to var_dumping $_COOKIE when it wasn't appearing in there either. I've tried using '.mydomain.co.uk' but it's still not working :(

cookies - PHP setcookie() not working - Stack Overflow

php cookies
Rectangle 27 0

Cookies don't kick in until after they are set and a new page request is sent. This is because cookies are sent with page requests, they just don't magically appear to a the server.

Your solution is to do a page refresh after setting the cookie.

How would I do a page refresh after setting the cookie? I don't think page refreshes can be done with php... Would I use header to redirect to the same page or use javascript?

You would use header() since you would do the redirect from the server.

cookies - PHP – setcookie() not working - Stack Overflow

php cookies