My latest idea which didn't seem to work was to store the array in a session,
include_once "scripts.php"
.........
//some code later
$errorlog .= "a random message<br/>";
$_SESSION['errorlog']=$errorlog;
reloadPage();
And then if 'errorlog' wasn't empty then display it,
[code]
<div class="randomclass">
<?php
displayErrors('errorlog');
?>
</div>
//here are the functions
function reloadPage(){
Header('Location: '.$_SERVER['PHP_SELF']);
}
function displayErrors($valuename = "errorlog"){
if(!empty($_SESSION['valuename'])){
echo $_SESSION['$valuename'];
unset($_SESSION['$valuename']);
return true;
}else{
return false;
}
}
[/code]
scripts.php
<?php
if(!isset($_SESSION)) session_start();
........
I have included scripts.php which starts with if(!isset($_SESSION)) session_start();.
I'm new to php, still making my first webpage (or actually, preparing scripts for it). I can't seem to successfully find bugs in my scripts because I don't know how to show the errors after a page reload is needed.
What I want, is a way to store strings like in this $errorlog and display it just like an echo(in div or whatever) after the page was reloaded
I don't get any errors with headers, the page reloads correctly but the problem is that no text is displayed after the page reloads, so I don't see why I shouldn't be using them unless you know another way to reload the page after script is done
surely this way is not the best one, but I think that the problem is very easy..
function displayErrors($valuename = "errorlog"){
if(!empty($_SESSION['valuename'])){ // here you must put a variable $valuename instead a simple string 'valuename'
echo $_SESSION['$valuename'];
unset($_SESSION['$valuename']);
return true;
}else{
return false;
}
}
You must change the session key at this row whit: $_SESSION[$valuename]
if(!empty($_SESSION['valuename'])){
The correct function is the follow:
function displayErrors($valuename = "errorlog"){
if(!empty($_SESSION[$valuename])){
echo $_SESSION[$valuename];
unset($_SESSION[$valuename]);
return true;
}else{
return false;
}
}
Bye!
Marco
Related
I am currently writing a page of a website, and I have a function that renders a new webpage to tell the user that they made an error if the date they have selected is in the past. The function looks like this:
if($interval < 0){
handle_error($dbval_date_error2);
}
If the user did put in a valid date, then the date is stored in a database and a new webpage is displayed which shows the new data entry.
The problem I have is that the handle_error function appears not to work usually. It functions exactly as it should if I also include some kind of print statement:
if($interval < 0){
handle_error($dbval_date_error2);
echo "here";
}
But if I just have the error function on its own, the function call just gets completely ignored and the entry gets stored in the database.
The error function looks like this:
function handle_error($error)
{
$_SESSION['error'] = $error;
header('location:../register/register.php');
}
The problem lies in how you're constructing your header; there needs to be a space between the colon and the path, Location needs to be uppercase, and you need to call exit(); after you set the header.
function handle_error($error)
{
$_SESSION['error'] = $error;
header('Location: ../register/register.php');
exit();
}
Just add an exit() after your header():
function handle_error($error)
{
$_SESSION['error'] = $error;
header('location:../register/register.php');
exit();
}
And it should work
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/
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?
I have this inside a class named site among other harmless stuff:
private
$notice_type = '',
$notice_msg = '';
public function setNotice($type,$msg){
$this->notice_type=$type;
$this->notice_msg=$msg;
}
public function notice($what){
switch($what){
case 'type': return $this->notice_type; break;
case 'msg': return $this->notice_msg; break;
}
}
public function clearNotice(){
$this->notice_type='';
$this->notice_msg='';
}
I've set this class to a session like this:
$_SESSION['site'] = new site();
Here's a scenario of how I use it:
After submitting a form; I set the notification like this : $_SESSION['site']->setNotice('success','success message');, or error if that's the case and redirect the user somewehere using header().
Then I output the message like this on the landing page:
echo $_SESSION['site']->notice('msg');
$_SESSION['site']->clearNotice();.
But; When I use the clearNotice()-function - the contents of both $notice_type and $notice_msg is cleared out before it gets outputted to the browser.
I need for it to stay untill the user navigates away from the page somehow. What am I missing here?
I don't know what happend. But somehow this script started to work as expected.
I've rewritten the code over and over for a while now, and as far as I know it's just about the same as before. But anyway; This is what works now:
site()-class:
This class controlls notifications as well as settings set by the user - like preffered sorting direction of data and selections worth remembering for better user experience and such.
<?php
class site {
private
$notice_type = '',
$notice_msg = '';
public function newNotice($type,$msg){
$this->notice_type=$type;
$this->notice_msg=$msg;
}
public function notice($what){
switch($what){
case 'type': return $this->notice_type; break;
case 'msg': return $this->notice_msg; break;
}
}
public function clearNotice(){
$this->notice_type='';
$this->notice_msg='';
}
}
?>
I have a document where I configurate the entire site by setting a couple of variables to Yes or No - As in this case : $_SITE_CLASS_site.
<?php
# check to see if session is started
if(!isset($_SESSION)){session_start();}
//
// check if site()-class should be activated for this site
if($_SITE_CLASS_site=='Yes'){
# if Yes; prevent resetting the class if it has already been started.
if(!isset($_SESSION['site'])){$_SESSION['site']=new site();}
//
}
//
?>
I've created a template where I have this code before the page content is outputted:
basically it just checks if there is any message to display
<?php if ($_SITE_CLASS_site=='Yes'&&$_SESSION['site']->notice('msg')!=''): ?>
<div id="site-notice-<?=$_SESSION['site']->notice('type')?>" class="grid_12"><p><?=$_SESSION['site']->notice('msg')?></p></div>
<?php endif; ?>
Then I load the page content, and at the end I have this:
the notice should be viewable untill the user closes it, or leaving the page. I don't want, or need, to keep the message
<?php
if ($_SITE_CLASS_site=='Yes'&&$_SESSION['site']->notice('msg')!=''):
$_SESSION['site']->clearNotice();
endif;
?>
Now; Whenever I need to give the user a feedback on their actions - after submitting a form successfully for example - I can just do this at the end of the script:
$_SESSION['site']->newNotice('success','<b>Success!</b> Your request was submitted successfully...');
header('Location '.$_SERVER['HTTP_REFERER']);
exit;
It works like a charm...
is there any any other command we can use as an alternative to exit(); in php.
Because it breaks my html code at the end of the page if the condition is not met and when script has to exit.
Or if anyone has any other idea to resolve this issue???
Thanks
Update:
html code...
<?php
if username is not in correct format
echo "Please check your username";
exit();
if Username and Password didn't match
echo "Wrong Username or Password.";
exit();
if some other condition not met
echo "Condition not met";
exit();
?>
html code continues...
Now the problem is if any of the condition is not met and the script has to exit, the html code below it, which is a whole webpage, does not display...
And please...I am not a computer geek, had a problem so asked it, but why people vote down the question??? don't understand....
You should probably wrap your code into an if statement:
<?php
if($code == 'ok'){
echo 'ok';
} else {
echo 'not ok';
}
?>
your script doesn't have to exit(), you can add statements where you want and how you want.
As the name suggests, the PHP exit() statement will cause your PHP script to exit, right there and then, and not do anything else. If you want it to carry on processing the rest of the code, just don't use exit().
Looking at your code, what you seem to be aiming for is displaying errors to the user, and then (I would guess) re-showing the form they filled in incorrectly.
Rather than just echoing the errors as soon as you discover them, why not store them into a variable, which can then be displayed at an appropriate point in the HTML? Even the most basic of scripts can benefit from a bit of basic code structure.
As an example (and I stress this is not the One True Pattern for this kind of thing), you could arrange your file something like this:
if ( /* form has been submitted */ )
{
$errors = validate_form();
if ( count($errors) > 0 )
{
display_form($errors);
}
else
{
display_success_message();
}
}
else
{
display_form();
}
function validate_form()
{
$errors = array();
// Series of if conditions, each adding a message to $errors if appropriate
return $errors;
}
function display_form($errors=array())
{
// HTML <ul> list displaying the contents of $errors, if any
// HTML for form
}
function display_success_message()
{
// HTML thanking user for a successful form submission
}