Remove item from session (show a remove button) - php

I have a button on a page, It's a simple input submit button, which sends the page ID to a form on another page to save it in a PHP session.
I was wondering how I'd go about showing a remove button instead if that item is already in your session?
This is the code that the form gets sent to
<?php
session_start();
if(!in_array($_POST['event_id'], $_SESSION['event_orders'])) {
$_SESSION['event_orders'][] = $_POST['event_id'];
}
?>
The page with the button doesn't actually have any session code, but I guess it would be a similar IF kind of statement, but I am unsure of the exact syntax I should use? And how would it take the ID away from session?
EDIT:
Would something like this work? To put around the form button.
<? if(isset($_SESSION['event_orders']))
{
echo "<a href='".$_SERVER['PHP_SELF']."?delete'>delete</a>";
}
else if(!in_array($_POST['event_id'], $_SESSION['event_orders'])) {
// echo the submit button;
} ?>

You can use unset function. Reference: http://php.net/manual/en/function.unset.php

<?php
session_start();
//if request parameter delete is present then unset the array
if(isset($_REQUEST['delete']))
{
unset($_SESSION['event_orders']);
}
else if(isset($_SESSION['event_orders']))
{
//displays delete link which redirects to same page with an additional request parameter as url?delete
echo "<a href='".$_SERVER['PHP_SELF']."?delete'>delete</a>";
}
else if(!in_array($_POST['event_id'], $_SESSION['event_orders'])) {
$_SESSION['event_orders'][] = $_POST['event_id'];
}
?>
EDIT:
we need only to delete the specific array items instead of fully unseting the array.
<?php
session_start();
//if request parameter delete is present then unset the array
if(isset($_REQUEST['delete']))
{
unset($_SESSION['event_orders'][$_REQUEST['delete']]);
var_dump($_SESSION['event_orders']);
}
else if(in_array($_POST['event_id'], $_SESSION['event_orders']))
{
//displays delete link which redirects to same page with an additional request parameter as url?delete
$key = array_search($_POST['event_id'], $_SESSION['event_orders']);
var_dump($_SESSION['event_orders']);
echo "<a href='".$_SERVER['PHP_SELF']."?delete=".$key."'>delete</a>";
}
else
{
$_SESSION['event_orders'][] = $_POST['event_id'];
var_dump($_SESSION['event_orders']);
}
?>

Related

how to pass session value other page if condition true in php

i have a $_sesstion['usermail']. i want to pass this value to next page.if condition match ($answer= $_SESSTION['usermail']);
if(isset($_POST['compair']))
{
echo $_SESSION['question'];
$_SESSION['usermail'];
$answer=$_POST['answer'];
if ($answer == $_SESSION['answer'])
{
header("Location:resetpass.php");
}
else
{
echo "<script>alert('Please Try again')</script>";
}
}
i want to pass $_sesstion['usermail'] value on resetpass.php page.
I think your logic is wrong here. What exactly are you checking in the if statement. A session variable means you can use it on every page that has session_start(); on top.
Sessions by default pass to other pages.
Make sure you have start_session(); on top of the page you want to access the session variable.
So if $_SESSION['usermail'] is working on your current page, it'll work on your next as well with same data.
Get an idea from this exmple
First Page
<?php
session_start();
$_SESSION['name'] = "Adam";
?>
Second page
<?php
session_start();
echo $_SESSION['name'];
?>
You can use GET methods for sharing your session value to next page...
if(isset($_POST['compair']))
{
echo $_SESSION['question'];
$_SESSION['usermail'];
$answer=$_POST['answer'];
if ($answer == $_SESSION['answer'])
{
$value_to_share=$_SESSION['usermail']; // You can share using GET
header("Location:resetpass.php?value=$value_to_share");
// receive this value at resetpass.php by $_GET['value']
}
else
{
echo "<script>alert('Please Try again')</script>";
}
}

Redirecting to same page along with Success Message with Php [duplicate]

