php setcookie fails under php5 - php

I created this simple script which will either set a cookie with three values or retrieve the cookies values if they are already set. On my server running PHP4, everything works. On my server with PHP 5 (5.2.11), the script fails to set the cookie in the browser. I already checked if output buffering is enabled in my php.ini and it is. Does anyone have any ideas as to why this fails to work?
<?php
echo "<!DOCTYPE html>";
echo "<body>";
if (!isset($_COOKIE['taeinv'])) {
echo "No cookie set... Attempting to set a new cookie.";
$user = "testuser";
$role = "admin";
$expire = "true";
$halfHour = 1800;
setcookie("websitename[Expire]", $expire, time()+$halfHour);
setcookie("websitename[User]", $user, time()+$halfHour);
setcookie("websitename[Role]", $role, time()+$halfHour);
}
if (isset($_COOKIE['websitename'])) {
echo "Cookie Values:";
echo "<br />";
foreach ($_COOKIE['websitename'] as $name => $value) {
echo "<b>$name</b> : $value <br />\n";
}
}
echo "<br />";
echo "<a href=logout.php>Logout</a>";
echo "</body>";
echo "</html>";
?>

You have to set the cookie before any output to the browser. Try moving all echo lines somewhere below the setcookie call. You could do something like this:
<?php
$set = false;
if (!isset($_COOKIE['taeinv'])) {
$set = true;
$user = "testuser";
$role = "admin";
$expire = "true";
$halfHour = 1800;
setcookie("websitename[Expire]", $expire, time()+$halfHour);
setcookie("websitename[User]", $user, time()+$halfHour);
setcookie("websitename[Role]", $role, time()+$halfHour);
}
echo "<!DOCTYPE html>";
echo "<body>";
if ($set) {
echo "No cookie set... Attempted to set a new cookie.";
}
if (isset($_COOKIE['websitename'])) {
echo "Cookie Values:";
echo "<br />";
foreach ($_COOKIE['websitename'] as $name => $value) {
echo "<b>$name</b> : $value <br />\n";
}
}
echo "<br />";
echo "<a href=logout.php>Logout</a>";
echo "</body>";
echo "</html>";
?>

That worked on my old PHP4 server, but not on PHP5.

Use output buffering – ob_start() and ob_end_flush().
Example:
<?php
ob_start();
echo '<p>Initializing…</p>';
setcookie('myLanguage', 'PHP');
ob_end_flush();
// you can continue your PHP code here…
?>

I had a similar problem but it was only in Chrome that the cookies disappeared. Firefox was fine.
Setting all the parameters in the setcookie function fixed it.
This sets the cookie but Chrome drops the cookie within a click:
setcookie('uname', 'Joe', time()+3600*24);
This sets the cookie and the browser retains it:
setcookie('uname', 'Joe', time()+3600*24, '/', 'www.domain.com', false, false);

Related

Variable set on true looses value after first if-statement ---?

This seems very bizarre to me.
At the beginning of my php-script I am defining a debug variable. In the script I am using this variable to test my functions etc. p.p. BUT:
After my first if-Statement, the variable $debug is not set on true but blank... what am I doing wrong:
Here is my code:
$debug=true;
if($debug){
echo 'Testausgabe: </br></br>';
include 'jsonData.php';
include 'database.php';
$ini_config=$ini_config = parse_ini_file("config.ini", true);
echo "Einbindung erfolgt!".LNBR;
$debug=true;
echo $debug;
echo LNBR;
}
function dropdownGen($link,$ini_config){
$drops=$ini_config['dropDowns'];
foreach($drops as $key => $liste){
$data=json_liste($link,$liste);
echo LNBR;
echo "droplist_parse=JSON.parse('".$data."');";
echo "ddslickNoImage(droplist_parse,'".$liste."');";
echo LNBR;
echo "ddslickNoImage_Toggle(droplist_parse,'".$liste."');";
echo LNBR;
}
}
function dropdownImgGen($link, $ini_config){
$images=$ini_config['image_links'];
print_r($images);
echo "<br><br>";
foreach($images as $key => $liste){
$link='..\\'.utf8_decode($liste);
echo $link;
echo LNBR;
$data=json_imageList($link);
echo $data;
echo LNBR;
echo "ddslickImageList(".$data.",'".$key."');";
}
}
if($debug){
echo $debug;
echo LNBR;
echo 'Testausgabe: </br></br>';
dropdownGen($link,$ini_config);
echo LNBR;
dropdownImgGen($link,$ini_config);
echo LNBR;
}

Login Redirect PHP with Special Function

