Apache + Chrome + PHP => Infinite Loading - php

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?

Related

php function verify token works in localhost but not on GoDaddy server

I have php function that is supposed to verify if there is a token, and if so, display some information. The function works fine when I use xampp in localhost. When I do it in prod on the server, it gives me a 'token undefined' error, even though I can see the token in dev tools. What could possibly be causing the error?
my php function
public function viewCompanies()
{
if (isset($GLOBALS['headers']['Authorization'])) {
print_r($GLOBALS['headers']['Authorization']);
if ($id = $this->VerifyUserToken($GLOBALS['headers']['Authorization'], $_SERVER['REMOTE_ADDR'])) {
$companies = $this->currentModel->viewCompanies();
if ($companies) {
echo json_encode($companies);
} else {
echo json_encode(['success' => false]);
}
}
else {
echo json_encode(['success' => false, 'error' => "invalid token"]);
}
} else {
echo json_encode(['success' => false, 'error' => "token undefined"]);
}
}
the verifyUserToken function
public function verifyUserToken($token, $ip) {
$db = new Database();
$db->query('SELECT * FROM auth WHERE token = :token AND expiry >now()');
$db->bind(':token', $token);
//check database if token exists and is not expired
if($res = $db->single()) {
// checks if token matches to ip address
// returns user or contact id if verified else returns false
if($res->token === $token && $res->ip === $ip) {
$this->cleanTokens();
if($res->user_id >0) {
return $res->user_id;
}
//
} else {
return false;
}
} else {
return false;
}
}
I checked the database, and the token is clearly there
I tested the function on Postman and I get the same token undefined error. Please let me know if there's any other info I should add. I've no idea how to debug this.
in the end. it was goDaddy that saved the day. They sent me the following message, after I opened a ticket and spoke with them:
In regards to the issue you are seeing with custom HTTP headers being stripped out of requests on your site, the issue you are running into is actually due to the CGI handler Apache is configured to use by default on cPanel. The CGI handler, for security reasons, strips out custom header entries that are not explicitly registered within Apache's configuration. We can further verify this by changing the PHP handler the site uses from CGI to PHP-FPM.
If you...please do not hesitate to contact our support teams over the phone or through live chat.
Sincerely,
all's well that ends well.

Flash Messages don't disappear PHP

I'm using this Flash Messages Script for a simple redirect and flash message system.
Everything works fine on my apache localhost, but as soon as I upload it to a server (also apache) it doesn't work. It sets the sessions and also displays the messages correctly, but it doesn't unset the messages afterwards. Now I have a whole bunch of "Flash messages" on my website and they'll get more and more unless you close your browser to unset all sessions forcefully.
I've already read the documentation like a thousand times and also searched in the Flash Messages script on the server for any errors. I couldn't find any.
Maybe you guys can help me. The host where I'll deploy my website is strato.com.
Edit: I found a cookie called PHPSESSID in my browser informations. Maybe this could be helpfull.
Constructor:
public function __construct()
{
// Generate a unique ID for this user and session
$this->msgId = sha1(uniqid());
// Create session array to hold our messages if it doesn't already exist
if (!array_key_exists('flash_messages', $_SESSION)) $_SESSION['flash_messages'] = [];
}
Clear session function:
protected function clear($types=[])
{
if ((is_array($types) && empty($types)) || is_null($types) || !$types) {
unset($_SESSION['flash_messages']);
} elseif (!is_array($types)) {
$types = [$types];
}
foreach ($types as $type) {
unset($_SESSION['flash_messages'][$type]);
}
return $this;
}
Add Sessions:
public function add($message, $type=self::defaultType, $redirectUrl=null, $sticky=false)
{
// Make sure a message and valid type was passed
if (!isset($message[0])) return false;
if (strlen(trim($type)) > 1) $type = strtolower($type[0]);
if (!array_key_exists($type, $this->msgTypes)) $type = $this->defaultType;
// Add the message to the session data
if (!array_key_exists( $type, $_SESSION['flash_messages'] )) $_SESSION['flash_messages'][$type] = array();
$_SESSION['flash_messages'][$type][] = ['sticky' => $sticky, 'message' => $message];
// Handle the redirect if needed
if (!is_null($redirectUrl)) $this->redirectUrl = $redirectUrl;
$this->doRedirect();
return $this;
}
I fixed it. It was due an change in PHP 7.1 in the php.ini file. As soon as I downgraded my PHP version to PHP 7.0 everything worked fine again.
I hope this will help a lot of people. At least you've got some starting point now.

Session_start causes 500 ERROR

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!

Cloud hosting causing issues with JSON retrieval?