This question already has answers here:
Redirect to another page with a message
(6 answers)
Closed 8 months ago.
What's the best way to display a success message after redirecting to same page? I've been thinking about doing that with javascript but maybe there's a way to do this with Php? The user submit from profile.php and gets redirected to same page. I'd like to grab a variable... Can I concatenate after $_SERVER['HTTP_REFERER']? Whats the best approach?
here a snippet of code: query.php
$stmt->execute() or die(mysqli_error($db));
if($stmt){
// echo "Data Submitted succesfully";
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
}
$stmt->close();
$db->close();
}
You could skip the session, and pass a url query parameter as a code or the message.
$stmt->execute() or die(mysqli_error($db));
if($stmt){
// echo "Data Submitted succesfully";
header('Location: ' . $_SERVER['HTTP_REFERER'] . '?message=success1');
exit;
}
$stmt->close();
$db->close();
}
Then have code that checks for $_GET['message] ...etc
You can use sessions. Just start session, save message in global array $_SESSION, then in profile.php check if $_SESSION with your key is set and it isn't empty show it. After it you can unset your key in $_SESSION.
query.php
<?php
session_start();
//your code
if($stmt) {
$_SESSION['myMessage'] = 'Some message';
//your code
}
//rest of your code
profile.php
<?php
session_start();
//your code
if(isset($_SESSION['myMessage']) && $_SESSION['myMessage'] !== '') {
//display message or do with it what you want
}
//rest of code
If you're processing your form in the same page, then you don't have to do any redirection. The solution to achieve the desired result would be like this:
Put your form processing code at the very top of your PHP script i.e. profile.php page.
Use a boolean variable to hold the status of ->execute() statement, and use that same variable at later point of your code.
So the code would be like this:
// Declare a boolean variable at the beginning
$status = false;
// your code
$status = $stmt->execute();
$stmt->close();
$db->close();
}
if($status){
// Data submitted succesfully
}else{
// Data couldn't get submitted
}
If you want to process the form at the same file, you don't need to redirect again to the same page.
As mention by the other answer, you process the form at the top of the page.
To display a message after success or failure, you store the message in a variable. Later with the from you echo the message variable if it is set.
// Check if form was submitted
if(isset($_POST['submit'])) { // I name the submit button "submit"
// process the form
if ($stmt->execute()) {
$message = "<div> Success </div>";
} else {
$message = "<div> Failed </div>";
}
}
// Display The form and the message if not empty
if (! empty($message)) {
echo $message;
}
// Form

How to get url on form submit

i just created a form and i am facing a problem on submit.
Example:
Here i have the link to edit.php where i get all the information with this link.
index.php
<a href="change/info/edit.php?url= '
. $row['url']
.'&title='. $row['title']
.'&info='. $row['info']
.'&name='. $row['name']
.'&date='. $row['date'] .' " target="_blank">Edit</a>
Here i get all the information from index.php like this here below:
edit.php :
<?php echo $_GET["title"]; ?>
<?php echo $_GET["info"]; ?>
<?php echo $_GET["date"]; ?>
<?php echo $_GET["name"]; ?>
<?php echo $_GET["url"]; ?>
EDIT: Ares Draguna
<?php session_start();
if(isset($_POST['Submit'])){
// code for check server side validation
if(empty($_SESSION['captcha_code'] ) || strcasecmp($_SESSION['captcha_code'], $_POST['captcha_code']) != 0){
$msg='<span class="fail">Please try again.</span>';// Captcha verification is incorrect.
}else{// Captcha verification is Correct. Final Code Execute here!
}
}
But when i hit the submit button and captcha is false the page refresh and i lose all the information, i have to hit back in the browser to see again all the information.
So what do i need to keep the information, when hit the submit button and captcha is false.
Thanks in advance !
To keep the information on the form, you can set some session variables like:
$_SESSION['title'] = $_GET["title"];
$_SESSION['info'] = $_GET["info"];
and so on... and the test it:
if(capcha == false) {
//do something
} else {
//unset the session variables
}
In this scenario, if the capcha is false, then you can repopulate the form inputs with what you have in session, so even after the page is reloaded you still have those information stored. If the capcha is true, then remember to unset the session vars.
However, if the exact same page refreshes, it means that you have the values in $_GET so you could use that with no problems. It really depends on how your code is structured.
L.E:
if(isset($_POST['Submit'])){
$_SESSION['captcha_code'] = $_GET['captcha_code'];
$_SESSION['other_info'] = $_GET['other_info'];
// code for check server side validation
if(empty($_SESSION['captcha_code'] ) || strcasecmp($_SESSION['captcha_code'], $_POST['captcha_code']) != 0){
$msg='<span class="fail">Please try again.</span>';// Captcha verification is incorrect.
}else{
// Captcha verification is Correct. Final Code Execute here!
}
}
And in the view file, check the session variables, so the session vars are set if isset submit post.
Hope it helps!
Keep on coding!
Ares.

PHP:my session_variables shows when the page refresh

