I want to use two independent $_SESSIONs in a single PHP script.
I have attempted to verify that this is possible using the following code.
error_reporting(-1);
session_name('session_one');
session_start();
$_SESSION = array();
$_SESSION['session_one_var'] = 'test_one';
$output1 =
(
"session_id(): '" . session_id() . "'.<br/>\n" .
"session_name(): '" . session_name() . "'.<br/>\n" .
print_r($_SESSION, true)
);
session_write_close();
$_SESSION = array();
session_name('session_two');
session_start();
$_SESSION['session_two_var'] = 'test_two';
$output2 =
(
"session_id(): '" . session_id() . "'.<br/>\n" .
"session_name(): '" . session_name() . "'.<br/>\n" .
print_r($_SESSION, true)
);
session_write_close();
$_SESSION = array();
echo "$output1<br/>\n<br/>\n$output2";
Output:
session_id(): 'f19aecd8d3ce0c5d444456d2387c6e35'.
session_name(): 'session_one'.
Array ( [session_one_var] => test_one )
session_id(): 'f19aecd8d3ce0c5d444456d2387c6e35'.
session_name(): 'session_two'.
Array ( [session_one_var] => test_one [session_two_var] => test_two )
I expect the output to show that the session named 'session_one' contains array('session_one_var' => 'test_one') and the session named 'session_two' contains array('session_two_var' => 'test_two'). Instead, 'session_two' seems to be the same session as 'session_one'.
If I insert a line 'session_regenerate_id();' after the second 'session_start();' line, a different session id is reported for 'session_two', but the output is otherwise the same. See below.
session_id(): 'f19aecd8d3ce0c5d444456d2387c6e35'.
session_name(): 'session_one'.
Array ( [session_one_var] => test_one )
session_id(): '3bcc74a7bcbac30e680c5b94fadcede1'.
session_name(): 'session_two'.
Array ( [session_one_var] => test_one [session_two_var] => test_two )
What am I doing wrong?
I know similar questions have been asked on this forum before, here and here, but the answers offered so far have failed to enlighten me.
Any help will be much appreciated.
The session ID is read from a cookie when you run the first session_start() and sticks around even if you use session_write_close() (otherwise you wouldn't be able to call session_start() to reopen the same session)
I don't have PHP handy here to test this, but in theory, you can do session_id($_COOKIE['session_two']); before the second session_start() to switch to the correct ID.
I may have the cookie name wrong, though, so you may want to printr($_COOKIE); to see which cookies are set.
Edit: I forgot to mention: The session's cookie name is based on session_name, or at least it is if you only use a single session in a file.
According to the docs,
As of PHP 4.3.3, calling session_start() after the session was previously started will result in an error of level E_NOTICE. Also, the second session start will simply be ignored.
My interpretation is that no, you cannot use session_start() more than once per page, regardless of the name.
The regenerate_id() is changing the ID for the first session, and the second session_start is being ignored. That is why you see the behavior described.
I'd suggest letting us know what you're seeking to accomplish by doing this, and probably someone can recommend another way to do it.
My solution is
ob_start();
$name1 = 'session_1';
session_name($name1);
if(empty($_COOKIE[$name1]))
$sid = md5(microtime(true));
else
$sid = $_COOKIE[$name1];
session_id($sid);
session_start();
$_SESSION['count']++;
print_r($_SESSION);
session_write_close();
$_SESSION = array();
$name2 = 'session_2';
session_name($name2);
if(empty($_COOKIE[$name2]))
$sid2 = md5(microtime(true));
else
$sid2 = $_COOKIE[$name2];
session_id($sid2);
session_start();
$_SESSION['count'] = $_SESSION['count'] + 2;
print_r($_SESSION);
session_write_close();
ob_end_flush();
Related
I am storing product id-s in a cookie with php. (These are the favorite products on a webshop.)
I added many products as favorit, so my cookie looks like: 12,55,120,43
What i know, that the $_COOKIE[$cookie_name] is not an array. (checked with is_array function)
How can i delete a product id from that cookie? I send the id that i want to delete with ajax to this php file:
if(isset($_POST['id']))
{
$id = intval($_POST['id']);
$cookie_name = "kedvenc_termek";
if(isset($_COOKIE[$cookie_name]))
{
echo $_COOKIE[$cookie_name];
}
}
Unset your cookie:
unset($_COOKIE[$cookie_name]);
Set your cookie null:
setcookie($cookie_name, null, -1, '/');
This should delete or invalidate cookie
// set the expiration date to one hour ago
setcookie($cookie_name, " ", time() - 3600);
?>
If I understand you correct you have a string stored in the cookie like 12,55,120,43 and you want to remove one of them using $_POST['id']?
Since it's a string I believe the best option is preg_replace() this gives you the benefit over str_replace that you can create a pattern to remove.
$id = $_POST['id'];
$cookie_name = "kedvenc_termek";
$_COOKIE[$cookie_name] = preg_replace("/\b(" . preg_quote($id) . ",)\b/", "", $_COOKIE[$cookie_name]);
echo $_COOKIE[$cookie_name];
If you want to store the new string in the cookie then be sure to do that before you echo the value since you can't set a cookie after an output.
Example: https://3v4l.org/RQH4o
I don't know the problem.
The data is saved in the session but it only shows the last input.
$_SESSION['data'][] = $_POST;
$_SESSION['data']['lengtezijde'] = $_POST['lengtezijde'];
$_SESSION['data']['kleur'] = $_POST['kleur'];
$_SESSION['data']['hoogte'] = $_POST['hoogte'];
?><tr><?
?><th><?echo $_SESSION['data']['lengtezijde'];?></th><?
?><th><?echo $_SESSION['data']['kleur'];?></th><?
?><th><?echo $_SESSION['data']['hoogte'];?></th><?
?></tr><?
I have tried your code also and it work me. Since it is an array, you must loop trough it to display the values and that is why I think it is giving you only the last value.
//Declare your variables
$lengtezijde = $_POST['lengtezijde'];
$kleur = $_POST['kleur'];
$hoogte = $_POST['hoogte'];
//Store it in session
$_SESSION['data'] = array(
'lengtezijde' => $lengtezijde,
'kleur' => $kleur,
'hoogte' => $hoogte,
);
Now you can loop through your data and display it. I hope this helps.
if i understand what you looking for you must check your $_POST
i test this code
$_SESSION['data'][] = "Test";
$_SESSION['data']['lengtezijde'] = 'test1';
$_SESSION['data']['kleur'] = 'test2';
$_SESSION['data']['hoogte'] = 'test3';
echo $_SESSION['data']['hoogte'];
br();
echo $_SESSION['data']['kleur'];
br();
echo $_SESSION['data']['lengtezijde'];
result :
test2
test1
test3
Make sure you have mentioned session_start() in First Line of your code ,
session_start() too, before you assign values to $_SESSION
Rest of things seems ok in your code.
Never use below kind of assignment it will ruin your machine memory . If you run your script you will see that on each refresh of the page this size will be increasing. that is not advisable.
$_SESSION['data'][] = $_POST;
I have the following plugin: http://wordpress.org/support/plugin/wp-session-manager
I cannot work out how to use the session variables in WordPress. From what I understand by reading, this is how it should be used:
I have the following on page one (page 1):
global $wp_session;
$wp_session['loggedIn'] = 15;
echo $wp_session['loggedIn'];
On the first page, the session variable is working but on the second page, the session variable is not working.
Can anyone suggest me where I am going wrong?
Thanks.
Replace:
global $wp_session;
With:
$wp_session = WP_Session::get_instance();
Make sure you add $wp_session = WP_Session::get_instance(); before you try to echo the variable on page 2.
Add below code in function.php file
function register_my_session(){
if( ! session_id() ) {
session_start();
}
}
add_action('init', 'register_my_session');
After that you can store value in session variable like
$_SESSION['something'] = $xyz
Introducing WP_Session:
Example :
global $wp_session;
$wp_session['user_name'] = 'User Name'; // A string
$wp_session['user_contact'] = array( 'email' => 'user#name.com' );// An array
$wp_session['user_obj'] = new WP_User( 1 ); // An object
Wordpress session functions:
wp_session_cache_expire() – get the session expiration time
wp_session_commit() – write session data out to the transient
wp_session_decode() – load data into the session from a serialized string
wp_session_encode() – write session data out to a serialized string
wp_session_regenerate_id() – change the ID of the current session to a new, random one
wp_session_start() – start the session and load data based on the user’s cookie
wp_session_status() – check the status of the current session
wp_session_unset() – clear out all variables in the current session
wp_session_write_close() – write session data and end session.
For some reason, I can't seem to set a cookie in one of my PHP files. All of the code works fine, except it refuses to set the cookie. I've placed different versions of cookie setting with different arguments, but it doesn't seem to make a difference. On top of that, I can set a cookie using that same line of code in a separate PHP file in the same directory. I've tried placing setcookie() at different places and I still get the same result. Am I missing something?
<?php
$table_name="lfgs";
$name=$_POST['name'];
$event="[";
$level=$_POST['level'];
$comments=$_POST['comments'];
$hours=$_POST['hours']*60*60;
$minutes=$_POST['minutes']*60;
$time=$hours+$minutes+time();
setcookie("remember", $name, $time, 'www.domain.com', '/');
if(isset($_POST['event'])){
if (is_array($_POST['event'])) {
foreach($_POST['event'] as $value){
$event = $event . "\"" . $value . "\",";
}
} else {
$value = $_POST['event'];
$event = $event . "\"" . $value . "\"]";
}
} else {
$event = "";
}
if($event[strlen($event)-1] == ',') {
$event = substr_replace($event ,"]",-1);
}
$con=mysqli_connect("domain.com","username","password","database");
$req="INSERT INTO $table_name(name, event, level, comments, time) VALUES ('$name', '$event', '$level', '$comments', '$time')";
mysqli_query($con,$req);
mysqli_close($con);
foreach($_COOKIE as $c) {
echo $c . "<br />";
}
?>
Edit: This is ALL the code for the entire file.
According to the php reference, the correct way to use the setcookie function is
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
Didn't you swaped the $path and $domain argument?
Try
setcookie("remember", $name, $time, '/', 'www.domain.com');
try
setcookie("remember", $name, '/', $time);
I dont't understand what you want to do, but it'll not works the way you do.
Always remember: you work with PHP on the server side.
So to set a cookie an then to test if it worked, you need always tow steps (because you are on the server side):
The first step is to set the cookie.
And then during the next request you can check if ur cookie contains in the global $_COOKIE array. if yes then ok, if not then mybe the client/user donsen't allow to set cookies.
If you need to do it in "one step", you should use JavaScript. Something like that:
On submit the form, set the cookie and then propagate the submit action (send the data to the server). JQuery support a good solution to set and read cookies.
Are you sure the php interpreter doesn't send a char before the setcookie() call for some reason? The function send a HTTP header, so it have to appear before any printing on the page.
From my experience, if you have any session active on the page it will not allow you to create PHP cookies. Start a new blank page and test it that way.
You should be able to set a cookie on the new generic page. Then go back to your other page that has a session started on it. Echo the details of that set cookie in the session page and you will get the stored value, no problem.
You can call cookies but you can't seem to create them in an active session page. At least, I can't with my current system settings/config.
I want a link on my site to redirect like such...
http://mysite.com?url=1
$offer = $_GET['url'];
if ($offer == '1'){
header("Location: http://site1.com");
}
if ($offer == '2'){
header("Location: http://site2.com");
}
This is functional, but is there a better way to do this rather than having 50 if statements?
Assuming that your sites aren't really site1.com and site2.com (I'd be impressed if they were), this is probably a good way to approach the problem:
$sites = array(
'1' => 'http://www.google.com/',
'2' => 'http://www.bing.com/'
);
if (isset($sites[$_GET['url']])) {
header('Location: ' . $sites[$_GET['url']]);
die();
} else {
die('Sorry, this does not exist.');
}
This would of course also allow you to do things such as accepting non-numeric values in ?url=.
Store your identifiers and URLs in an associative array:
$list = array(
'1' => 'http://site1.com',
'2' => 'http://site2.com'
);
Then look for the value that matches your key:
if (array_key_exists($_GET['url'], $list)) {
header('Location: ' . $list[$_GET['url']]);
} else {
// bad key
}
header("Location: http://site{$url}.com"); //success!!
or
header("Location: http://site" . $url . ".com"); //success!!
But please do not rely on user (client) input like that.
Validate it a little before making the header or you will have issues...
As long as they're in this format you can use:
$offer = $_GET['url'];
header("Location: http://site".$offer.".com");
Might want to check the $offer as an integer $offer = intval($offer)
Use a table on db, search for id and use a single header() or an array $redirect[option] header("Location: "$redirect[option]);
Instead of passing a number, try passing the actual url. When you initially place the url on the link, make sure you encode it, and when you try to read it back, make sure you decode it.
$offer = urldecode($_GET['url']);
header("Location: ". $url);
You can also store the mapping on number and url on a database, and then just query for the url where number matches what you send.
Another alternative would be to have an array where you have that mapping.
<?php
$array = array(
1 => "http://www.google.com",
2 => "http://www.yahoo.com",
3 => "http://www.msn.com",
4 => "http://www.reddit.com"
);
$offer = $_GET['url'];
header("Location: " . $array[$offer]);
?>
You can have an array of possible URL's and you can check the value of $_GET['url'] against these values, then redirect the user accodingly. This can be a manually written array inside this PHP file or an array the values of which have been gathered from a database.
You can also use the if/else consitions or a switch condition but that will make your code longer. It's not a bad option although it's less practical.
Also, if you have any other code in this specific page, make sure you have exit; after the header() function to prevent it from executing before redirection.
$urls = array(
1 => 'www.someurl.com',
2 => 'www.someotherurl.com'
);
$key = #trim($_GET['url']);
if (!empty($key) && isset($urls[$key]))
header('Location: http://' . $urls[$key]);
else
// fallback
header('Location: http://www.defaulturl.com');
exit;