How to read session variables from bootstrap.php file - session

Is there any any way to read session from bootstrap file.
App::uses('CakeSession', 'Model/Datasource');
$value = CakeSession::read('User.id');
I tried this code. But fail to read. Please help me out ..

For future visitors,
Looking for Cakesession object in bootstrap.php is a little weird but if you really must do it, do it this way:
App::import('Model/Datasource', 'CakeSession');
$Session = new CakeSession();
// $userId = $Session->read("Auth.User.id");
Check the difference between App::uses() (attempted by OP) and App::import() in documentation.

rather than do all the initialisation overhead, I would here (and just here in bootstrap.php) resort to a basic php stuff:
session_start();
debug($_SESSION);

Related

View::make in Phpunit

I've a function that returns a View::make($string). I want to test that this function did indeed return an instance of View object. $string points to a file that does exist.
When I try to run this function within Phpunit it doesn't seem to finish. How can I test in Phpunit that a View object was created?
Laravel has helper methods specifically designed for testing views.
Some of them include:
$response = $this->get('/path/to-your-route');
$response->assertViewIs($value);
$response->assertViewHas($key, $value = null);
$response->assertViewHasAll(array $data);
$response->assertViewMissing($key);
More info can be found here: https://laravel.com/docs/5.5/http-tests#available-assertions
If you need to assert that something is an instance of something else, you can try the following:
$this->assertInstanceOf($expected, $actual);
When you provide invalid string the view object will not be created and will throw an exception. Not sure what you have in your function that prevents the exception, but the way to go around this issue, is to include this line in the failing test:
$this->expectException(InvalidArgumentException::class);
The issue stemmed down from usage of var_dump as I wanted to see the object in question. As nothing was presented in output, I assumed that had to do with View::make rather than outputting the object to the console.

laravel: get name of active log at runtime

I need to know the name of the current log in an app Laravel 5.
Try search for this on Iluminate\Log\Writer.
Only see $path var on call to some functions, but I don't understand how to get this value.
Basically, I need to compress the file and send it if the app gets some exceptions. For this, I need to know the name of active log.
My app conf log for daily rotation and see name of logs such laravel-2016-04-29.log
I know the name using PHP, but I imagine it is possible to know using the Log class itself.
The best I've thought
use Carbon\Carbon;
...
$carbon = new Carbon();
$log = storage_path().'/logs/laravel-'.$carbon->toDateString().'.log';
I think there is a better way
I happened to dig a little bit into Laravel logging a few days ago and possibly have a solution for you.
Log::info('abc');
foreach (Log::getMonolog()->getHandlers() as $handler) {
$stream = $handler->getStream();
if ($stream) {
$meta = stream_get_meta_data($stream);
echo $meta['uri'] . "<br/>";
}
}
This will output paths of log files that have been written to.
Otherwise getStream() will return null and therefore path cannot be extracted so easily. It is stored in url property of Monolog\Handler\RotatingFileHandler, unfortunately protected, therefore you would need to extend this class to get the path.

CakePHP 1.3 - Calling Shells from a Controller?

I cannot for the life of me figure out how to call a shell from a controller.
We have a background process that packages up data in a .pdf, and we don't want to bog down the page loads waiting for this to occur, so we want to put all this processing in a shell.
I've figured out how to pass values to a shell with $this->args
I know you can use App::import('Shell','TestShell')... but after that I am lost.
How do I call the main() function of the shell within a controller?
In Cake 1.3, I was able to get it working by doing the following:
App::import('Shell', 'Shell');
App::Import('Vendor', array('shells/shell_title'));
$myShell = new ShellTitleShell(new Object());
$myShell->initialize();
$myShell->someAction();
I should be more focused reading the question :/
Could do it in Cake2, not sure how different would it be for 1.3. :?
<?php
App::import('Console/Command', 'AppShell');
App::import('Console/Command', 'HelloWorldShell');
$h = new HelloWorldShell();
$h->dispatchMethod('main');
?>
Windows:
If you do not have your environment variables set you will need to provide location of PHP executable.
C:\wamp\bin\php\php_v\php.exe C:\wamp\www\cakephp\cake\console\cake.php test this_arg_0 this_arg_1
Linux:
You may already have your php location defined. If not, you may need to export it to your $PATH or provide full path to php
php /var/www/html/cakephp/cake/console/cake.php test this_arg_0 this_arg_1
main() function will be called by default.
Hope it helps!

Get environment inside controller

