Unserialized COOKIE returns empty - php

I'm trying to save an array into a cookie, in a serialized manner. So what I do is this:
$serial_auth = serialize($_SESSION['auth']);
setcookie("auth_cookie", $serial_auth , 2592000 + time());
and in the next page I'm trying to use this data like this:
if(isset($_COOKIE['auth_cookie']))
{
$_SESSION['auth'] = unserialize($_COOKIE['auth_cookie']); //but it returns an empty array.
}
now the strange thing is the whole thing works in my localhost, but it does not work on 000webhost site.
and a note: when I try to echo those, I get this:
$_SESSION['auth'] =
Array ( [status] => ok [userid] => 1 [username] => user11 [visiblename] => user11 )
SERIALIZED =
a:4:{s:6:"status";s:2:"ok";s:6:"userid";s:1:"1";s:8:"username";s:6:"user11";s:11:"visiblename";s:6:"user11";}
This may be a PHP configuration issue, but I would like to learn if there is a way for this, without changing any PHP configuration. Thanks for any help.

This has severe security drawbacks and shouldn't be done.
An attacker can set the cookie value to anything, including serialized objects. These objects may execute code when recreated. So an attacker may execute code on your machine by sending you a properly crafted serialization string! One cannot want attackers to be able to do this.
See the warning at the bottom of this page: http://www.php.net/manual/en/function.unserialize.php
The second thing is: Why the hell do you need the authentication info in a separate cookie, and what is connected with it? What would an attacker be able to do if he changes any of the values, especially the userid or the status? I assume he might gain access to things he shouldn't be able to.

Related

parse_url giving host name as stars when debugged (but can still get value)

Using PHP 5.5.12
Using CakePHP 2.6.7
Running
debug($url); // output = "http://google.co.uk"
debug(parse_url($url));
/* output = array(
'host' => '*****',
'scheme' => 'http'
)
*/
I had been using this without trouble but now copy/pasting a section of my code to have it as method (to save repeating myself) has started giving me this output. But testing it back in the same place I had it originally gives me this output too.
Can anyone explain why the hostname is stars and why the rest of the array doesn't appear (I realise all other elements should be expected to be NULL)?
Edit
Just tried it again with a url that had a path to a page after the host. The path shows up fine but the host is still starred out.
Partial Answer
Just thought to try debug(parse_url($url)['host']) and it prints the host correctly. I realised that the other elements would only be set if they exist in the url.
However, can anyone explain why printing out the array prints several stars instead of the hostname even though it is definitely stored there?
The reason this happens is because of how debug() works. Many moons ago people were not pleased that they could accidentally have their database credentials dumped out in error pages (which use the same underlying code as debug()). Because of this, debug() and Debugger::export() blacklist a set of array keys that could have database credentials. The following keys are replaced with ***'s:
password
login
host
database
port
prefix
schema

PHP store a single variable on the server?

I want to store a single integer like so:
<?php
$_SERVER['amount'] = 54;
echo($_SERVER['amount']);
?>
And be able to modify it, as well as be accessed from every new php session. However whenever the session ends the server variable disappears. How can i store a single variable on the server without a database? A .txt file seems kinda unnecessary for 2 characters stored.
Your storage options are a file, a hardcoded variable in the PHP code, a database table, a cookie or a session variable, as I understand it. Probably the most elegant solution if you already are using a database is to add a new table with your permanent data variables.
Another solution, if you are looking for a quick and dirty solution, is to add a global php variable with a magic number, which is really what you are trying to do with your server variable, eg global $_AMOUNT = 54; // The amount is always 54 for all users. That doesn't really meet your requirement of being able to modify it each time the page is accessed, though.
$_SERVER is a superglobal, which is read from a file each time PHP is initiated on every pageload. You are not writing to the file that the variable is read from, and so it resets each time the script executes.
Just make a database table, in my opinion. Make one row for the table, amount. I am willing to bet the table will grow over time as you add more global variables.
You could use file_put_contents and create a kind of cache file then use file_get_contents to retrieve the data..
file_get_contents AND
file_put_contents
something like
$data = array(
'something' => 'this',
'somethingelse' => 'again',
);
$settings = json_encode($data);
file_put_content( 'settings.txt', $settings);
//then
$texstSettings = file_get_contents('settings.txt' );
$settings = json_decode(texstSettings);

CakePHP Variable containing an array of models becomes inaccessible?

