Session_start causes 500 ERROR - php

I have been working on website (Yii + angularJs) and everything was okey.
Then I decided to work at home and cloned repository to my laptop.
And then a problem appeared.
Website doesn't give any resources or files to display, just white screen and error 500 (Internal Server Error) appears with no reasons or explanations.
And only when I comment some lines in Main Controller everything goes okey.
I comment session_start() function and checks of users rigths from $_Session array.
Example below.
(Note, if I leave session_start() line, site loads index page with login form, then I fill fields and then white screen again)
public function actionIndex() {
$page = safe($_GET,'page','index');
$pages = $this->get_pages();
$pageInfo = safe($pages,$page);
//session_start();
if(safe($pageInfo,'layout')) {
$this->layout = $pageInfo['layout'];
}
if($page == 'reset-password') {
$params = array_change_key_case($_GET, CASE_UPPER);
if(!isset($params['RECOVERY_TOKEN']))
$this->redirect('/');
} else if($page == 'request') {
$id = safe($_GET, 'id');
if(!$id || !$this->validID($page, $id)) {
$this->redirect('/requests');
}
}
$this->render(safe($pageInfo,'render',$page)); //moved from comments below
/*if($_SESSION['rights'][$page] && !$_SESSION['rights'][$page]['show']){
$this->redirect('/dashboard');
}else {
try {
if (!safe($pageInfo,'layout') && empty($_SESSION) && $pages[$page]) {
$this->redirect('/');
}else{
$this->render(safe($pageInfo,'render',$page));
}
} catch (Exception $e) {
throw new CHttpException(404);
}
}*/
}
Strange is that after login to website I also have session_start() function, but this one doesn't cause such error.
And also, i have no problems with my code on my work computer and on dev-server.
We have tried to clone this site to another laptop, the same error appeared.
I have no ideas what is wrong. Please, help. Thanks!

Related

Apache + Chrome + PHP => Infinite Loading

I'm running on a custom local domain a login form. I have a simple router which redirects to the Controller, and the login method of the controller is the following:
public static function login()
{
if ($_SERVER['REQUEST_METHOD'] == "POST") {
echo "What the f***!";
} else {
self::renderLoginForm();
}
}
Here is the code of the router:
$requested_path = explode('?', $_SERVER['REQUEST_URI'], 2)[0];
try {
if (preg_match('/[^.]+.css/', $requested_path)) {
$file_path = __DIR__ . "/Public" . $requested_path;
if (file_exists($file_path)) {
header('Content-Type: text/css');
echo file_get_contents($file_path);
}
} elseif (preg_match('/[^.]+.js/', $requested_path)) {
$file_path = __DIR__ . "/Public" . $requested_path;
if (file_exists($file_path)) {
header('Content-Type: text/js');
echo file_get_contents($file_path);
}
} elseif ($requested_path === "/") {
PageController::homeAction();
} elseif ($requested_path == "/api/recognize") {
SoundController::recognizeAction();
} elseif ($requested_path == "/login") {
UserController::login();
} else {
PageController::notFoundAction();
}
} catch (Throwable $throwable) {
if (ISDEV) {
echo $throwable->getMessage();
echo $throwable->getTraceAsString();
} else {
echo "Erreur 500";
}
}
Using GET method, the form is well rendered, I can refresh, do anything, everything works. But when I'm validating my form, Chrome starts in an infinite loading (Not displaying my echo).
I tried the following:
Safari or Postman => POST works like a charm
Chrome + XDebug => POST works like a charm
Clear all data, then Chrome => POST does not work
Private Navigation Window => POST does not work
Restart server then Chrome => POST does not work
Restart MBPro then Chrome => POST does not work
I double checked that it's same URL, and same ports everytime.
I had this problem prior to XDebug installation. Actually this problem is the reason why I installed XDebug
If you have any idea where it could come from, that would be very very helpful, because I'm running out of things to try.
EDIT with CAUSE
I finally found why, even if I don't know how to solve it. When I don't set any password, the POST is sent well, without any problem, the problem occurs only when I set a password.
After uninstalling and installing Chrome, it finally worked with password set, but taking a lot of time loading, before showing me the Save password popup.
After finding this cause, I switch off my internet connection, and then it worked like a charm.
Then question
Does anyone know how to disable the automatic save password popup for some domains only?