I know this is very simple thing but i am not aware of this. I have php code on same page for a signup form which have some session variables to be shown when any condition matches with the code.
The code structure is like this:
<?php
session_start();
if(isset($_POST['signup'])
{
if(condition)
{
$_SESSION['err1']="string";
}
else
{
$_SESSION['err2']="string";
}
}
?>
//HTML form
<?php if(isset($_SESSION['err1']) {?>
<li><?php echo $_SESSION['err1'];}?></li>
<?php if(isset($_SESSION['err2']) {?>
<li><?php echo $_SESSION['err2'];}?></li>
//rest of the form
I have more block of if-else in my code. Initially, when an condition is matched, the session message is shown. But as soon as the page refresh an another session message is shown along with previous session message.
Is this correct way of coding with forms? Because i want to show error messages inside the html form.
That's maybe because you do not empty your session variable.
Between 2 HTTP request, the session is kept on the server (juste reloading at each request).
So, if you are putting a message on $_SESSION['error1'] for the first call, it will show it. Then, on the second load, if you are putting a message on $_SESSION['error2'], you will also have the message of error1 because the session keep your data.
After showing the form, you should empty all your session messages
Simply unset your session variable after you echo.
<li><?php echo $_SESSION['err1'];} unset($_SESSION['err1']); ?></li>
This is really a bad example that use session to echo errors.
what i do many times at the starting of my php.
$errors = array(); // make a empty array errors before the conditional statements
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['Submit'])) {
//handle your POST variable
if(condition1){
$errors[] = "some error";
}
if(condition2) {
$errors[] = "some another error";
}
//more conditions
if (!empty($errors)) {
//process your form data if there is no errro
} else {
//display back your form along with Errors
if(isset($errors) && !empty($errors)) {
foreach($errors as $error) {
echo "<p class = 'error'>" . $error . "</p>";
}
}
<form action = "" method = "POST">
//your form elements
</form>
}
}
in first line of the php page, u can write
you can try any of the three lines between if condition
if(isset($_SESSION))
{
unset($_SESSION);
unregister($_SESSION['variable-name']) // try this also
session_destroy(); //try this also
}

Refresh button on Browser

I have a simple coding problem. I try to create a page with a textbox and a share button.
When the user clicks the share button the text in the textbox get inserted as string into the database table named "posts".
I use the following code.
<?php
if(isset($_POST['share']))
{
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res)
echo "<script type='text/javascript'>alert('Posted successfully')</script>";
else
echo "<script type='text/javascript'>alert('some error')</script>";
}
else
{
?>
<form action="<?php $_SERVER['PHP_SELF']?>" method="post">
Status : <input type = "text" name ="status">
<input type = "submit" name ="share">
</form>
<?php
}
This solution works fine but there is a problem when the user refreshes the page. The browser will show a message window asking for resend the information, which will submit the post to the table again. Then the same entry is in the table twice.
I want the user to stay on the same page after submitting. But a page refresh should not show the message window or send the information again.
Thanks in advance!
Redirect the user after he shares, use redirect
header('Location: whatever.php');
exit;
Use this :
<?php
if(isset($_POST['share'])) {
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res) {
?>
<script type='text/javascript'>alert('Posted successfully')</script>
<?php
header('Location: whatever.php');
exit;
} else {
?>
<script type='text/javascript'>alert('some error')</script>
<?php
header('Location: whatever.php');
exit;
}
}
?>
And btw better don't alert the users using javascript
AND DO USE BRACES AROUND IF ELSE
P.S : You Can Also Redirect An User Using JavaScript window.location
Header Reference
It's called "redirect-after-post": After you received the post request and did something useful with it, you redirect the user (usually) back to theire own post, or whatever.
You can try doing redirect just after your logic saving the post is done.
header("location: $my_page");
exit();
Set variable $your_page with the name of page which contains your code
$my_page = 'yourpage.php';
This should work:
$my_page = 'your_page.php'
if(isset($_POST['share']))
{
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res)
{
echo "<script type='text/javascript'>alert('Posted successfully')</script>";
header("location: $my_page");
exit();
}
else
{
echo "<script type='text/javascript'>alert('some error')</script>";
header("location: $my_page");
exit();
}
}
Right after you have finished inserting your query and everything, change to another page using:
<?php
header('Location: /path/to/yourotherpage.php');
exit();
?>
What this does, is it is a redirect to another page, which removes all POST data from the browser's 'memory' of the page.
On that page, you write something like 'Your stuff has been submitted and recorded', whatever you want, your choice.
If your user refreshes on that page, nothing will be inserted at all.
That should work.

Categories