Using php header Location to exchange messages between pages with POST - php

I am using already this code:
<?php
// [...]
ELSE IF(isset($_GET['msg'])){
echo "<div id='noticePanel' class='panel panel-success'><div class='panel-heading'>
<h2 class='panel-title'>Good job!</h2></div>
<div class='panel-body'><h4>".addslashes(strip_tags(trim(#$_GET[msg])))."</h4></div></div>";
}
//[...]
?>
Which is called from other pages if some operation goes well:
if ($result){
header("Location:index.php?msg=DB updated succesfully");
exit;
}
BUT as you may imagine, it is not clean. Working, but not the best.
Can anybody tell me if I should move it to a POST request or if this code is "widely" used to exchange status messages between pages?
And, in case of the POST, can someone write down some code or redirect me to a page where this is explained well? I searched already of course, I found THIS from mozilla, THIS with jquery and in general searching "send post php header" on google.
But I just can't understand how to do it.
Thanks a lot guys!

Because you prefer to keep your code pure
i just suggest you to do not send the message in GET/POST
just send the status like
index.php?status=success
then check the status in result file
if(isset($_GET['status']) AND $_GET['status'] == success){
echo "bla bla";
}elseif(isset($_GET['status']) AND $_GET['status'] == fail){
echo "bla bla";
}else{
//do something
}
EDIT
If you have many messages, then you can create array
$message = [
'success' => 'success message here',
'fail' => 'failmessage here',
'notFound' => 'not found message'
];
$status = ( isset($_GET['status']) AND
isset($message[$_GET['status']]) )?$_GET['status']:'notFound';
echo $message[$status];

I think i'm going to go with this: PHP. How to pass variable and auto redirect to another PHP file
<?php
session_start();
$id = $user_profile['id'];
$_SESSION['id'] = $id;
header('Location: checkIfExsists.php');
?>
And on the checkIfExsists.php page, retrieve the variable so:
<?php
session_start();
$id = $_SESSION['id'];
?>
New code
session_start()
// [...]
ELSE IF(isset($_GET['msg'])){
echo "<div id='noticePanel' class='panel panel-success'><div class='panel-heading'>
<h2 class='panel-title'>Good job!</h2></div>
<div class='panel-body'><h4>".addslashes(strip_tags(trim(#$_SESSION['msg'])))."</h4></div></div>";
}
And..
session_start();
if ($result){
$_SESSION['msg'] = "DB updated!";
header("Location:index.php?msg");
exit;
}

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.

Pass multiple values through header function

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"]))
...

PHP echo in a HTML Page

I have a contact.html page I have a form on. The form action goes to .php page to handle the email, nothing special. On that page I have:
<?php
function check_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$FirstName = check_input($_REQUEST['FirstName']);
$LastName = check_input($_REQUEST['LastName']);
$email = check_input($_REQUEST['email']);
$phone = check_input($_REQUEST['phone']);
$message = check_input($_REQUEST['message']);
$human = check_input($_REQUEST['human']);
$webpackage = check_input($_REQUEST['webpackage']);
$webdesign = check_input($_REQUEST['webdesign']);
$customdesign = check_input($_REQUEST['customdesign']);
if ($human == 5) {
$to = "****.com";
$subject = "From ****";
$body = " From: $FirstName $LastName\n\n E-Mail: $email\n\n Phone: $phone\n\n Message:\n\n $message\n\n Web Package:$webpackage\n\n Web Design:$webdesign\n\n Custom Design:$customdesign";
mail ($to, $subject, $body);
header('location: index.html');
}
else {
$result="<div class=\"alert alert-danger\">Sorry there was an error sending your message. Please go back and check your anti-spam answer</div>";
}
?>
I have a simple box that equals 5 that I am checking value for. This works and email sent with all info. BUT if not equal to 5 is where the problem starts. The page goes to my action.php page and is blank.
My html on the contact.html page is:
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<?php echo($result); ?>
</div>
</div>
Using this to get to my action.php page through form. Everything else is .html:
<form class="form-horizontal" id="contact-form" method="post" action="/action.php">
Is there a way to do this? I have a work around where I just echo the error from the .php page. This works if !=5 but not exactly what I want to do. As you may tell, I am not PHP literate.
You can set a variable in the $_SESSION[] array, and in your "else" section use Header() to redirect to a page where you display the value you stored.
See example in this other answered question:
displaying a message after redirecting the user to another web page
Update your else part with following code :
} else {
header('location: contact.html?status=error');
}
Now check if get method is set on your contact.html page. if yes than set and display your $result value.
<?php
if(isset($_GET['status']) && $_GET['status']=='error' ) {
$result="<div class=\"alert alert-danger\">Sorry there was an error sending your message. Please go back and check your anti-spam answer</div>";
} ?>
on contact.html check if $result has value and print it :)
Add a redirect towards contact.html in your action.php like this
else {
$result="Sorry there was an error sending your message. Please go back and check your anti-spam answer";
$result=str_replace(" ","%20",$result);
header('location: contact.html?result=$result');
}
And then get the result in contact.html with GET
$result= $_GET['result'];
Ideally do the html mark up for result in the destination Contact.html page after you receive the result. That eliminates the nuances of passing html over http