I'm hosted with Smarthosting, they used cloud based hosting which delivers faster loading times - great!
But I have a snag.
I'm setting some sessions via PHP in a seperate file...
<?php
session_start();
if(filter_var($_POST['question_1'], FILTER_VALIDATE_INT)) {
$_SESSION['question_1'] = addslashes($_POST['question_1']);
}
if(filter_var($_POST['question_2a'], FILTER_VALIDATE_INT)) {
$_SESSION['question_2a'] = addslashes($_POST['question_2a']);
}
if(filter_var($_POST['question_2b'], FILTER_VALIDATE_INT)) {
$_SESSION['question_2b'] = addslashes($_POST['question_2b']);
}
if(filter_var($_POST['question_2c'], FILTER_VALIDATE_INT)) {
$_SESSION['question_2c'] = addslashes($_POST['question_2c']);
}
if(filter_var($_POST['question_2d'], FILTER_VALIDATE_INT)) {
$_SESSION['question_2d'] = addslashes($_POST['question_2d']);
}
if(filter_var($_POST['question_2e'], FILTER_VALIDATE_INT)) {
$_SESSION['question_2e'] = addslashes($_POST['question_2e']);
}
if(filter_var($_POST['question_2f'], FILTER_VALIDATE_INT)) {
$_SESSION['question_2f'] = addslashes($_POST['question_2f']);
}
if(filter_var($_POST['question_2g'], FILTER_VALIDATE_INT)) {
$_SESSION['question_2g'] = addslashes($_POST['question_2g']);
}
?>
Then later on I access another PHP file which puts these into a JSON string...
<?php
session_start();
echo json_encode($_SESSION);
?>
This works fine, however, until I call the JSON via Ajax...
$.getJSON( "retrieve-variables.php", function( data ) {
var items = [];
...etc....
});
It's not pulling the most recent session data, it seems to pull back the session data from previous attempts. Is this to do with the cloud hosting? Or some other issue? Is there a way I can disable caching for this particular file and/or entire directory?
Thanks for listening.
EDIT: If I access the PHP retrieval file directly, then hard refresh it (CTRL+F5), and then go through the form again, it will ignore the answers I've selected and enter the data for that hard refresh I did
I found out how to fix this, in case anyone stumbles upon this post.
I simple added cache:"false" to the ajax get request.

PHP redirection issue

I have a program that prints reports for a user id list. The program is supposed to print reports one by one for users on the list uploaded. The problem is that when I was running the printing process and getting to print the report with indexInList=30, I got error:
This webpage has a redirect loop
The webpage at http://127.0.0.1/content/8520?print=1&bulkprinting=1&filename=/private/var/tmp/phpHRXEw8.moved&indexInList=30&nopeergroup=1&nolabpage=0&hideScreeningOnly=1&showOnlyScreening=0&hideHoldMailing=1 has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer.
I tried to clean the cookie but still keep getting the same error.
I attached some code here and hope anyone can help me:
$sessionData['first_name'] = $foundUser->first_name;
$sessionData['last_name'] = $foundUser->last_name;
// Overwrite $_REQUEST variable with parameters before including
// the hpa report
$_REQUEST = array(
'user_id' => $foundUser->id,
'bulkprinting' => true
);
if($nopeergroup) { $_REQUEST['nopeergroup'] = $nopeergroup; }
if($nolabpage) { $_REQUEST['nolabpage'] = $nolabpage; }
if($hideScreeningOnly) { $_REQUEST['hideScreeningOnly'] = $hideScreeningOnly; }
if($showOnlyScreening) { $_REQUEST['showOnlyScreening'] = $showOnlyScreening; }
if($hideHoldMailing) { $_REQUEST['hideHoldMailing'] = $hideHoldMailing; }
$includeValue = include __DIR__.'/../hpa/hpa.php';
$url = sprintf(
"/content/8520?print=1&bulkprinting=1&filename=%s&indexInList=%s" .
"&nopeergroup=%s&nolabpage=%s&hideScreeningOnly=%s" .
"&showOnlyScreening=%s&hideHoldMailing=%s",
$filename, $indexInList, (int)$nopeergroup, (int)$nolabpage,
(int)$hideScreeningOnly, (int)$showOnlyScreening, (int)$hideHoldMailing);
if($hradata[0] !== false) {
$sessionData['hra_id'] = $hradata[0]['id'];
}
if($screeningdata[0] !== false) {
$sessionData['screening_id'] = $screeningdata[0]['id'];
}
if($includeValue !== 1) {
// Redirect to URL
$sessionData['message'] = $messages_set[$includeValue];
$_SESSION['printing_set'][] = $sessionData;
redirect($url);
}
$sessionData['markAsMailed'] = true;
$_SESSION['printing_set'][] = $sessionData;
?>
<script type="text/javascript">
function waitPrint() {
window.print();
var t = setTimeout("timed()", 1000);
}
function timed() {
window.location.replace("<?php echo $url ?>");
}
if(window.attachEvent) {
window.attachEvent("onload", waitPrint);
} else if(window.addEventListener) {
window.addEventListener("load", waitPrint, false);
}
</script>
Sounds like you have a lot of files that need printing!
You may be able to alter your browser settings (I seem to remember you can in Firefox) to allow more than 30 loops.
Alternatively, you could always limit your code to 30 loops then wait for further user interaction to proceed to the next 30.
The 3rd option is to always create a Word document or PDF with one report on each page, then save the file and print it - a little more hassle (in a way) but at least you'll be able to print everything at once.
In order for $includeValue to be set to anything, the file __DIR__.'/../hpa/hpa.php' must have a return statement inside of it, as demonstrated in the PHP documentation for include, example 5. include will only return a value when called if the included file returns a value.
If your script still produces an infinite loop, your logic within the included file is incorrect and it is consistently producing a value that is not 1.
Essentially, here is the code that your question boils down to:
$includeValue = include __DIR__.'/../hpa/hpa.php';
if($includeValue !== 1) {
// Redirect
}
Browsers have checks built-in to help you when sites are misconfigured into a redirection loop, and 30 must be the limit for the browser you're using. You've built a redirection loop on purpose, but the browser doesn't know that. Instead of using the window.location.replace() method, how about a form that automatically submits? That should look different to the browser, and allow your loop to progress as designed.
<script type="text/javascript">
function waitPrint() {
window.print();
var t = setTimeout("timed()", 1000);
}
function timed() {
window.reloadForm.submit();
}
if(window.attachEvent) {
window.attachEvent("onload", waitPrint);
} else if(window.addEventListener) {
window.addEventListener("load", waitPrint, false);
}
</script>
<form name="reloadForm" action="<?php echo $url ?>">
</form>

Categories