I created a PHP script that reads the data from mysql database and returns an output in json format.
The script works fine, but now I want to save the output in my cookie.
When I add the function setcookie("Messages",base64_encode(serialize($messages)),157680000000);
I have a Server Error 500 : Premature end of script headers.
How can I save the array $messages in the cookie?
----------------- PHP CODE -------------------
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT");
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Content-type: application/json");
include_once("include/common.php");
if (empty($uname)){
$uname = (!empty($_GET['u'])) ? $_GET['u'] : "";
$uname = (!empty($_POST['u'])) ? $_POST['u'] : $uname;
}
if (empty($limit)){
$limit = (!empty($_GET['limit'])) ? $_GET['limit'] : "";
$limit = (!empty($_POST['limit'])) ? $_POST['limit'] : $limit;
}
$isonline = is_online();
$user_obj = new User();
$user_info = $user_obj->getUserInfo($uname);
$msg_obj = new Message();
$msg_array = $msg_obj->getMessages($user_info[_USERID_COLUMN],$limit);
$messages = array();
$i = 0;
[...]
foreach( $msg_array as $id => $val ){
$messages[$i]['id_message']=$val['id_message'];
$messages[$i]['user']=$val['user'];
$messages[$i]['user_image']=$val['user_image'];
$messages[$i]['posted_time']=time2str($val['posted_time']);
if($options['link'] == "off"){
$messages[$i]['message']=htmlspecialchars_decode(cleaner($val['message']));
}else{
$messages[$i]['message']=htmlspecialchars_decode($val['message']);
}
$messages[$i]['mediatype']=$val['mediatype'];
$messages[$i]['mediaurl']=$val['mediaurl'];
$i++;
}
array_reverse($messages);
if(ceckCookie()){
setcookie("Messages",base64_encode(serialize($messages)),157680000000);
}
if( !$isonline && !empty($_COOKIE["Messages"]) ){
echo($_COOKIE["Messages"]);
}else{
echo(json_encode($messages));
}
is the data you are trying to save is huge ??
$_COOKIE can store under 4000 bytes...(Includes date, name, value, expiry) ..
Related
I use session_set_save_handler in a custom session class to use database storage. I have used database session storage for over a year. This has always worked fine and so has the captcha code that I wrote also almost a year ago. Problem I am having now is that the captcha code is no longer outputting the image. If I remove the require_once to the session class the image is outputted but the code is saved as if using session_start alone and not with the custom class. If I require the session class the image is not shown but the code is written as expected. I have used the same code for almost a year with no problems. I am at a total loss as to what is going on.
<?php
require_once('database.php');
require_once('config.php');
class FileSessionHandler
{
private $database;
private $life_time;
public function FileSessionHandler(){
$this->life_time = get_cfg_var("session.gc_maxlifetime");
$this->database = new database();
$this->database->newConnection (db_host,db_users_name,db_users_pass,db_users_prefix . db_users);
session_set_save_handler(
array(&$this,'open'),
array(&$this,'close'),
array(&$this,'read'),
array(&$this,'write'),
array(&$this,'destroy'),
array(&$this,'gc')
);
register_shutdown_function('session_write_close');
session_start();
}
function open($savePath,$sessionName){
return TRUE;
}
function close(){
return TRUE;
}
function read($id){
$data = "";
$time = time();
$newid = $this->database->sanitizeData($id);
$sql = "SELECT `session_data` FROM `" . tb_site_sessions . "`
WHERE `session_id`='{$newid}' AND `expires`>{$time}";
$this->database->executeQuery($sql);
if($this->database->numRows() > 0) {
$row = $this->database->getRows();
$data = $row['session_data'];
}
return $data;
}
function write($id,$data){
$newid = $this->database->sanitizeData($id);
$newdata = $this->database->sanitizeData($data);
$time = time() + $this->life_time;
$sql = "INSERT INTO `" . tb_site_sessions . "`
(`session_id`,`session_data`,`expires`)
VALUES('{$newid}','{$newdata}',{$time}) ON DUPLICATE KEY UPDATE
session_data='{$newdata}',expires={$time}";
$this->database->executeQuery($sql);
return TRUE;
}
function destroy($id){
$newid = $this->database->sanitizeData($id);
$sql = "DELETE FROM `" . tb_site_sessions . "` WHERE `session_id`='{$newid}'";
$this->database->executeQuery($sql);
return TRUE;
}
function gc($maxlifetime){
$time = time();
$sql = "DELETE FROM `" . tb_site_sessions . "` WHERE `expires`<'{$time}'";
$this->database->executeQuery($sql);
return TRUE;
}
}
?>
method of calling:
require_once('site-sessions.php');
$handler = new FileSessionHandler();
image headers:
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
Found the problem and it was simple. In the config file there was a blank line before the php tag. The blank line was messing with the headers and session calling. I didn't even think about looking in the config file since it hadn't been altered in a while. Just including the answer in case anyone else comes across a similar situation.
I am trying to return a value using php and AJAX but I get the following returned when doing so. This part of my code has been functional in previous projects so I am a little stumped as to why it is happening now.
The returned value:
‹������«VÊÏV²2ÔQ*.)V²qjÜ¥5¼���
it should return something like this:
{"ok":1,"status":"ok"}
The PHP I am using:
$response = array('ok' => 0);
if($results)
{
$response['ok'] = 1;
$response['status'] = ($visible == 'visible') ? 'ok' : 'no';
}
ob_clean();
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
echo json_encode($response, true);
exit;
Now if I removed the code and put into its own file it works fine. I have all files and database set to UTF-8 also.
You have a duplicate closing parentheses on line 2.
It should be:
$response = array('ok' => 0);
if($results)
{
Fixing that, your code works for me:
{"ok":0}
And if I force $results = true; :
{"ok":1,"status":"no"}
I feel so stupid now, I was running ob_gzhandler within my ob_start();
Apologies to all.
I am having trouble executing this code in my index.php.
It says 'CartAction not set'
I need your help php gurus. I can display any files you need to fix this error.
Here is the code:
// Handle AJAX requests
if (isset ($_GET['AjaxRequest']))
{
// Headers are sent to prevent browsers from caching
header('Expires: Fri, 25 Dec 1980 00:00:00 GMT'); // Time in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
header('Content-Type: text/html');
if (isset ($_GET['CartAction']))
{
$cart_action = $_GET['CartAction'];
if ($cart_action == ADD_PRODUCT)
{
require_once 'C:/vhosts/phpcs5/presentation/' . 'cart_details.php';
$cart_details = new CartDetails();
$cart_details->init();
$application->display('cart_summary.tpl');
}
else
{
$application->display('cart_details.tpl');
}
}
else
trigger_error('CartAction not set', E_USER_ERROR);
}
else
{
// Display the page
$application->display('store_front.tpl');
}
It's because your code is expecting a parameter named 'CartAction' in the url
Example:
www.yoursite.com/?CartAction=ADD_PRODUCT
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character. Source
You check if $_GET['CartAction'] has a value ( from the above url this superglobal variable has the value 'ADD_PRODUCT' )
What #Mackiee (in comments) and your error message are both telling you is that the problem is that there is a query parameter missing. The URL that calls this needs to include either ?CartAction=ADD_PRODUCT or &CartAction=ADD_PRODUCT
I have a file text file in which i am saving user id via file_put_contents
i want to display that user id before sending it to view function
here is my code
i try myself bt not geting result....
$name = $this->session->userdata('name');
$id = $this->session->userdata('id');
file_put_contents($filename,json_encode(array('id'=>$id,'name'=>$name)));
$response = array();
$response = json_decode(file_get_contents($filename));
if ($response->name==1){
echo $this->session->userdata('name');
}
echo json_encode($response);
this dont work that i want to display bt if i remove this if condition then i get my result in view file
if ($response->name==1){
echo $this->session->userdata('name');
}
thanks....
$response->name it will be a string, not an int.
Replace:
if ($response->name==1){
echo $this->session->userdata('name');
}
With:
if ($response->name){
echo $this->session->userdata('name');
}
Update:
You stated somewhere in the comments that you want to check for the user id, but in the code you check username. Also inside the if condition, you should use data from $response and not the one from session. That said:
if ($response->id == 1){
echo $response->name;
}
As a side note, are you sure that id and name exists in the session ?
im not clear why do you have
if ($response->name==1){
but any way try this
if you want to prezerve json object stucture you need the second param to be true
json_decode(file_get_contents($filename) ,true);
and you need some json headers that you can find in the botom
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$name = $this->session->userdata('name');
$id = $this->session->userdata('id');
if(!empty($name)){
if(!is_file($filename)){
touch($filename);
chmod($filename,0777);
}
file_put_contents($filename,json_encode(array('id'=>$id,'name'=>$name),true));
$response = array();
$response = json_decode(file_get_contents($filename) ,true);
if (empty($response->name)){
echo json_encode(array('error'=>'empty response name'),true);
die();
}else{
echo json_encode($response);
}
}else{
json_encode(array('error'=>'no username'),true)
}
there is my messaging system inside my admin its for codeigniter
http://dl.dropbox.com/u/72626795/messaging.zip
I have a simple search form with a search box and a result box.
When I type a search word a request is created like: http://www.site.com/php_handler.php?s=hello
In the php script and a result is given back to the script this way:
<?php return $s; ?>
The problem is that my htmlrequest stops at readyState 3 it doesn't get to 4.
The javascript looks like this:
var xmlhttp = sajax_init_object();
function sajax_init_object() {
var A;
try {
A=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
A=new ActiveXObject("Microsoft.XMLHTTP");
} catch (oc) {
A=null;
}
}
if(!A && typeof XMLHttpRequest != "undefined")
A = new XMLHttpRequest();
if (!A)
sajax_debug("Could not create connection object.");
return A;
}
function getSearchItem()
{
gs=document.forms.mainform.resultsfield;
var searchword=document.forms.mainform.searchform.value;
if (searchword.length>=3)
{
setWaitCursor();
clearResults();
var uri = "http://site.com/ajax_handler.php?s="+searchword;
console.log(uri);
xmlhttp.open("GET", uri, true);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4) {
processResults(xmlhttp.responseText);
removeWaitCursor();
}else{
console.log(xmlhttp.readyState);
}
}
xmlhttp.send(null);
}
else
{
alert("please add at least 3 characters .");
}
}
Can someone tell me why it stops at 3?
edit: here is also the php code:
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
session_start();
//include main file
require_once($_SESSION["FILEROOT"] . "xsite/init.php");
//check if formulier is posted
$zoekterm = C_GPC::getGETVar("s");
$s="";
if ($zoekterm != "") {
$query="SELECT number,name,city,zib,zip_annex FROM articles WHERE version='edit' AND (naam LIKE '%$school%' OR brinnummer='$school') ORDER BY name";
if ($rs=C_DB::fetchRecordSet($query)) {
while ($row=C_DB::fetchRow($rs)) {
if ($row["plaats"]!="") {
$s.=$row["name"].", ".$row["city"]."|".$row["number"]."\n";
} else {
$s.=$row["name"].", ".$row["zip"].$row["zip_annex"]."|".$row["number"]."\n";
}
}
}
}
return $s;
?>
edit:
I missed a semicolon in my php script and now the ready state only gets to 2
edit:
The problem is even different. It gets to 4 but it doesn't show the result text.
1> Don't send Cache-Control: post-check=0, pre-check=0. These don't do what you think they do, and they're entirely unnecessary.
2> Your AJAX results page needs to send a Content-Length or Connection: Close header.
3> Try adding a random to your request URL to ensure you're not looking at a stale cache entry.
ReadyState 3 => Some data has been received
ReadyState 4 => All the data has been received
Maybe the XMLHTTPRequest object is still waiting for some data.
Are you sure your php script ends correctly ?
Is the content-length alright ?
To debug this you have two options, type the URL directly into the browser [since you are using a GET] and see what is happening.
OR
You can use a tool such as Fiddler and see what is exactly happening with the XMLHttpRequest