my $_SESSION["message"] echoing everywhere even there is if - php

I have one problem.I wanted to echo my message ("subject created", "subject creation failed" depending on whether my subject is created or not). The problem is the message is on every page even though setting the $_SESSION["message"] is under if condition . I really don't know where is the problem. I lost probably 2 hours on this...
All includes and requires are included...
This is on my proceeding page:
if(isset($_POST["submit"])) {
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$query = "INSERT INTO subjects(";
$query .= " menu_name, position, visible ";
$query .= ") VALUES ('{$menu_name}', '{$position}', '{$visible}')";
$result = mysqli_query($connection,$query);
if($result) {
//success //
$_SESSION["message"] = "Subject created";
redirect_to("manage_content.php");
} else {
$_SESSION["message"] = "Subject creation failed";
redirect_to("create_new_content.php");
}
} else {
redirect_to("create_new_content.php");
}
my message function is:
session_start();
function message() {
if (isset($_SESSION["message"])){
$output = $_SESSION["message"];
return $output;
}
}
and after all Im echoing on my manage_content.php and create_new_content.php
<?php echo message(); ?>

You should clear the session when its not needed any more.
E.g.
unset($_SESSION['message']);

Try to clear your $_SESSION message and check if is not empty
function message() {
if (isset($_SESSION["message"]) && !empty($_SESSION["message"])){
$output = $_SESSION["message"];
$_SESSION["message"] = '';
return $output;
}
}

if you show your message only one time, you need to clear the $_SESSION["message"] before return
session_start();
function message() {
if (isset($_SESSION["message"])){
$output = $_SESSION["message"];
// clear the session message
$_SESSION["message"] = null;
// remove message index from $_SESSION
unset($_SESSION["message"]);
return $output;
}
}

Related

PHP $_SESSION returning incorrect value

Ok, so when I execute the initial function it works fine, the username gets stored in the database, however when I run the second function that appends the username to the text the user chooses to enter the IF statement returns 'no user' - when a user is defined...
If anyone knows how to fix this that would be great - I am currently learning PHP and mysql so I am sorry if any of this is incorrect
<?php
session_start()
// connect to the database
mysql_connect("localhost", "root", "");
mysql_select_db("ajaxchat");
// read the stage
$stage = $_POST['stage'];
// primary code
if($stage == 'initial') {
// check the username
$user = $_POST['user'];
$query = mysql_query("SELECT * FROM chat_active WHERE user='$user'");
if (mysql_num_rows($query) == 0) {
$time = time();
//
mysql_query("INSERT INTO chat_active VALUES ('$user', '$time')");
// set the session
$_SESSION['user'] = $user;
echo 'good';
}
else {
echo 'taken';
}
}
/////////////// PROBLEM FUNCTION ///////////////
================================================
else if($stage == 'send') {
// get the textdomain
$text = $_POST['text'];
// check for user_error
if (isset($_SESSION['user'])) {
$user = $_SESSION['user'];
echo $user.' - '.$text.'<br />';
}
else {
echo 'no user';
}
}
else {
echo 'error';
}
?>
This is the javascript:
<script type="text/javascript">
function chat_initialise() {
var user = document.getElementById("chat_user").value;
$.post("./chat.php", {stage:"initial", user:user}, function(data) {
if (data == "good") {
$('#initial').css('display', 'none');
$('#content').css('display', 'inline')
}
else {
alert("That username is taken! Please try another.");
}
});
}
function chat_send() {
var text = document.getElementById("chat_text").value;
$.post("./chat.php", {stage:"send", text:text}, function(data) {
document.getElementById("chat_text").value = '';
$('#window').text($('#window').text() + data);
// alert(data)
});
}
</script>
I fixed it - changed the POST function to take the current username then redefine it as a variable in the second function:
else if($stage == 'send') {
// get the textdomain
$text = $_POST['text'];
$user = $_POST['user'];
echo $user;
// check for user_error
if (isset($_SESSION['user'])) {
$_SESSION['user'] = $user;
echo $user.' - '.$text.'<br />';
}
else {
echo 'no user';
var_dump($_SESSION);
}
}
Thanks for all your help guys!!

