Show message from php

Whats a good way to show errors/messages to users in php?

I have been using my own method for years, but I figured maybe its not the best way to go about it. Essentially when I want to throw an error to a user, or display confirmation of a successful action, I do the following:

function show_message() < global $_SESSION; if (isset($_SESSION["message"])) < echo "
" . $_SESSION["message"] . "
"; unset($_SESSION["message"]); unset($_SESSION["message_type"]); > >

and I put show_message(); on top of every page to display possible errors that might be throw to this page. What are the possible problems with this?

I was under the impression php handled that by passing SID thru the URL. EDIT: My impression was false, it didnt work. 😮

Only thing I would add would be to turn these functions into methods of a dedicated class. Messaging used this way is often called flash messaging in various frameworks. So this could be the base of your FlashMessage class.

2 Answers 2

I see nothing wrong with this approach. You’ll find this technique under different names in quite a number of frameworks, for instance FlashMessenger in Zend Framework. Usually the Session is wrapped in an object instead of the regular Session array and with a ViewHelper instead of a function.

To make sure you don’t have any typos in the Session keys when assigning the message, you could wrap the assigning code into a function as well, e.g.

function set_message($text, $type) < $_SESSION['message'] = array( 'text' =>$text, 'type' => $type ); > 

You could improve it by having the function return the string instead of echo ing it and personally I’d use sprintf to format the output. Makes the code somewhat more readable imho, e.g.

