Another command to replace exit in php? - php

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
}

Related

wrong webpage rendered on user error

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

Echo (or display errors) after page reload

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

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/

Check result of PHP include

I've got my login and session validity functions all set up and running.
What I would like to do is include this file at the beginning of every page and based on the output of this file it would either present the desired information or, if the user is not logged in simply show the login form (which is an include).
How would I go about doing this? I wouldn't mind using an IF statement to test the output of the include but I've no idea how to go about getting this input.
Currently the login/session functions return true or false based on what happens.
Thanks.
EDIT: This is some of the code used in my login/session check but I would like my main file to basically know if the included file (the code below) has returned true of false.
if ($req_method == "POST"){
$uName = mysql_real_escape_string($_POST['uName']);
$pWD = mysql_real_escape_string($_POST['pWD']);
if (login($uName, $pWD, $db) == true){
echo "true"; //Login Sucessful
return true;
} else {
echo "false";
return false;
}
} else {
if (session_check($db) == true){
return true;
} else {
return false;
}
}
You could mean
if (include 'session_check.php') { echo "yeah it included ok"; }
or
logincheck.php'
if (some condition) $session_check=true;
else $session_check=false;
someotherpage.php
include 'session_check.php';
if ($session_check) { echo "yes it's true"; }
OR you could be expecting logincheck.php to run and echo "true" in which case you're doing it wrong.
EDIT:
Yes it was the latter. You can't return something from an included file, it's procedure not a function. Do this instead and see above
if (session_check($db) == true){
$session_check=true;
} else {
$session_check=false;
}
Actually..
$session_check=session_check($db);
is enough
Depending on where you want to check this, you may need to declare global $session_check; or you could set a constant instead.
you could have an included file which sets a variable:
<?php
$allOk = true;
and check for it in you main file:
<?php
include "included.php";
if ($allOk) {
echo "go on";
} else {
echo "There's an issue";
}
Your question seems to display some confusion about how php includes work, so I'm going to explain them a little and I think that'll solve your problem.
When you include something in PHP, it is exactly like running the code on that page without an include, just like if you copied and pasted. So you can do this:
includeme.php
$hello = 'world';
main.php
include 'includeme.php';
print $hello;
and that will print 'world'.
Unlike other languages, there is also no restriction about where an include file is placed in PHP. So you can do this too:
if ($whatever = true) {
include 'includeme.php';
}
Now both of these are considered 'bad code'. The first because you are using the global scope to pass information around and the second because you are running globally scoped stuff in an include on purpose.
For 'good' code, all included files should be classes and you should create a new instance of that class and do stuff, but that is a different discussion.

Using PHP to request errors information and post if errors has anything

I have an HTML form that takes inputted data and sends it via the mail() function. I also have some validation techniques that validate the inputs, and I created an array variable $errors to log all of the errors; for example,
if the name was left empty, $errors[]="Name empty";
If the email was left empty, $errors[]="email empty";
and so on..
I was able to report the errors using the following technique:
print '<div id="formfeedback"><h3>Error!</h3><p>The following error(s) has occurred:<br />';
foreach ($errors as $msg) { //prints each error
print " - $msg<br />\n";
} // end of foreach
However, what I want is the following. I want the page to be redirected back to the original form that was used to input the information (I know the exact link location, so i can use a header() or even a <meta=http-equiv=refresh> to bring me back to the form page.
Also, on the form, I want to be able to post the errors above the form in some div (call it div=errors)
Would I be able to do the following?
<div id="errors">
<?php
print 'The following error(s) has occurred:<br />';
foreach ($_REQUEST[$errors] as $msg) { //prints each error
print " - $msg<br />\n";
} // end of foreach
?>
</div>
Thanks a lot!
Amit
I agree with #Fosco. I want to explain a little bit more-
There may be two cases-
1. You are doing raw php
2. You are coding on any php framework like CI or your own.
and this will help to identify error field and change style to make better user response. Also last input data remain as it was.
You are doing raw php
In this case you can receive the input data in same file/page.
I will do a common example later.
You are coding on any php framework like CI or your own.
In this case you load a view file to show the form page and you can pass data to view page/file when you load it.
For both of above case you can do some coding like-
/*
your input validation and verification goes here. where $error is generated too
In addition add some error status in above section,
you can do it in your $error array too. Also you store received data into $data here. index of $data should be similar as (corresponding) HTML input name.
You can do it like below
*/
$error_stat = array();
//if the input field name is "email" and email input data raises any error then
$error_stat['email'] = true;
// same for name
$error_stat['name'] = true;
// and so on
// now decide whether you will back to the form page or send the email and do other tasks
if(count($error_stat)<= 0){
// send email
// do aditional tasks
}
else{
// load the form again if its aframework or the form is in seperate file
// off course send $error,$data and $error_stat to the form page/file
}
// now here is a code segment of form page
<?php if(isset($error) && count($error)>0):?>
<div id="error-msg">
<?php
//display errors here
?>
</div>
<?php endif;?>
<form .... >
<input type="text" name="email" class="<?php echo (isset($error_stat['email'])?'error':'else'); ?>" value="<?php echo $data['email'];?>" />\
<!-- and so on ... -->
The simplest way to do this is to:
// Start the session
session_start();
// Store the errors in the session
$_SESSION['errors'] = $errors;
// Redirect to correct page
header('HTTP/1.1 303 See Other');
header('Location: http://original/page');
exit;
Then, on the form page:
// Start the session
session_start();
// extract the errors
$errors = isset($_SESSION['errors']) ? $_SESSION['errors'] : array();
// Display the form with errors
foreach ($errors as $msg) ... ;
Typically I would have the same page process the input and the submission. If the data was valid, the mail would be sent and the page would notify them of that (or redirect them elsewhere)... if the data was not valid, then the form would appear again and the errors could be displayed, without any fancy redirection.
make sure your session is started at the top of your application
include this basic class
class FormErrors
{
var $handler;
function __construct($fname)
{
$this->handler &= isset($_SESSION[$fname]) $_SESSION[$fname] : ($_SESSION[$fname] = array());
}
public function add($name, $value)
{
$this->handler[$name] = $value;
}
public function remove($name)
{
unset($this->handler[$name]);
}
public function getErrors()
{
return $this->handler;
}
}
so when your processing the errors you can go
if(isset($_POST))
{
$FormErrors = new FormErrors("registration");
if(strlen($_POST['username']) == 0)
{
$FormErrors->add('Username','Please enter a valid username');
}
//And for the rest of your checks
}
then within side your html do
foreach($FormErrors ->getErrors() as $name => $error)
{
echo sprintf("<p title=\"%s\">%s</p>",$name,$error);
}
Should work, and if you want to remove all known errors do
$FormErrors = new FormErrors("registration");
unset($FormErrors->handler,$FormErrors);

Categories