I have a situation in one of my controllers that should only be accessed via AJAX, I have the following code.
if (!$request->isXmlHttpRequest()) {
$response = new Response();
$response->setContent('AJAX requests only!');
return $response;
}
When I am testing this gives me an issue because the request hasn't actually been made via AJAX. This then breaks my tests every time. How should I go about working around this?
My Ideas:
I have tried to set a server header but have had absolutely no success.
Check if I am in the test environment in the controller and don't do the check if it is. I know this is dirty, but it would work. :-/ The problem was that I couldn't figure out how to discover what environment I am in.
Anyone else have any other ideas or tips that I am missing to get one of the above to work?
Of course in Icode4food's case, it's better to use Matt's solution, but here is how to find the current environment:
$this->container->getParameter(‘kernel.environment’)
Looking at the code for isXmlHttpRequest in class Request and method getHeaders in class ServerBag, the piece of code below should do the trick:
$client->request(
'GET',
'/path/to/test',
array(),
array(),
array(
'HTTP_X-Requested-With' => 'XMLHttpRequest',
)
);
I did not test it personally but I think it should works. The line of code below in Request is used to check if the http request is a XmlHttpRequest.
return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
In the code, $this->headers is set using:
$this->headers = new HeaderBag($this->server->getHeaders());
The method getHeaders creates an array of headers. Each server variable starting with HTTP_, plus some special server variables like CONTENT_TYPE, are put in this array.
Hope this helps.
Regards,
Matt

What is the safest way to store a password using Code Igniter?

I am using Code Igniter for my current project.
As of now, I am using MD5 for password hashing, but I have read at a lot of places, that it is not a good practice to do so.
What should I go with?
Using a salt
Or should I use bcrypt
Also, if bcrypt is recommended, then how to use it with Code Igniter?
EDIT
I have put these files in application/libraries
PasswordHash.php
c/Makefile
c/crypt_private.c
In my controller, I am using this code -
$params = array(
'phpass_hash_strength' => 8,
'phpass_hash_portable' => FALSE
);
$this->load->library('PasswordHash', $params);
$password = $this->passwordhash->HashPassword($pwd);
I am getting these errors -
A PHP Error was encountered
Severity: Notice
Message: Uninitialized string offset: 3
Filename: libraries/PasswordHash.php
Line Number: 116
A PHP Error was encountered
Severity: Warning
Message: strpos() [function.strpos]: Empty delimiter
Filename: libraries/PasswordHash.php
Line Number: 116
Update
Removed PasswordHash.php, using SimpleLoginSecure now.
Use bcrypt. This discussion came up here in the comments to my answer. You can use a library such as phppass to really simplify the password encryption.
On the matter of salt. Use it! Otherwise somebody can simply go to this site and download the rainbow tables that will cover the large majority of passwords the average users chooses. Especially with all the security leaks in the last few months, now is not the time to be saying you won't use something as simple to implement as random salt.
UPDATE
To use PHPPass with CI, download and extract the files from the phppass website, linked above. Put the PasswordHash.php file into your CI application/libraries directory.
In your code, you then load the library via: $this->load->library('PasswordHash',array(8, FALSE));
Hashing passwords is then as simple as $this->PasswordHash->HashPassword($password);
To later check if a password is correct, it is as simple as:
$password = $_POST['password'];
$actualPassword = /*Get the hashed password from your db*/;
$check = $this->PasswordHash->CheckPassword($password, $actualPassword);
I've taken this demo from http://dev.myunv.com/articles/secure-passwords-with-phpass/ which gives you a lot more informations. I've modified that tutorial slightly to utilize CI's loader which is why you don't need the include or new statements.
why use md5() when it is just as easy to use sha1() ?
Also salting the passwords is always a good idea as it effectively removes the threat of a Rainbow Table attack
In my experience a salted SHA1 hash is pleanty secure for 99% of web application situations.
Code Igniter has changed since the time this question was asked. But for the benefit of some who may not have come across the extensive documentation of CI or haven't seen this before, CI has an encryption class which provides a two-way data encryption using the Mcrypt library of PHP.
After initializing the class using:
$this->load->library('encrypt');
You can encrypt as follows:
$msg = 'My secret message';
$encrypted_string = $this->encrypt->encode($msg);
and decrypt as follows:
$encrypted_string = 'APANtByIGI1BpVXZTJgcsAG8GZl8pdwwa84';
$plaintext_string = $this->encrypt->decode($encrypted_string);
CI also has a non-decodable 1-way hashing:
$hash = $this->encrypt->sha1('Some string');
For more information see:
http://www.codeigniter.com/user_guide/libraries/encryption.html

Resources