Store value of session key then unset?

I'm trying to imitate the behavior of flash messages in native PHP, for one-time display of error messages.
Displaying the Login page:
public function showLoginAndRegistrationPage()
{
$session = new Session();
$data['errors']['login']['account'] = $session->getFormErrorFlashData('login', 'account');
$this->viewPresenter->display('basic', 'customer/login-registration', $data, 'Login/Register');
}
Verifying the login details:
public function processLogin()
{
// Some code
$session = new Session();
if($this->formInputFilter->isValid()) {
// Some code
if(true) {
// Some code
} else {
$errors = array(
'account' => 'Account does not exist.'
);
$session->setFormErrorFlashData('login', $errors);
header('Location: /login');
}
} else {
header('Location: /login');
}
}
For setting the error messages:
public function setFormErrorFlashData($form, $errors = array())
{
foreach($errors As $field => $message) {
$_SESSION['errors']["{$form}"]["{$field}"] = $message;
}
}
For getting the error messages stored in the session:
public function getFormErrorFlashData($form, $field)
{
if(isset($_SESSION['errors']["{$form}"]["{$field}"])) {
$message = $_SESSION['errors']["{$form}"]["{$field}"];
unset($_SESSION['errors']["{$form}"]["{$field}"]);
return $message;
}
}
Basically for an invalid attempt, after redirect, it should now display the 'Account does not exist' message, and then when the user refreshes the page, it should no longer be there.
What happens is when I comment out the unset() line in getFormErrorFlashData(), the $_SESSION contains the errors, but of course as expected they do persist even after countless page refreshes.
But when it's not commented out, I get a NULL. It seems that $message is also unset, even after attempting to store in it the value of that session key.
I have a bootstrap file that has the session_start() line, it's loaded for every page so I doubt that's the cause?
UPDATE:
index.php (bootstrap file)
<?php
session_start();
date_default_timezone_set('Asia/Taipei');
require_once 'core/Autoloader.php';
use core\Autoloader As Autoloader;
use core\Router As Router;
use core\Dispatcher As Dispatcher;
spl_autoload_register('core\Autoloader::loadClass');
$request_uri = trim($_SERVER['REQUEST_URI']);
$router = new Router();
$route = $router->handleRequest($request_uri);
if (!$route) {
require_once ('./views/errors/404.php');
} else {
$dispatcher = new Dispatcher($route);
$isDispatched = $dispatcher->dispatch();
if (!$isDispatched) {
echo '<div>' .$route['class'] .'/' . $route['action'] . ' not found </div>';
require_once ('./views/errors/404.php');
}
}
I've found the culprit.
When I traced the request logs, showLoginAndRegistrationPage() was being called twice because I didn't realize I also had a .js file attached in the html file with a submit event handler that gets fired too, thus the double page requests.
I removed the file and now it's working.
Thanks for the help!

My php cookie session code displays a blank white page no matter what?

