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.
Related
I am pretty new in php .so hopefully this all make sense . I am using below script to extract url from database.I want down-loader will popup in browser while reading the url from database....
$q=" Select url from videos where id = '".$_REQUEST['id']."' ";
$result=mysql_query($q);
while( $rows =mysql_fetch_assoc($result) )
{
$url=$rows['url '];
//here i want code to send this url to down-loader of browser..
//and browser should popup the down-loader
$myarray1=array("url "=>$url );
}
I have searched codes on google but i don't understand how to use for this scenario...
First of all, you need to fix the SQL Injection problem.
Use MySQLi instead of MySQL
Here's a code:
$request_id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
if(!empty($request_id)){
$mysqli = new mysqli("localhost", "user", "password", "database_name");
$request_id = $mysqli->real_escape_string($request_id);
$query = "SELECT url FROM videos WHERE id='" . $request_id . "'";
$query_result = $mysqli->query($query);
if(!empty($query_result)){
if($query_result->num_rows > 0){
$my_result_array = array();
while($row = $query_result->fetch_assoc()){
$my_result_array[] = $row['url'];
}
}
}
mysqli_close($mysqli);
}
Concerning the download problem, you need to redirect the user to a PHP page with a specific header
<?php
$file_name = "";
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment;filename=\"" . $file_name . "\"");
header("Cache-Control: max-age=0");
?>
You need to add the $file_name and the specific Content-Type.
Here's a list of Content-Types: http://davidwalsh.name/php-header-mime
In order to redirect a user to the download page, you can use the PHP header() function.
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) ..
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 am trying to update mysql table with AJAX and php script, but I am still receiving "304 Not modified" message. I have searched many questions here and also searched for it with google but without any luck... I am 100% sure all variables are sent with AJAX and received by PHP in correct form, I have checked it like this:
$tabulka=$_SESSION["uzivatel"];
$slovensky=testVstupov($_POST["slovensky"]);
$prelozene=testVstupov($_POST["prelozene"]);
$druh=testVstupov($_POST["druh"]);
$lekcia=testVstupov($_POST["lekcia"]);
$reset=testVstupov($_POST["reset"]);
$id=testVstupov($_POST["id"]);
$nula=0;
//echo $tabulka."#".$slovensky."#".prelozene."#".$druh."#".$lekcia."#".$reset."#".$id."#".$nula;
function testVstupov($data)
{
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
that echo is just to make sure all variables are filled with correct value
Then I try to update table, but it results with 304 message, variable $hodnoty is returned empty:
$pripojenie=mysqli_connect("localhost","user","password","database");
if (mysqli_connect_errno($pripojenie))
{
echo "Zlyhalo pripojenie do databázy: ".mysqli_connect_error();
}
if($reset == "false")
{
$hodnoty = mysqli_query($pripojenie, "UPDATE `$tabulka` SET slovensky=$slovensky, preklad=$prelozene, druh=$druh, lekcia=$lekcia WHERE id='$id'");
}
if(mysqli_error())
{
die('Zápis do databázy sa nepodaril. Chyba: ' . mysqli_error() ); //skjurajozimy.
}
//ukncenie spojenia s databazou
mysqli_close($pripojenie);
Same code in other php file but only to modify different collumns in same table works. This code works:
$pripojenie=mysqli_connect("localhost","user","password","database");
if (mysqli_connect_errno($pripojenie))
{
echo "Zlyhalo pripojenie do databázy: ".mysqli_connect_error();
}
$vysledok=mysqli_query($pripojenie, "SELECT skusane,spravne FROM `$tabulka` WHERE preklad='$data1'");
if(mysqli_error())
{
die('Výpis z databázy sa nepodaril. Chyba: ' . mysqli_error() ); //`skjurajozimy`.
}
$hodnoty = mysqli_fetch_array($vysledok);
$noveSkusane = $hodnoty['skusane']+1;
$noveSpravne = $hodnoty['spravne']+$data2;
$uspesnost = round($noveSpravne*$noveSkusane);
$hodnoty = mysqli_query($pripojenie, "UPDATE `$tabulka` SET skusane=$noveSkusane, spravne=$noveSpravne, uspesnost=$uspesnost WHERE preklad='$data1'");
if(mysqli_error())
{
die('Zápis do databázy sa nepodaril. Chyba: ' . mysqli_error() ); //`skjurajozimy`.
}
//ukncenie spojenia s databazou
mysqli_close($pripojenie);
collumns in my table are: id slovensky preklad druh lekcia skusane spravne uspesnost , where id is autoincrement.
Please, any suggestions, why update code doesn't work?
Have you tried:
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Pragma: no-cache' );
at the beginning of your PHP function?
Finally solution, problem was with ticks and spaces, so correct code here:
$hodnoty = mysqli_query($pripojenie, "UPDATE `$databaza`.`$tabulka` SET `slovensky` = '$slovensky', `preklad` = '$prelozene', `druh` = '$druh', `lekcia` = '$lekcia' WHERE `$tabulka`.`id` =$id;");
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