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.
Related
I have some php codes, and there is a condition which declare type of ajax. Now I want to know, should I write all php codes for each request separately? In other word, should I write all php codes twice (almost repeatedly) for both methods?
if(!empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) === "xmlhttprequest")
{
// I'm ajax
$arr = array('key1'=>'value1', 'key2'=>'value2');
echo json_encode($arr);
} else {
// I'm not ajax
$arr = array('key1'=>'value1', 'key2'=>'value2');
$_SESSION["arr"] = arr;
header('Location: '.$_SERVER['HTTP_REFERER']); // redirect to previous page
}
So, as you see, I have to write all PHP code twice. One time for regular request and one time for ajax request. In reality there is a lot of codes, Maybe 1000 lines of code that I have two write them again for ajax requests (while they are almost identical). Is this a normal way?
Also I want to know, is there any succinct approach? Actually I like to use a approach which needs to php code just one time for both requests ...!
I would create a class to handle those request and put common code right into a method used by both contexts:
// file: class.handler.php
class contextHandler() {
public function handleHttp() {
$this->handleGeneral();
// What ever has to be done in this context
$_SESSION["arr"] = arr;
header('Location: '.$_SERVER['HTTP_REFERER']);
}
public function handleAjax() {
$this->handleGeneral();
// What ever has to be done in this context
echo json_encode($arr);
}
private function handleGeneral() {
// put common code here
$arr = array('key1'=>'value1', 'key2'=>'value2');
}
}
In your code you could then use that class:
include 'class.handler.php';
$handler = new contextHandler();
if(
!empty($_SERVER["HTTP_X_REQUESTED_WITH"]) &&
strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) === "xmlhttprequest"
)
{
$handler->handleAjax();
} else {
$handler->handleHttp();
}
This has of course to be adjusted to your concrete needs but offers a nice and clean way of reusing code and generating small and readable code.
So, now, I can't seem to get this to work. What I'm trying to accomplish is to get the success message to show up, but it just doesn't work for some odd reason.
I'm using the php-login project (minimal) available here: http://www.php-login.net/
This is the basic PHP part.
<?php
//die(print_r(get_defined_vars(), true));
include("includes/database.incl.php");
require_once("includes/Login.php");
$login = new Login();
if (isset($login)) {
if ($login->errors) {
if ($login->messages) {
foreach ($login->messages as $message) {
die("success");
}
}
foreach ($login->errors as $error) {
echo $error;
}
}
} else {
echo "nope";
}
$login = null;
?>
Right now, I'm using a program to send login details (log_name, log_password) using a POST request. It works and echos the errors if I deliberately put in wrong details, but once I type the details, it returns nothing. Even if I type incorrect details after, it still presents me with nothing.
Thanks in advance.
It turns out that it was a web server problem.
I was originally using XAMPP, and now that I switched to WAMP, it works.
Thanks for the help, everyone.
I'm sorry to trouble you, I have tried my best to solve this but I am not sure where I am going wrong and I was wondering if someone out there would be willing to help!
Basically, I am having some issues with $_SESSION variables; I would like for each occasion that a visitor came to the page that they would be shown a different content message.. The below code, when first landing on a page will seem to skip the first "content1", and will display "content2" instead, then "content3" after another revisit. I've put in an unset call, which eventually sends it there, am I not using _SESSIONS correctly?
I'm not sure how the session variable was assigned to 1, for it to land correctly in the if===1 statement without it first returning the original "content1"
if (empty($_SESSION)) {
session_start();
}
if (!isset($_SESSION['content'])) {
$content = "content1";
$_SESSION['content'] = 1;
return $content;
}
elseif ($_SESSION['content'] === 1) {
$content = "content2";
$_SESSION['content'] = 2;
return $content;
}
elseif($_SESSION['content'] === 2) {
$content = "content3";
unset($_SESSION['content']);
return $content;
}
Apologies for babbling or whether this was a simple fix / misunderstanding on my part. It's caused quite a headache!
Many thanks.
-edit-
This is a function that is called from within the same class, it has not gone through a loop anywhere either..
You are only calling session_start(); if the session has not been created.
What about the other times, when it's 1, or 2?
Call session_start(); regardless of your if (empty($_SESSION)) { statement
You should always use the session_start() function. If a session exists, it will continue it, otherwise it will create a new session.
Your code can then be simplified to the following:
// Start/Resume session
session_start();
// Get content
function display_message()
{
if ( ! isset($_SESSION['content']))
{
$_SESSION['content'] = 1;
}
if ($_SESSION['content'] == 1)
{
++$_SESSION['content']; // Increment session value
return 'Content #1';
}
elseif ($_SESSION['content'] == 2)
{
++$_SESSION['content']; // Increment session value
return 'Content #2';
}
elseif ($_SESSION['content'] == 3)
{
unset($_SESSION['content']); // Remove session value
return 'Content #3';
}
}
// Display content
echo display_message();
However, if someone visits your page a fourth time, they will be shown the first message again (because the session value is no longer tracking what they've been shown).
Perhaps this sort of functionality might be handled better with by using a cookie to track this information?
How would I create a cookie that would store the randomly added body class for one browser session or for one day. My intention would be to randomly give every user a body background image and then store that image so that it won't change every pagereload or when they go to page 2.
Site http://www.midnightlisteners.com/
i am using this jQuery plugIn: https://github.com/carhartl/jquery-cookie
but it does not work somehow
My jQuery code:
the code that I use:
if($.cookie('userBackground') === null) {
var classes = ['body-bg1','body-bg2', 'body-bg3', 'body-bg4'];
var randomnumber = Math.floor(Math.random()*classes.length);
var chosenClass = classes[randomnumber];
$('body').addClass(chosenClass );
$.cookie('userBackground', chosenClass, { expires: 7, path: '/' });
} else {
//todo verify cookie value is valid
$('body').addClass($.cookie('userBackground'));
}
Errors i am getting:
Uncaught ReferenceError: require is not defined
Uncaught TypeError: Object function (a,b){return new e.fn.init(a,b,h)} has no method 'cookie'
Are there other ways to do this? php? pure javascript?
UPDATE:
If you want to make it only last the length of the session then just use the session instead:
<?php
if(!isset($_SESSION['bgclass'])) {
// lets make our cookie!
$classes = array('body-bg1','body-bg2', 'body-bg3', 'body-bg4');
$classIndex = array_rand($classes);
$_SESSION['bgclass'] = $classes[$classIndex];
}
$bgclass = $_SESSION['bgclass'];
?>
This way after the session times out or the browser is closed the user will get a new bgclass value.
If you already have php running i would do it that way. Much better to handle this server side if you can. Its also a bit simpler:
<?php
if(!isset($_COOKIE['bgclass'])) {
// lets make our cookie!
$classes = array('body-bg1','body-bg2', 'body-bg3', 'body-bg4');
$expire = time()+(60*60*24); // expire 1 day form now
$classIndex = array_rand($classes);
$bgclass = $classes[$classIndex]; // had $class here as opposed to $classes
setcookie('bgclass', $bgclass, $expire);
} else {
$bgclass = $_COOKIE['bgclass'];
}
?>
<html>
<head></head>
<body class="<?php echo $bgclass ?>">
...
</body>
</html>
The key thing to remeber is that a cookie is essentially a response header so you have to do this before headers have been sent (ie. anything from php is output to the browser).
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>