PHP Form data validation issue

I am making a basic content management system and I have got stuck with the validation of data being entered into a form.
For example, one form is to edit the name of a subject (in the navigation menu). The form contains a few different pieces of data but the main focus is the "menu_name" field (name of subject).
On form submission data in "menu_name" should be checked to ensure it is not empty and if it is then give an error. What is happening is that the form validation doesn't seem to be working as when I enter nothing the script continues to edit the subject name, in this case making it blank.
This is the script that is executed on form submission:
if (isset($_POST['submit']))
{
// Process the form
// Validations
$required_fields = array("menu_name", "position", "visible");
validate_presences($required_fields);
$fields_with_max_lengths = array("menu_name" => 30);
validate_max_lengths($fields_with_max_lengths);
// If errors occured, redirect
if(empty($errors))
{
// Perform update
// Assign POST data to variables
$id = $current_subject["id"];
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
// 2. Perform database query
$query = "UPDATE subjects SET ";
$query .= "menu_name = '{$menu_name}', ";
$query .= "position = '{$position}', ";
$query .= "visible = '{$visible}' ";
$query .= "WHERE id = {$id} ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) >= 0)
{
// Success
$_SESSION["message"] = "Subject updated.";
redirect_to("manage_content.php");
}
else
{
// Failure
$message = "Subject update failed.";
}
}
}
The data is then checked by two custom validation functions as you can see, the second one is not my concern but the first function validate_presences(), here is the function:
function validate_presences($requried_fields)
{
GLOBAL $errors;
foreach($required_fields as $field)
{
$value = trim($_POST[$field]);
if (!has_presence($value))
{
$errors[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
You can see there that it references the has_presence() function, which is:
function has_presence($value)
{
return isset($value) && $value !== "";
}
If anyone has any ideas on what is wrong, any help is appreciated!
Just ask if you need some more information.
Thanks in advance!
Why don't you just return the error array instead of making it global? I think it will resolve your problem instantly ;)
function validate_presences($requried_fields)
{
$errors = array();
foreach($required_fields as $field)
{
$value = trim($_POST[$field]);
if (!has_presence($value))
{
$errors[$field] = fieldname_as_text($field) . " can't be blank";
}
}
return $errors;
}
Now set $errors = validate_presences($required_fields); and your ready to go!
It's not recommended to use variables in a global way like this. Rather pass the errors variable by reference to the validation functions.
$errors = array();
function validate_presences($requried_fields, &$errors)
{
foreach($required_fields as $field)
{
$value = trim($_POST[$field]);
if (!has_presence($value))
{
$errors[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
$required_fields = array("menu_name", "position", "visible");
validate_presences($required_fields, $errors);
$fields_with_max_lengths = array("menu_name" => 30);
validate_max_lengths($fields_with_max_lengths, $errors);
// If errors occured, redirect
if(empty($errors))
{

echo a message on a new page

I want to echo a message on a new page after redirecting. but I only want the message to show once after reloading (redirecting) and on the next reload I want the message gone. is this at all possible? I give you an example:
$_SESSION['message'] = "entry deleted"
header("location: anotherpage.html")
on "anotherpage.php"
echo "$_SESSION['message']" // upon next reload $_SESSION['message'] = "";
echo $_SESSION['message'];
unset($_SESSION['message']);
But I prefer to add a function to display messages, something like:
function setMessage($msg_body, $css_style = 'normalMsg') {
$_SESSION['messages'][$css_style][] = $msg_body;
}
function showMessages() {
if (empty($_SESSION['messages'])) return;
foreach ($_SESSION['messages'] as $css_style=>$messages) {
echo '<div class="'.$css_style.'">';
echo implode($messages,'<br>');
echo '</div>';
}
unset($_SESSION['messages']);
}
You can check, if message is set and valid
if (isset($_SESSION['message']) && $_SESSION['message']) {
echo $_SESSION['message'];
$_SESSION['message'] = false;
}
It should be working as you suggested. (If I got you right).
Simply:
the redirecting page :
$_SESSION['message'] = 'test';
header('Location: anotherpage.php');
on "anotherpage.php" :
echo $_SESSION['message'];
$_SESSION['message'] = ''; // message will being empty on further reloads

returning array and message to function

please help me out regarding this function. I want to fetch data from the database and if there are results, I want to return a message and data array.
$this->query=("select * from user where pno='".$search."'");
$rd = $this->executeQuery();
$data = $rd->fetch_assoc();
if ($data) {
$message = "Record found.";
} else {
$message = "Record not found.";
}
return array($data, $message);
I am calling it this way:
list($data, $message)=$user->search($result);
echo $message
echo $data['name'];
I am getting the message but I am unable to fetch the array.
Please help me out if there is a problem in the function or if I can improve it.
Never do it this way
you should put your message setting code outside of the function.
function getData(){
$this->query=("select * from user where pno='".$search."'");
$rd = $this->executeQuery();
return $rd->fetch_assoc();
}
if ($data = getData()){
$message = "Record found.";
echo $message;
echo $data['name'];
} else {
$message = "Record not found.";
echo $message;
}
I'm not sure what you're using, but most likely you'll have an array of rows in $data, even if there is only single row. Try $data[0]['name']. Besides, I'd suggest that you move that message from your function to the place where it's called, and make the function return NULL or FALSE if nothing found.
$this->query=("select * from user where pno='".$search."'");
$rd = $this->executeQuery();
$data = $rd->fetch_assoc();
return empty($data)?FALSE:$data;
You’re missing a semicolon after echo $message in your code example.
Try appending this to your code and tell us what it returns:
var_dump($data);

Validating input and returning errors with PHP and XML

I have a form with several input fields, i would like to go through and check to make sure they are all present before continuing.
This is the code i am using
if(isset($_POST['url'])){ $url = $_POST['url']; } else { echo "<error>no url</error></data></xml>"; exit(); }
if(isset($_POST['username'])){ $username = $_POST['username']; } else { echo "<error>no username</error></data></xml>"; exit(); }
if(isset($_POST['password'])){ $password = $_POST['password']; } else { echo "<error>no password</error></data></xml>"; exit(); }
if(isset($_POST['cachename'])){ $cachename = $_POST['cachename']; } else { echo "<error>no cachename</error></data></xml>"; exit(); }
if(isset($_POST['lat'])){ $lat = $_POST['lat']; } else { echo "<error>no lat</error></data></xml>"; exit(); }
if(isset($_POST['long'])){ $long = $_POST['long']; } else { echo "<error>no long</error></data></xml>"; exit(); }
if(isset($_POST['message'])){ $message = $_POST['message']; } else { echo "<error>no message</error></data></xml>"; exit(); }
if(isset($_POST['notes'])){ $notes = $_POST['notes']; } else { echo "<error>no notes</error></data></xml>"; exit(); }
if(isset($_POST['tags'])){ $tags = $_POST['tags']; } else { echo "<error>no tags</error></data></xml>"; exit(); }
The problem im getting, is even when i JUST enter a URL, it returns "no lat". Even when i fill in everything down to notes, it still returns "no lat"
Any ideas?
Check values in $_POST
echo "<pre>";
print_r($_POST);
echo "</pre>";
Make sure every post variable is set and the names match.
Not that this will fix your problem (see Ólafur's comment), but, here's a more automated way of performing validation on all of your fields:
$required = array('url', 'username', 'password', 'cachename',
'lat', 'long', 'message', 'notes', 'tags');
while (list($i, $require)=each($required)){
if(empty($_POST[$require])){
die('<error>no ' . $require . '</error></data></xml>');
}else{
$$require = $_POST[$require];
}
}
PS: empty() is often better better to use than isset(). An empty string will return true with the isset() function.

Categories