AJAX fade on submit

I have a quick question about this fade out div. I use facebox, and after the submit, and it shows an error it'll show this:
http://puu.sh/1uPnF
however I want that to fade away, after they've caught that message. On my AJAX handler for the submit form, this is the PHP code:
<?php
require_once('....');
$form_name = $_GET['form_name'];
$form_comment = $_GET['form_comment'];
$date = date('Y-n-j');
$ip = $_SERVER['REMOTE_ADDR'];
if($form_name == '') {
echo("<div class='alert alert-error-x'>Don't forget to enter a name, as we need to identify who's commenting on this article!</div>");
} else if($form_comment == '') {
echo("<div class='alert alert-error-x'>Please do not leave the comment field blank, we want to know what you're saying!</div>");
} else {
mysql_query("INSERT INTO comment (id, articleid, name, comment, date, ip) VALUES (NULL,'{$_GET['id']}','{$form_name}','{$form_comment}','{$date}','{$ip}')");
// output comment
echo "<div class='alert alert-success-x'>Posted by <strong>$form_name</strong> on <strong>{$date}</strong>$form_comment</div>";
}
?>
This is where the output of what would be submitted, on the article.php:
<?php
$amount_get = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "'"); $comments = mysql_num_rows($amount_get);
$grab = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "'");
if (mysql_num_rows($grab)==0) {
echo "<div class='alert alert-note-x'>Sorry, it looks like their are no comments to be displayed, check back later!</div>";
}
while($row = mysql_fetch_array($grab)){
?>
<div id="new_comment"></div>
<div class="article-comment">
Posted by <b><?php echo $row['name'] ?></b> on <b><?php echo $row['date'] ?></b>
<br />
<?php echo $row['comment'] ?>
</div>
<?php } ?>
</div>
</body>
</html>
Now I tried adding the below code in the core.js file, which is located on my site at krissales.com
$(window).bind("load", function() {
$('#new_comment').fadeOut(4000);
});
However it did not work. If you want to test the demo, then check it out at: http://www.krissales.com/#/media/30.This-is-a-new-article-for-Testing!
What is it that I'm doing wrong, please?
Thanks!
If you're using AJAX, I suggest you use jquery's ajax method (http://api.jquery.com/jQuery.ajax/) to make the call to your PHP file.
Then, use the success callback function of that method to show the correct response.
Hiding the response can then simply be done by fading out the div (with a delay if you want that).
if ($('#new_comment').length > 0)
{
$('#new_comment').delay(4000).fadeOut();
}
You are now trying to fade out the message on window load, but since you're using AJAX, there is no page reload happening.
Hope this helps you!

PHP session variable, check then delete

Code:
if(!$picture) $error = $error."<div>This is a photo site, we require you select a photo.</div>";
if(!$imgname) $error = $error."<div>You must enter a name for your photo.</div>";
if(!$description) $error = $error."<div>You must enter a description for your photo.</div>";
else if(strlen($description) > 500) $error = $error."<div>Your descriptions to long. 500 characters max.</div>";
if(!$error) {
$case = 2;
$max_width_new = 190;
$make_thumb=1; $make_medium=1; $make_original=1;
$imagename = "picture";
$folders = "accounts/".$dbid."/";
if(!file_exists($folders))
mkdir($folders);
include("scripts/php/uploadpicture.php");
if($file) {
$connect = mysql_connect("localhost","headinth_admin","adobe1234");
mysql_select_db("headinth_core");
mysql_query("INSERT INTO pictures (id, uploader, name, description, location, picture, date) VALUES('','$dbid','$imgname','$description','$location','$file_name','$date')");
$_SESSION['uploaded'] = 1;
header("location: ?upload");
}
} else echo "<div class='green f18 fl coolvetica' style='text-align:left;'>".$error."</div><div class='c20'></div>";
}
if(isset($_SESSION['uploaded'])) {
echo "<div class='white f18 fl coolvetica' style='text-align:left;'>Your picture was uploaded.</div><div class='c20'></div>";
unset($_SESSION['uploaded']);
}
?>
So it goes through and if everything successful it declares $_SESSION['uploaded'] = 1. Makes sense. Since theres a header it refreshes the page. Then I check if $_SESSION['uploaded'] exists, to see if a photo was just uploaded. If it was then it should send the message "Your photos been uploaded". Then it would have to delete the $_SESSION['uploaded'] variable so it doesn't show up again if the page is refreshed or an invalid submission is made.
The issue is that its just skipping the if(isset($_SESSION['uploaded'])) line and just unsetting the session. So its not echoing the success message. IF i delete the unset it works, just always appears until the entire session is destroyed. So the goal, carry a variable over a page refresh, echo it then remove it.
header() doesn't halt execution of your script. After the header() command, the script continues to your isset()/unset() block. The solution is to die after the header():
header("location: ?upload");
die;
I think its just an issue with the order that you're doing the output and the unsetting.
$_SESSION['test'] = 1;
echo "test session variable is: {$_SESSION['test']} <br />";
unset($_SESSION['test']);
echo "test session variable is: {$_SESSION['test']}";
will output:
test session variable is: 1
test session variable is:

Categories