return sprintf('
%s
', $_SESSION["message"]["text"], $_SESSION["message"]["type"]);

Like @Gumbo pointed out, the function might not work when Sessions do not work, but that will likely impose a number of other problems for the entire application then, so I wouldn’t exactly bother about this particular piece of code then.

Читайте также:  Поиск по таблице html css

Minor thing: $_SESSION is a superglobal, so you do not have to use the global keyword.

Источник

How do I return a message after submitting a form on my page with PHP?

I just followed this tutorial on how to create a contact form with PHP. Now everything works fine but when I submit a form it returns a message on a new blank page. I want this to happen on the current page underneath the contact form. This is my first time ever doing anything with PHP so I have no idea how I would do this. In the tutorial it is briefly mentioned that you can just put the script anywhere you would want the message to appear but it doesn’t seem to work for me. This is my HTML code:

     
Your message has been sent!

'; > else < echo '

Something went wrong, go back and try again!

'; > > else if ($_POST['submit'] && $human != '4') < echo '

You answered the anti-spam question incorrectly!

'; > > else < echo '

You need to fill in all fields!!

'; > > ?>

I’ve already found some answers but none of which make any sense to me. I also tried inspecting the example on the tutorial’s site but, ofcourse I can’t access the PHP. Can anybody explain this to me?

presumably this code above is some OTHER .php file than the one that contained the actual form? If that’s the case, you’d need to combine the two so that the form gets re-displayed after you send your email, or you use this code to redirect BACK to the original page.

Well I have 1 separate php file containing my code and a HTML file. The tutorial file mentioned in the beginning that I should create a PHP file and put everything in there. But that didn’t work at all so I tried it this way, and that did work.

You can use wamp or xampp to run php scripts on your local machine. actually like your own web server 🙂

3 Answers 3

If you want the message on the same page then you have to put the php code on the same page like this:

     Your message has been sent!

'; > else < echo '

Something went wrong, go back and try again!

'; > > else if ($_POST['submit'] && $human != '4') < echo '

You answered the anti-spam question incorrectly!

'; > > else < echo '

You need to fill in all fields!!

'; > > > ?>

I wonder why this received a -1 since this is how it works in most cases. Anything else requires more complicated techniques such as AJAX, cookies or sessions (based on cookies). Only downside is that reloading the page after submitting will submit the form again (most browsers will show a related dialog).

true but other solutions are bit complicated as you sad and he is just learining php so for now i think this is enough

When user loads this page for the first time, there is not set $_POST array. So PHP will throw errors. those $_POST variables must be under if($_POST[‘submit’])<. code block. I think it may be reason to down voted, but i didn't downvoted this and i have no reputation to :)

Okay so what I didn’t know was that I have to put everything in a PHP file, my HTML as well. That finally did the trick! I would like to make use of the solution people suggested with AJAX but for now this will do.

From what you appear to be asking you need to look into AJAX. You’ll need to use a JavaScript library such as jQuery to make it easier. It will do exactly what you’re looking for. Post the form data to your «contact.php» and the returned message (success/error) straight back to the page you are currently on. No redirect, no refresh.

There are different ways to go about this. AJAX is one of them, but since you are just starting out my opinion is to avoid that — learn the basics first. The code below is just that — the basics.

This method entails having the form and the processing on the same page. This is generally not the best method, but it is probably the simplest — and again, my opinion is that when you are starting out, simplicity is your friend.

Your message has been sent!

'; > else < echo '

Something went wrong, go back and try again!

'; > > else < echo '

You answered the anti-spam question incorrectly!

'; > > else < echo '

You need to fill in all fields!!

'; > > ?>

Keep in mind that, while this method works, in the long run it is not the best approach. It is better to keep logic and markup separate. That would mean having at least two pages — one that displays the form, and another page that processes the form. Even better approaches will involve object oriented programming. However, I am a firm believer in the ready, fire, aim methodology. when you are trying to learn, get it to work first, worry about best practices and optimization later. As you run into bigger problems and the need for more complexity arises, you can make adjustments and figure out better ways to do things. Progress only comes from practice, trial, and error. Good luck.

Источник

Display message before redirect to other page

I have a simple question but yet i don’t know. I would like to display message first before redirect to other page, but my code just directly redirect the page without display the message, or the display time is too short am not sure.. my code as below.. pls advise. thank much.

echo "Please Log In First"; header("location: login6.php"); 

«. but my code just directly redirect the page without display the message,» Impossible. You can’t use echo before header, you will get an error message Headers already sent

7 Answers 7

You can’t do it that way. PHP header must sent out before any content, so the correct order is:

header("location: login6.php"); echo "Please Log In First"; 

But these codes will redirect instantly and wouldn’t let you see the content. So I would do the redirection by JavaScript:

echo "Please Log In First"; echo ""; 

You can use header refresh. It will wait for specified time before redirecting. You can display your message then.

header( "refresh:5; url=login.php" ); //wait for 5 seconds before redirecting 

stackoverflow.com/questions/283752/refresh-http-header says that as well as not being standard the refresh header also causes performance issues in Internet Explorer.

HTTP refresh redirect to wait 5 seconds:

header('Refresh:5; url=login6.php'); echo 'Please Log In First'; 

sir.. i don’t quite understand the logic.. why redirect the page first before display the message ?? I am applying this. and it works.. thanks so much..

A redirect is a redirect 😉

If you tell a browser by using a Location: header to redirect to another page, the browser does just this: It redirects to the other page. And the browser does this immediately — without any delay.

Therefore, your echo won’t display at all.

Set headers first

Furthermore, you need to set headers before each other output operation (as pointed out by Fred -ii-):

// First, echo headers header("location: login6.php"); // Then send any other HTML-output echo "Please Log In First"; 

Better not use auto-redirects

Quite likely, you won’t show a message and then — after a certain amount of time — automatically redirect to another page. People might get confused by this process. Better do this:

Show the login-page and present a user-hinter or error-message on this page.

General solution

Prepare a component in the user’s session, that contains information to be displayed at the next script instance. This component might be a list of messages like this:

$_SERVER[ 'sys$flashMessagesForLater' ] = array( "Sorry, userID and password didn't match.", "Please login again." ); 

Each time a script request comes in, check if $_SERVER[ ‘sys$flashMessagesForLater’ ] is a non-empty array.

If this is the case, emit these values to a well-defined located on the generated HTML-page. A well-defined location would always be at the same location, somewhere at the top of each page. You might probably wish to add a read box around error messages.

You might want to prepare a class like this:

class CFlashMessageManager < static public function addFlashMessageForLater( $message ) < $_SERVER[ 'sys$flashMessagesForLater' ][] = $message; >static public function flashMessagesForLaterAvailable() < return isset( $_SERVER[ 'sys$flashMessagesForLater' ] ) && is_array( $_SERVER[ 'sys$flashMessagesForLater' ] ) && ( 0 < count( $_SERVER[ 'sys$flashMessagesForLater' ] )) ; >static public function getFlashMessageForLaterAsHTML() < return implode( '
', $_SERVER[ 'sys$flashMessagesForLater' ] ); > > // CFlashMessageManager

Источник

How to get the message form php page to Html page?

I was wondering how I could get the message from my php page to my html message. When the user successfully creates a user, I want to get the «success» message from php to the html. html:

$firstname = mysqli_real_escape_string($conn, $_REQUEST['firstname']); $stmt = "INSERT INTO user (firstname) VALUES('$firstname')"; if(empty($firstname) ) < echo $result = "added"; header('Location: index.php', true, 303); exit; >else < if (mysqli_query($conn, $stmt)) < echo "erro"; header('Location: index.php', true, 303); exit; >else < echo "Error: " .mysqli_error($conn); >> 

I did not include the connection file. The function works, its only the echo part that does not work. I get the error message «Fatal error»

3 Answers 3

You could do this by appending the message as a get var onto the header url which is a bit unorthodox

$stmt = "INSERT INTO user (firstname) VALUES('$firstname')"; if (mysqli_query($conn, $stmt)) < $msg = "success"; header('Location: index.php?msg='.$msg); exit; >else

in your html you would call the get var using:

or you could store the error message in a session:

 //include at top of your script session_start(); $stmt = "INSERT INTO user (firstname) VALUES('$firstname')"; if (mysqli_query($conn, $stmt)) < $msg = "success"; $_SESSION['msg'] = "Success message" header('Location: index.php'); >else

and on your recipient php file of the error message, also include session_start() and simple echo the $_SESSION[‘error’] like so

in your html you would call the get var using:

You are redirecting the user back to index.php.

You have two options to pass the message to index.php

header('Location: index.php', true, 303); 
header('Location: index.php?response=success', true, 303); 

Note: This scenario is xss prone, please use appt sanitizing before echoing the message.

The sql was potentially vulnerable to SQL injection so you ought to use prepared statements when dealing with user supplied data like this. It has already been suggested that using a session variable would be one way — this is how I might have done it.

Be wary of displaying too much information if there is some sort of error with the database query — fine for development but not in production.

prepare( $sql ); if( !$stmt )throw new Exception('Failed to prepare sql'); $stmt->bind_param( 's', $firstname ); $result=$stmt->execute(); if( $result && $stmt->affected_rows==1 ) < $_SESSION['useradded']='User added'; >else < throw new Exception('error adding user'); >$stmt->free_result(); $stmt->close(); $conn->close(); exit( header('Location: index.php') ); > else < throw new Exception('firstname is required'); >>catch( Exception $e )< $conn->close(); $_SESSION['error']=$e->getMessage(); exit( header('Location: index.php') ); > ?> 

%s', $_SESSION['error'] ); unset( $_SESSION['error'] ); > else < printf('

%s

', !empty( $_SESSION['useradded'] ) ? $_SESSION['useradded'] : '' ); unset( $_SESSION['useradded'] ); > > ?>

Источник

Оцените статью