So I'm building this small REST API for a part of a website so I can load comments asynchronously, after the main content has loaded. But every time my dataset goes above 25 entries the variable where I store the comments becomes completely inaccessible.
This is exactly the database find operation I'm doing:
// A nice default before responding
$response = array('status'=>'error','message'=>'Request incomplete');
// [...] Some validation stuff
// $response is perfectly accessible here
$response = $this->Comment->find(
'threaded',
array(
'conditions' => array(
'Comment.object_class' => $query['object_class'],
'Comment.object_id' => $query['object_id'] ,
'Comment.status' => 'approved'
),
'order' => 'Comment.created ASC'
// No limits, I need all the comments
)
);
// $response is not accessible anymore
// So my JSON response below comes absolutely empty;
$this->set('response',$response);
$this->set('_serialize',array('response'));
By the time I use $this->set('_serialize',array('response')); to be able to send the JSON response the $comments variable is still inaccessible, so my response comes back empty, at 0 length, which of course is pretty bothersome and very confusing.
I've experienced this problem before and have found that it solves by requesting a limited set of entries, but in this case I need the entire comment list, don't wanna do several requests and kill the purpose. Is there a limit to what Cake can retrieve from the database and keep usable in the Controllers? Am I missing something here?
I also tried "manually " doing a json_encode($response); but since the problem is that the $response var is inaccessible/empty then of course it fails as well.
The json response does work for some 25 comments or less, but many of the website entries have more comments than that, up to 100 comments! How can I solve this weird issue?
So after souting the Internet in search of a concrete answer and ending up in the #cakephp IRC channel, a very kind fellow suggested my data may have some encoding mistakes.
Turns out he was correct about it, and the comments table still had some comments that were encoded as latin1. Back in the day I moved the database to utf8, but it was just a charset change, not an actual text encoding conversion for every entry.
After a quick search I found this post which instructs you about how to move loads of data from latin1 to utf8 with three simple cli lines.
I hope this serves someone else that may encouter this issue and doesn't know what to do about it :)
Thanks to those who commented on the question.

CodeIgniter Session syntax

Can someone quickly help me out with CodeIgniter's syntax. I need to access an array I stored in the session's userdata and I cant figure out the proper syntax.
<?php echo $this->session->userdata['user_session']['first_name']; ?>
gives me this error:
Fatal error: Cannot use object of type stdClass as array
All of the answers given in this Question dont work:
Access array variable in session (CodeIgniter)
This is how you get session data:
echo $this->session->userdata('first_name');
Been a while since I've worked in Codeigniter, but if I can remember correctly, when you store an array like you've stated, you'd call it like this:
$this->session->userdata("user_session")['first_name'];
Let me know if that works?
Or you can store that data to a variable, and call the array that way. Like such:
$data = array("bar" => "the_value");
$this->session->set_userdata("foo", $data);
$foo = $this->session->userdata("foo");
echo $foo["bar"]; //Outputs the_value
Let me know if that helped.
However, just to let you know.. Normally, storing the session data goes as follows:
$this->session->set_userdata("first_name", "value");
Really no need to go and set your own array inside of userdata, because that's generally what the userdata array is for.
I found the proper syntax. Well, at least one way to go about it. #Matt GrubB was the closest and put me on the right track.
$temp_session = $this->session->userdata('user_session');
echo $temp_session->first_name;
Since userdata is an object full of info created when I query my database, the easiest way to access the data is to take it and put it in another temporary array. You then have to stab it. I kept stumbling by trying to do $this->temp_session->first_name or something of the like.

How to use Request::factory()->execute() to call an script from another library in the same host

I'm using Kohana 3.2, and I want to be able to call another script (unrelated to Kohana, outside of its 'jurisdiction') that returns a application/json response.
When I tried using:
$response = json_decode(Request::factory('/scripts/index.php?id=json')->execute()->body());
It errors out saying there's no route to scripts/index.php. So I tried using Request_Client_External
Request_Client_External::factory()->execute(Request::factory('/scripts/index.php?page=s'))->body();
Gives me Request_Exception [ 0 ]: Error fetching remote /scripts/index.php?page=s [ status 0 ] Could not resolve host: scripts; Host not found. It appears it need a full flagged URL using http/https, but how to avoid the overhead of it doing a real external request?
Doing a
Request::factory(url::site('/scripts/index.php?page=s', 'http'))->execute()
works but is it considered "external"?
The short answer to your question is that the only way to use Request::factory()->execute() to achieve that is to use pass it the full url (with whatever "overhead" that entails, which shouldn't be too much: your server's probably quite good at talking to itself).
Otherwise, ideally you'd put the functionality of scripts into a library and call that from Kohana. However it sounds like that's not an option for you. If you have to leave /scripts/index.php untouched and insist on an 'internal' request, you could use PHP's output buffering, as illustrated below. But there are a bunch of caveats so I wouldn't recommend it: the best way is passing a full url.
// Go one level deeper into output buffering
ob_start();
// Mimic your query string ?id=json (see first caveat below)
$_GET = $_REQUEST = array('id' => 'json');
// Get rid of $_POST and $_FILES
$_POST = $_FILES = array();
// Read the file's contents as $json
include('/scripts/index.php');
$json = ob_get_clean();
$response = json_decode($json);
Some caveats.
Firstly, the code changes $_GLOBALS. You probably don't use these in your Kohana code (you use $this->request->get() like a good HMVCer, right?). But in case you do, you should 'remember' and then restore the values, putting $old_globals = $GLOBALS; etc. before the above code, and $GLOBALS = $old_globals; after.
Sessions: if your /scripts/index.php uses `session_start() this will cause a warning if you've already started a session at this point in Kohana.
Note that all variables set in scripts/index.php will remain set in the context you're in. If you want to avoid possible conflicts with that context, you'd start a new context, i.e. wrap the above into its own function.
Finally, you'd also need to make sure that /scripts/index.php doesn't do anything like Kohana::base_url = 'something_else', or touch any other static attributes, or do something catastrophic using this.

Categories