So on one page my users check a box and type agree in an input field to proceed to the next page, I am trying to use session cookies to stop people bypassing this by typing the URL however when you proceed to the next page it just displays blank? i have tried tests such as using Echo to display text at the beginning of the script and have enabled error reporting but the page still just displays white? any ideas why?
Check Box and Input Page php:
<?php
if(isset($_POST["terms"])&&isset($_POST["agree"])) {
$agree = $_POST["agree"];
$validated = false;
if($agree=="agree") $validated = true;
if($validated) {
setcookie("agree",($agree));
header("Location: nextpgae");
} else {
header("Location: homepage");
}
}
?>
Page it leads to that is displaying blank's php:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$validated = false;
if(isset($_COOKIE["agree"])){
$agree = $_COOKIE["agree"];
if(&$agree==("agree")) $validated = true;
}
if($validated) {
} else {
header("Location: homepage");
?>
A blank page is usually symptomatic of a server error. Frequently, it indicates a syntax error in your PHP code. Your server error log will tell you exactly what is going on, but in this case you have missed a closing } after this line
header("Location: homepage");
You should implement tokens for this kind of procedure. This may help you: http://forum.codecall.net/topic/58268-form-tokens-with-php/

Use index.php for login and main content

Currently I have a very basic PHP login system. My index.php file simply checks if a session is set, if it isn't it redirects them to login.php. I see a lot of websites where the same effect is achieved but through the index of the site entirely.
For example, at http://twitter.com if I am not logged in I will land at simply twitter.com. If I am logged in I will also land at twitter.com just with different content. How can I achieve the same effect on my site?
I'm sure this is very basic but it's something I am yet to explore.
Thanks
A simple example how you can handle your welcome/user index.php site:
index.php
require_once('configFile.php'); // session_start();.. and other stuff
if ($logged) {
require_once('userLogedIn/index.php');
} else {
require_once('welcome/index.php');
}
Lots of ways to do this but the below is a primitive example. Assuming your pseudo logic is something like...
if (!$logged_in) {
redirect('login.php');
}
else {
// show page content
}
You can do...
if (!$logged_in) {
include('login.php');
}
else {
include('page-content.php');
}
The includes aren't necessarily required but help to keep it tidy.
First of all answer yourself the question if your index file can contain user supplied stuff. If so DON'T DO IT! The problem are possible attack vectors from that user supplied stuff against your login.
That said let me help you:
<?php
$session_id = session_id();
if (!empty($_COOKIE[$session_id]) && session_start() !== false && isset($_SESSION["user_id"])) {
echo "index page";
}
elseif (isset($_POST["login"])) {
// validate login ...
if ($valid_login === true) {
if (session_status() === PHP_SESSION_ACTIVE) {
session_regenerate_id();
}
else {
session_start();
}
$_SESSION["user_id"] = $user_id;
}
}
else {
echo "login page";
}
?>
I think you get the idea here. We now have a single file taking care of everything.

URL redirection wont work always?

Im Workin on a Webapplication in PHP with CodeIgniter, and im stuck :P
Its very difficult to explain, so i show it with an example.
I have normal CodeIgniter Controller. In this Controller i have a function like this:
<?php
public function groups($subdomain ='') {
$this->load->library('MyLogin');
$user_id = $this->mylogin->logged_in();
if ($subdomain == '') {
.....
} elseif ($subdomain == 'create') {
.....
} elseif ($subdomain == 'join') {
.....
} elseif ($subdomain == 'leave') {
.....
} elseif ($subdomain == 'assign') {
.....
} else {
.....
}
}
The logged_in Function checks if the user who's loading this page (sub pages) is logged in. If not he gets automatically redirected in the logged_in function like this:
echo header("Location: /user/login");
5 Minutes ago this worked well. Now i created a new subdomain 'assign'.
Now if im not logged in and try to Connect to one of the following URLS i always get redirected
localhost/user/groups
localhost/user/groups/2
localhost/user/groups/create
localhost/user/groups/join
localhost/user/groups/leave
But if im connecting to
localhost/user/groups/assign
he tries to load this page (what does not work because the $user_id is empty).
Why the ... does this happen?
Regards Teifun2
I recommend you modify the logged_in() function from this:
echo header("Location: /user/login");
To this:
header("Location: /user/login");
exit;
I think that will solve the problem. The echo has nothing to do with it, it's just superfluous.
use $_session while logging user in...! so he will reamain logged in even after refresh and page change..! And empty values wont pass.

Categories