Pass multiple values through header function - php

I want to set a message for the user to see in php, but I'm having issues crossing controllers. Here was my first try:
if($revOutcome > 0){
$message = "<p>Review updated!</p>";
header('Location: /acme/accounts/index.php?action=seshLink');
exit;
}
And here was my second try:
if($revOutcome > 0){
header('Location: /acme/accounts/index.php?action=seshLink&message=Update was successful!');
exit;
}
I have an isset in the view that checks if $message is set, and if it is, echo what is displayed in $message. But for some reason, it's not displaying. Here is the code for the view:
<?php
if (isset($message)) {
echo $message;
}
?>
And here is the switch case statement seshLink:
case 'seshLink':
$userId = $clientData['clientId'];
$revData = getCliRev($userId);
if(!$revData){
$message = "<p>No reviews here yet. Write your first one today!</p>";
include '../view/admin.php';
exit;
}
else {
$RevDisplay = buildAdminReviewDisplay($revData);
}
include '../view/admin.php';
break;
I really don't know why $message isn't displaying.

Because you are making a request call (parameters through url) which means that you need to get your variables using $_GET array like
...
if (isset($_GET["message"]))
...

Related

call a php function inside a div

I want to make a call of this php logic inside a html div but when passing it as a function the logic breaks since it does not send an error message in case of entering the pass wrong and its confirmation at the time of performing the password change.
<?php
require 'funcs/conexion.php';
require 'funcs/funcs.php';
$user_id = $mysqli->real_escape_string($_POST['user_id']);
$token = $mysqli->real_escape_string($_POST['token']);
$password = $mysqli->real_escape_string($_POST['password']);
$con_password = $mysqli->real_escape_string($_POST['con_password']);
if(validaPassword($password, $con_password))
{
$pass_hash = hashPassword($password);
if(cambiaPassword($pass_hash, $user_id, $token))
{
echo "Contraseña Modificada <br> <a href='index_alumnos.php' >Iniciar Sesion</a>";
} else {
echo "Error al modificar contraseña";
}
} else {
echo "Las contraseñas no coinciden <br> <a href='index_alumnos.php' >contacta a Academia</a>";
}
?>
If the echo happens before your actual div is drawn, the echo goes... right where it happens. Which isn't within your div.
One way of getting around this would be to put your error message into a variable and then deliver this variable into your div (whether it be through a return value, if it's a call, or some other means.)
Here's a simple example to illustrate this:
<?php
if(1 === 2) {
//great, 1 is 2
} else {
//oh no, an error
$someErrorLine = '1 is not 2';
} ?>
<h1>Hi</h1>
<div><?= $someErrorLine ?></div>
You could also check if the variable exists, something like if(isset($someErrorLine)) {} and echo the div with it, or put the div within your variable.

Setting General Messages Using Flash Message

I have a simple register form, my form validates but will not show error messages or validation messages
This is my form function
function validate_new_user()
{
$errors = [];
if (isset($_POST['register'])) {
$email = $_POST['email'];
$name = str_replace(" ", "", $_POST['username']);
$password = $_POST['password'];
if (empty($email)) {
$errors[] = "Email Address is required";
}
if (empty($name)) {
$errors[] = "Username is required";
}
if (strlen($password) < 5) {
$errors[] = "Password must be at least 6 characters long";
}
if (!empty($errors)) {
set_message($errors[0], WARNING);
} else if (create_new_user($email, $name, $password)) {
set_message('Please check your email for user Information.', SUCCESS);
redirect_to_url("/user/login");
}
}
}
I call my validation function in my form page
<?php validate_new_user(); ?>
so if there is an error it should set message but don't.
now if it successfully it redirects to login and sets a flash message also and I call it with
<?php display_message(); ?>
That don't display a message either
Flash message code
define('SUCCESS', 'success');
define('INFO', 'info');
define('WARNING', 'warning');
function set_message($message, $type = 'success')
{
if (!empty($_SESSION['flash_notifications'])) {
$_SESSION['flash_notifications'] = [];
}
$_SESSION['flash_notifications'][] =
$message = [
'<div class="alert . $type .">$message</div>'
];
}
function display_message()
{
if (isset($_SESSION['flash_notifications'])){
return $_SESSION['flash_notifications'];
}
}
my goal is to use one set message for all notifications with styles but I cannot get none of the messages to display
I’ll assume you’re calling session_start() at the beginning of the script.
Your usage of functions makes the problem much easier to diagnose! Sometimes, though, it helps to have a different set of eyes look at it.
Your function set_message() has a couple of errors:
The initialization of $_SESSION['flash_notifications'] should occur if it is empty, but instead you are initializing if it is not empty. Hence nothing can be added
Malformed assignment. When you are building the message array to save in $_SESSION, there is no need to reassign $message. Also, usage of single quotes does not interpret variables within the quotes, so the html snippet is not what you expect.
Corrected function:
function set_message($message, $type = 'success')
{
if (empty($_SESSION['flash_notifications'])) {
$_SESSION['flash_notifications'] = [];
}
$_SESSION['flash_notifications'][] = '<div class="alert '. $type .'">'.$message.'</div>';
}
Note, it might be more understandable to write it this way:
$_SESSION['flash_notifications'][] = <<<FLASH
<div class="alert $type'">$message</div>
FLASH;
Your function display_message() is almost correct as is, except you’re returning an array, not a string. If you’re going to print it, it must be converted into a string:
function display_message()
{
if (isset($_SESSION['flash_notifications'])){
return join('',$_SESSION['flash_notifications']);
}
}
Then when you call it in your html, use the short print tag instead of the regular <?php tag:
<!— somewhere in your view (html output) —>
<?= display_message() ?>
<!— continue html —>

php contact form using location.href

i have created a contact form using html and php to send the email, when the user fills the forms it just display blank screen
// Let's send the email.
if(!$error) {
//$messages="From: $email <br>";
$messages.="Company Name: $name <br>";
$messages.="Email: $email <br>";
$messages.="Message: $message <br>";
$emailto=$to;
$mail = mail($emailto,$subject,$messages,"from: $from <$Reply>\nReply-To: $Reply \nContent-type: text/html");
if($mail) {
$url = 'index.php?page=process&token=101';
echo "<script language=\"javascript\">
location.href=\"$url\";
</script>";
exit;
}
} else {
echo '<div class="error">'.$error.'</div>';
}
}
want if the user entered all the fields then should send them to index.php?page=process&token=101
Try this instead. There is no sense in echoing out a partial HTML page with a script tag in it when you can redirect them in PHP.
header("Location: $url");
Try this,
echo "<script>
window.location = '$url';
</script>";
I would suggest to go with header(), instead of java script.
In this case instead on JavaScript best practice is use the php function for redirection.
Try this
header("Location: index.php?page=process&token=101");

