I'm Trying To Use A Textbox Value As A Session Variable
Solution 1:
When you are assigning the _SESSION url, you will need to use the posted variable to assign the string.
$_SESSION['url'] = $_GET['url'];
To do the opposite, and have the textbox show the value of the session, you would:
echo"<input type='text' id='starurl' value='" . htmlspecialchars($_SESSION['url']) . "'/>";
It is important to note that if you want the text box to actually do something, you will need to have the input box wrapped around a form tag.
The <form>
tag tells the browser where the form starts and ends. You can add all kinds of HTML tags between the <form>
and </form>
tags. (thanks echoecho!)
If you are working RESTfully, GET should be used for requests where you are only getting data, and POST should be used for requests where you are making something happen.
Some examples:
- GET the page showing a particular SO question
- POST a comment
- Click the "Add to cart" button and send a POST request.
The form & PHP file would look like this:
<?php
session_start();
if (isset($_POST['url']) {
$_SESSION['url'] = $_POST['url'];
}
echo'<form action="POST" method="?">';
echo"<input type='text' id='starurl' value='" . htmlspecialchars($_SESSION['url']) . "'/>";
echo'</form>';
You will notice when the form is updated, the session updates too. When you close your browser and open it again, you will see you old contents on the input box. (Press "enter" to save the input box without a submit button).
Solution 2:
Simply use this one
//page1.php
<form action="page2.php" method="post">
<inputtype="text" name="session_value">
<inputtype="submit" name="set_session" value="Set Session">
</from>
//page2.php
<?phpif(isset($_POST['set_session'])){
session_start();
$_SESSION['url'] = $_POST['session_value'];
}
?>
Solution 3:
For getting the value from your textbox, first modify your HTML as :
<input type='text' id='starurl' name='url' value=''/>
The textbox needs a name
attribute which is used by the $_POST
, $_GET
or $_REQUEST
superglobals.
Then depending upon your form submission method (GET or POST) :
$_SESSION['url'] = $_GET['url'] // Default method for form submission$_SESSION['url'] = $_POST['url'] // For <form method="post">$_SESSION['url'] = $_REQUEST['url'] // Works for both
EDIT : Since you are using a button onclick event to set the session variable, you can use this (assuming you are using jQuery) :
Javascript:
$('button').click(function(){
var url = $('#starurl').val();
$('#sessionURLDiv').load('save_session_url.php?url='+url);
});
PHP: save_session_url.php :
<?php
session_start();
if ( isset ( $_GET['url'] ) ) {
$_SESSION['url'] = $_GET['url'];
}
?>
HTML : Just add this div anywhere in the page.
<div id = "sessionURLDiv"></div>
I hope this helps.
Post a Comment for "I'm Trying To Use A Textbox Value As A Session Variable"