I have the following function set up in my includes and class file:
function makeMessage($message, $href, $onclick = '', $redirect = '', $linktext = 'Click here to continue') {
echo "<center>";
echo "<strong>" . $message . "</strong><br>" . $linktext . "";
if (! empty ( $redirect ))
echo "<br><meta http-equiv=\"refresh\" content=\"" . $redirect . "\"><strong>You should be redirected within a few seconds...</strong>
<br><br>Or let's check out now!";
echo "</center>";
}
However, on my register and login, add to order all uses this function, but I'm unsure what broke. Here's how I'm using it:
if ($post ['price_id'] == 0) {
$WALM->makeMessage ( 'You are now logged in!', 'order_now.php', '', 'order_now.php' );
} else {
}
The problem is, that it's not working with the meta refresh, does anyone have any help here to change this about and to what?
tags should be placed within the section. Maybe it's the problem?
You could try a JS redirect as follow:
function makeMessage($message, $href, $onclick = '', $redirect = '', $linktext = 'Click here to continue') {
echo "<center>";
echo "<strong>$message</strong><br/>$linktext";
if (!empty ($redirect))
echo "<br>
<script type=\"text/javascript\">
window.location = \"$redirect\"
</script>
<strong>You should be redirected within a few seconds...</strong>
<br><br>Or let's check out now!";
echo "</center>";
}
EDIT
You can not send headers considering that the redirect is not to the top of the page. If you want to delay the redirect, you can use the setTimeout() JS function
Use header() instead of <meta>
function makeMessage($message, $href, $onclick = '', $redirect = '', $linktext = 'Click here to continue') {
echo "<center>";
echo "<strong>" . $message . "</strong><br>" . $linktext . "";
if (! empty ( $redirect )) {
header("refresh:5;url=$redirect");
echo "<br><strong>You should be redirected within a few seconds...</strong>
<br><br>Or let's check out now!";
}
echo "</center>";
}

passing one variable from one page to another for pdf generation

I have a page that I have used to retrieve some excel data written in php... by using phpexcel... this part provides me company information
echo '<form action="final.php" method="post">';
echo "<table border='1'>";
for ($rowcount = $rowCompanyInfoStart; $rowcount <= $rowCompanyInfoEnd; $rowcount++)
{
//$data = $objWorksheet->rangeToArray('A1:' . $maxCell['column'] . $maxCell['row']);
$rangeCoordinates = $colCompanyInfoStart . $rowcount . ':' . $colCompanyInfoEnd . $rowcount;
$rowData = $sheet->rangeToArray($rangeCoordinates, NULL, TRUE, FALSE);
echo "<tr>";
$companyname=$worksheet->getCell($column.$row)->getValue();
// echo $companyname;
foreach($rowData[0] as $result)
{
echo "<td>".$result." </td>";
}
echo "</tr>";
}
echo "</table>";
echo "<br />";
echo '<input type="submit" name="sub" value="Convert into PDF" />';
// echo '<input type="text" name="resName" value="$result">';
function getdatan()
{
global $result; // declare as global
return $result;
}
echo '</form>';
this part is where I get company information... it looks like the table area shown down part...
I retrieve info and able to show as "$result" variable and with submit button named "convert it into pdf" I send it into other php page where I use TCPDF ....
Normally, this part of second page
$pdf->SetFont('times', 'BI', 12);
// add a page
$pdf->AddPage('L', 'A4');
if(isset($_POST['submit']))
{
$result = $_GET['resName'];
$pdf->Write(20, $result, '', 0, 'C', true, 0, false, false, 0);
}
// set some text to print
$txt = <<<EOD
TCPDF Example 003
Custom page header and footer are defined by extending the TCPDF class and overriding the Header() and Footer() methods.
EOD;
// print a block of text using Write()
// $pdf->Write(20, $resultt, '', 0, 'C', true, 0, false, false, 0);
// ---------------------------------------------------------
ob_end_clean();
//Close and output PDF document
$pdf->Output('example.pdf', 'I');
However, I am unable to print "$result" in the second page... can you help me about how to print this table on pdf...
PS: please clarify your help...
Try this
Change :
echo '<input type="submit" name="sub" value="Convert into PDF" />';
To:
echo '<input type="submit" name="resName" value="Convert into PDF" />';
EDIT
Put this at the begining of your second page:
var_dump($_POST);
just to check what you are receiving from the first page.
Also change :
$result = $_GET['resName'];
to this:
$result = $_POST['resName'];
ok since I was on my own... I found solution by myself ....
on the first page of PHP...
session_start();
//rest of your code and then...
if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo '<form action="final.php" method="POST">';
$tablo="<br />";
$tablo = $tablo."<table border=\"1\" cellpadding=\"2\" cellspacing=\"2\" align='center'>";
for ($rowcount = $rowCompanyInfoStart; $rowcount <= $rowCompanyInfoEnd; $rowcount++)
{
//$data = $objWorksheet->rangeToArray('A1:' . $maxCell['column'] . $maxCell['row']);
$rangeCoordinates = $colCompanyInfoStart . $rowcount . ':' . $colCompanyInfoEnd . $rowcount;
$rowData = $sheet->rangeToArray($rangeCoordinates, NULL, TRUE, FALSE);
//fazla bosluk olursa bunları aç ya da hucre bos mu kontrol et (cellExists ile)
//rowData = array_map('array_filter', $rowData);
//$rowData = array_filter($rowData);
$tablo= $tablo."<tr >";
$companyname=$worksheet->getCell($column.$row)->getValue();
// echo $companyname;
foreach($rowData[0] as $result)
{
$tablo= $tablo. "<td>".$result. " </td>";
}
$tablo= $tablo. "</tr>";
}
$tablo= $tablo. "</table>";
echo $tablo;
echo "<br />";
if($_SERVER['REQUEST_METHOD'] != 'POST') {
echo "SESSION Not AVAIL. first run.";
}
else{
$_SESSION['varname'] = $tablo;
}
echo '<input type="submit" name="resName" value="Convert into PDF" />';
}
so here I used both "POST request" instead of just "POST". It sends "REQUEST" without any "POST DATA"... and then for sending the data I created a a variable called "$table" I put all my rows and cell info into that and created a session so that second PHP can retrieve it....
ON the second PHP page I answer "request" and open "session" just like that
session_start();
//rest of your code and then...
if($_SERVER['REQUEST_METHOD'] != 'POST') {
echo "SESSION Not AVAIL. first run.";
$tablo = $_SESSION['varname'];
echo "SESSION now set.";
}
else{
$tablo = $_SESSION['varname'];
//echo "SESSION SET, value: " .$_SESSION['varname']. " and ". $_SESSION['color'];
}
if (isset($_SESSION['varname'])){
$tablo = $_SESSION['varname'];
// print_r($_SESSION);
//echo "Session Set: <br/>" . $tablo;
}
else{
echo "Session not set. Tablo is empty";
// echo "Session Set: <br/>" . $tablo;
}
so that's it!