Send a POST value only with PHP

I want to use my webpage to recognize if a $_POST is set and the, if it is, print it in the page, so this is what I really have now:
if (isset($_POST['error'])) {
echo '<div id="error">'.$_POST['error'].'</div>';
}
But what I want is that, when an if statement that I have in the same document returns true, to send a POST request to that same file and so, show the error message with the $_POST. Is this possible or it is another easy way for doing it?
Sorry for not explaining so well, this is my code:
if (password_verify($_POST['oldpassword'], $result['password'])) {
// Upload password to database
} else {
// Set the $_POST['error'] to an error message so I can show it in the error DIV.
}
Thanks!
You can define a $message athe beginning of your page then handle the errors you want to show
$message = '';
if (password_verify($_POST['oldpassword'], $result['password'])) {
// Upload password to database
} else {
//set a proper message ID which will be handled in your DIV
$message_id = 1;
header('location: /current_path.php?message='.$message_id);
}
Now in the div you can show it as
if (!empty($_GET['message'])) {
echo '<div id="error">';
if ($_GET['message'] == 1) { echo 'First message to show.'; }
elseif ($_GET['message'] == 2) { echo 'Second message to show.'; }
echo '</div>';
}

PHP display error on another page

I'm having issues to send an occuring error to another page.
I have already created the page the error will be sent to, and I've tried a header function. But that doesn't seem to work. Here is the php code that I am using for the page.
<?php
if(isset($_POST['username'], $_POST['password'])){
//login the user here
$connect = mysql_connect("","","")or die(mysql_error());
mysql_select_db("")or die(mysql_error());
$errors = array();
$username = strip_tags(mysql_real_escape_string($_POST['username']));
$password = strip_tags(mysql_real_escape_string($_POST['password']));
if (empty($Regi_Username) || empty($Regi_password)) {
$errors[] = 'All fields are requerid';
} else {
if (strlen($Regi_Username) > 25) {
$errors[] = 'Username is to long';
}
if (strlen($password) > 25) {
$errors[] = 'Password is to long';
}
}
$password = md5($_POST['password']);
$loginquery = "SELECT * FROM regi WHERE username='$username' and password='$password'" or die(mysql_error());
$result = mysql_query($loginquery);
$count = mysql_num_rows($result);
mysql_close();
if($count==1){
$seconds = 2000 + time();
setcookie(loggedin, date("F jS - g:i a"), $seconds);
header("location:member.php");
} else {
echo 'Wrong username and password please try agian.';
}
}
?>
Pass the GET variable in your URL like..
header('Location:page.php?err=1');
exit;
On the other page use this
if(isset($_GET['err'] && $_GET['err'] == 1) {
echo 'Error Occured';
}
Here is a session based approach. This is the best way to pass messages from one page to another as they are stored in the user's session (a piece of data related to each user and stored in the server side) and not in the browser (like cookies or URL GET parameters, which can be easily corrupted), so it is really quite harder to manipulate the messages from 3rd parties.
Page process.php:
<?php
// Very top of your page
session_start();
$_SESSION['errors'] = array();
// Do stuff now...
// ...
// Hey it's a X error!
$_SESSION['errors']['X'] = 'Message for X error';
// Continue doing stuff...
// ...
// OMG! It's a Y error now!
$_SESSION['errors']['Y'] = 'Message for Y error';
// Keep doing stuff till you're done...
// All right, process is finished. Any Errors?
if (count($_SESSION['errors']) > 0) {
// It seems there's been any errors
// time to redirect to error-displaying page
header('Location: error-page.php');
exit;
}
Page error-page.php:
<?php
// Very top of your page
session_start();
// Let's check if there is any error stored in the session.
// In the case no errors found, it is better to redirect to another page...
// ...why anybody would end in this page if no errors were thrown?
if (!isset($_SESSION['errors']) || !is_array($_SESSION['errors']) || empty($_SESSION['errors'])) {
header('Location: home.php');
exit;
}
// If we reach this point it means there's at least an error
foreach ($_SESSION['errors'] as $errorCode => $errorMessage) {
// Here we can display the errors...
echo '<p>Error ', $errorCode, ': ', $errorMessage, '</p>', PHP_EOL;
}
// You can also do stuff only if a certain error is received
if (array_key_exists('X', $_SESSION['errors'])) {
// Error `X` was thrown
echo '<p>Oh no! It seems you suffered a X error!!</p>', PHP_EOL;
echo 'Click here to go back home.', PHP_EOL;
}
// At the end you should to remove errors from the session
$_SESSION['errors'] = array();
// or
unset($_SESSION['errors']);
You could use Alien's method, but it'd better if you use Session:
// Assume you init the session already; Use json_encode since you use array for $errors
$_SESSION['errors_msg'] = json_encode($errors);
header("location:member.php");
// Remember to exit here after we call header-redirect
exit;
Besides, there are a lot of problems is your currently code:
Use salt for hashing password
Use mysqli over mysql
Filtering input, escaping output
.. Read other recommendations here in this topic ..
Please read http://www.phptherightway.com/. There is a lot of right recommendation (of course not all) for PHP.

Categories