$_GET OR escape string being unpredictable. Please explain?

i simply pass 3 values to the URL and while testing i was trying to echo them back to the screen but it will only echo each value once even though i have set it to echo at various points. once i escape the value it wont let me echo it. Why is this?
<?php
session_start();
if (isset($_SESSION['SESSION_C']) && ($_SESSION['SESSION_C']==true))
{
$getyear = $_GET["Year"];
echo $getyear; (IT WILL ECHO AT THIS POINT)
$getyear = mysql_real_escape_string($getyear);
echo $getyear; (BUT WONT ECHO HERE)
$getsite = $_GET["Site"];
echo $getsite;
$getsite = mysql_real_escape_string($getsite);
echo $getsite;
$getsite = str_replace(' ', '', $getsite);
echo $getsite;
$getdoc = $_GET["Doc"];
echo $getdoc;
$getdoc = mysql_real_escape_string($getdoc);
echo $getdoc;
}
else
{
echo "sessionerror";
}
?>
mysql_real_escape_string() requires a open connection to mysql. Otherwise it will return false. I guess var_dump($getdoc); will give you boolean(false).
You'll have to call mysql_connect() before that code.

Comparing 2 exact same strings returns false

I have a variable that is posted through a html form:
$_POST['ref']
And a variable that is pulled from a table in a database:
$row['ref']
i have a basic comparison script to check if they are both the same:
$ref = $_POST['ref'];
$result = mysql_query("SELECT * FROM logbook.job");
if (!$result) {
die("Query to show fields from table failed");
}
$row = mysql_fetch_array($result);
$refdb = $row['ref'];
$refform = $_POST['ref'];
echo $_POST['ref'] ."<br>". $row['ref'] . "<br><br>";
if ($refdb == $refform) {
echo "Yes they are<br><br>";
}
else {
echo "No they are not<br><br>";
}
if (is_string($_POST['ref']))
{
echo "Yes";
} else {
echo "No";
}
echo "<br>";
if (is_string($row['ref']))
{
echo "Yes";
} else {
echo "No";
}
Which outputs:
G2mtxW
G2mtxW
No they are not
Yes
Yes
I echo them both out. Than i ask if they are the same. Then i check whether each is a string.
How come they are not the same? How can i get them to match
Any help would be appreciated
Try using the binary-safe comparison for String:
result = strcmp($str1, $str2);
If the result is 0, then both are the same. Otherwise, they aren't.
One of your strings (probably the one from the DB) might be null-terminated. I've tested the following
$foo = "abc\0";
$bar = "abc";
echo "$foo\n$bar\n";
if($foo == $bar)
echo "Equal.";
else
echo "Not equal."
Output is
abc
abc
Not equal.
Try var_dump-ing both values, check their lengths and inspect them using view-source. They are different in someway.
echo $status_message;
echo "Accepted";
if(strcmp($status_message,"Accepted")==0)
{
echo "equal";
}
else
{
echo "not equal";
}
?>
$row['status'] is a field from table

Categories