PHP - How To Destroy Session Automatically After Defined Time?
As my title said the question, i want to destroy my session after a particular time if user is being ideal..
currently i am using this code to define my session: Code: [Select] session_start(); // Check, if username session is NOT set then this page will jump to login page if (!isset($_SESSION['myusername'])) { header('Location: admin.php'); } Similar TutorialsHi all, My session is not destroy even after I have click 'log out' The user will only log out only when I have closed the browser. May I know what could have caused the problem? Below is my code My admin.php page Code: [Select] <?php // For logging out if (isset($_SESSION['username'])) { echo '<a href="admin_logout.php">Log Out (' . $_SESSION['username'] . ')</a>'; // Connect to the database $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); // Retrieve the user data from MySQL $query = "SELECT tutor_id, name FROM tutor_profile ORDER BY name ASC"; $data = mysqli_query($dbc, $query); // Loop through the array of user data, formatting it as HTML echo '<h4>Latest members:</h4>'; echo '<table>'; while ($row = mysqli_fetch_array($data)) { echo '<td><a href="viewprofile.php?tutor_id=' . $row['tutor_id'] . '">' . $row['name'] . '</a></td></tr>'; } echo '</table>'; mysqli_close($dbc); } else { echo '<a href="admin_login.php">Log In</a>'; } ?> My logout.php page Code: [Select] <?php // If the user is logged in, delete the session vars to log them out session_start(); if (isset($_SESSION['admin_id'])) { // Delete the session vars by clearing the $_SESSION array $_SESSION = array(); // Delete the session cookie by setting its expiration to an hour ago (3600) if (isset($_COOKIE[session_name()])) { setcookie(session_name(), '', time() - 3600); } // Destroy the session session_destroy(); } // Delete the user ID and username cookies by setting their expirations to an hour ago (3600) setcookie('admin_id', '', time() - 3600); setcookie('username', '', time() - 3600); // Redirect to the home page $home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/admin_login.php'; header('Location: ' . $home_url); ?> Currently I have a Javascript button to close a tab window which is great, but annoying problem is when the user opens up the section again all the previous session errors are there. I have tried the following, which didnt work; [ function destroy() { window.open('destroyCode.php'); } <a href='javascript:window.close()' onclick="destroy()" ><img class='close' src='images/close.jpg' alt='Close Window' /></a> ] [ <?php session_unregister("add_customer_errors"); session_unregister("add_customer_form"); session_destroy(); ?> <html> <body onload="javascript:window.close()"> </body> </html> ] Any ideas of how to do it? I have got the session being unregistered if the data is correct and saved to the database. But what is the user wants to start and then changes there mind. Hello, How do I get a user's session destroyed when he closes his browser? Thanks in advance what would be the best way to automate/force session destroy and cookie erase i have a facebook iframe, with facebook login which gets the activation token now the user is not logged out from the login script after he logs out of facebook. any ideas how to force cookie timeout without a logout button? im playing with Code: [Select] <?php session_start(); //Global User Object Var //loggedInUser can be used globally if constructed if (isset($_SESSION['userCakeUser'])) { $obj = casttoclass('stdClass', $_SESSION['userCakeUser']); $_SESSION['userCakeUser'] = $obj; $_SESSION['start'] = time(); // taking now logged in time $_SESSION['expire'] = $_SESSION['start'] + (1 * 60) ; // ending a session in 1 minute } if(isset($_SESSION["userCakeUser"]) && is_object($_SESSION["userCakeUser"])) { $loggedInUser = $_SESSION["userCakeUser"]; } ?> Let's say I am buying a share for $10. If I sell the share on the same day BEFORE 3:30PM, it will be sold for $10, but if I keep the share past 3:30PM, I want the code to automatically add $1 (Taxes and such) once in the the price of the share in database, after that no matter how many days pass by, the price will remain the same.
I've thought about CRON jobs, but I have no idea how to make/use them or set them up.
Any direction or help is appreciated.
Hi, I have a project where i want to send the sms to the customers at the particular time calling from the database, how to do these in php? Thanks, Is it possible to set a certain session to time out after say 2 minutes. I want to lock a person from seeing a page for 2 minutes then destroy the session yet keep the primary session and still keep dpoing what they were doing? Just curious. Thanks, Hello guys, I am new to PHP. I need some help. I am trying to build a web app, in which I have login functionality. I want to keep the logged in user session active for around 3-4 months. But in my case as soon as I close the browser, session data is lost and I need to login again. Can anyone help me with this. how can i set a session to expire after a set amount of time, say 1 hour. i'm using the following code to create my session, but i dont know what i need to add to make it expire $_SESSION['pageviewsid'.$id] = $new; $new is the result from a calculation and $id is the page id from the URL using $_GET Hello everyone, I've searched these forums for a while now trying to resolve a problem that I have with my sessions timing out before I would like them to, but I've only gotten confused about it. I've read about changing some settings or adding code in my php.ini file but I have no idea what I'm doing when it comes to that. I'm starting the session simply by having session_start(); at the top of each of my pages. I'm including a copy of my entire php.ini file here so that you can see what I have already. Can someone please help me to figure out what I would need to do to make my sessions last at least 8 hours? Thanks in advance. Here's my php.ini file: Code: [Select] register_globals = off allow_url_fopen = off expose_php = Off max_input_time = 60 variables_order = "EGPCS" extension_dir = ./ upload_tmp_dir = /tmp precision = 12 SMTP = relay-hosting.secureserver.net url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=,fieldset=" ; Only uncomment zend optimizer lines if your application requires Zend Optimizer support ;[Zend] ;zend_optimizer.optimization_level=15 ;zend_extension_manager.optimizer=/usr/local/Zend/lib/Optimizer-3.3.3 ;zend_extension_manager.optimizer_ts=/usr/local/Zend/lib/Optimizer_TS-3.3.3 ;zend_extension=/usr/local/Zend/lib/Optimizer-3.3.3/ZendExtensionManager.so ;zend_extension_ts=/usr/local/Zend/lib/Optimizer_TS-3.3.3/ZendExtensionManager_TS.so ; -- Be very careful to not to disable a function which might be needed! ; -- Uncomment the following lines to increase the security of your PHP site. ;disable_functions = "highlight_file,ini_alter,ini_restore,openlog,passthru, ; phpinfo, exec, system, dl, fsockopen, set_time_limit, ; popen, proc_open, proc_nice,shell_exec,show_source,symlink" Hi I am developing a e-commerce website. The user logs in and buy a product when he checkout the page will redirect to the payment gateway. After the payment is completed it will return back to my website. This is ok. But when it is returning back the session maintained in my website get lost. This happen only for the first time. If the user again logged in and checkout the process works good and the session is maintaining. Why does the session lost for first time. I used session_start() in all the pages.. I cannot find the solutions. Kindly help.. Regards P.Balakrishnan Hi all, I'm trying to increase the server default php session timeout from 1hour to 3hours. I don't have access to my php.ini but can use .htaccess. Is the following the correct way to do this? in the .htaccess add the line: php_value session.gc_maxlifetime 10800 Or would I be better off including the following after every session start() on everypage: Code: [Select] ini_set("session.gc_maxlifetime","10800"); thanks! I have the following session timeout code which should redirect users of a website to a page (session_expired.php) which prints out a message telling the user that his session has expired. I include this code at the top of every page in the website, that requires user authentication. Code: [Select] <?php //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) { // last request was more than 30 minates ago session_destroy(); // destroy session data in storage session_unset(); // unset $_SESSION variable for the runtime header("location: session_expired.php"); } $_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp ?> The session_expired.php page which I will include below, has a login link, which takes the user to a login page (access_denied.php) Code: [Select] <?php //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //Set the page title before the header file $title = 'Session Expired'; require ('header.php'); //need the header ?> <div id="content" class=""> <div id="left_content" class=""> </div> <!--closes left content--> <div id="right_content" class=""> <div id= "right_content_inner_border"> <h5 style ="position:relative;left:660px;top:1px;"> <a style="text-decoration:none" href="access_denied.php">[Login]</a> </h5> <h3 style ="position:relative;left:110px;top:100px; font-color:blue;"> You Session Expired Due to Inactivity! </h3> </div> <!--closes right content inner border--> </div> <!--closes right content--> </div> <!--closes content--> <?php require ('footer.php'); //need the footer ?> Now here lies the problem. When i set the session timeout to say 60 seconds to test the code, everything seems to work perfectly. The authenticated page gets redirected to session_expired.php after 1 minute and when the user clicks on the login link, he is taken back to the login page(access_denied.php). However, when I replace the time with 1800 seconds, the page notice that when I leave the page idle for JUST about 5 minutes, it gets redirected NOT even to the expected session_expired.php page but strangely, directly to the login page(access_denied.php). What could be going wrong here? Any hint is appreciated. Hi guys, I'm having a problem with destroying Cookies in IE8 (maybe other versions of IE but this is the one I'm testing on). I am checking to see if the referrer of the site is not itself, and if not, delete all cookies with the cookie domain. if ($_COOKIE['exp_last_visit'] < mktime("23", "59", "59", "12", "03", "2010")) { if (!strstr($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'])) { foreach ($_COOKIE as $key => $value) { setcookie($key, $value, time()-10000, "/", ".domain.com"); } } } This works in Chrome and FF, but of course, not IE8. If anyone could shed any light on this I'd be really grateful! hey guys im having a spot of botter unsetting, destroying a session which has been given a cookie lifetime...i know it is possible to destroy all sessions using session_destroy() but i want to destory a particials session and not all of them. here is my method if anyone can give some advice on how i could do this please...thank you
public function destroy($name = null) { $namespace = $this->_namespace; $sessions = $_SESSION[$namespace]; if ($name == null) { foreach ($sessions as $name => $value) { $session = $sessions[$name]; unset($sesion); if (isset($session)) { // sessions with lifetime ini_set('session.cookie_lifetime', 0); ini_set('session.gc_max_lifetime', 0); ini_set('session.gc_probability', 1); ini_set('session.gc_divisor', 1); $session; } } } else { unset($sessions[$name]); } session_regenerate_id(true); } My code below, i already imagedestroy($newimage)... but i'm not sure if i should be destroying $oldimg as well? Any thoughts? $newimg = imagecreatetruecolor($sizeA,$sizeA) or die('Problem In Creating image'); $background = imagecolorallocate($newimg, 255, 255, 255); imagefilledrectangle($newimg, 0, 0, $sizeA, $sizeA, $background); $oldimg = imagecreatefromjpeg($source)or die('Problem In opening Source Image'); imagecopyresampled($newimg,$oldimg,0,$move,0,0,$sizeA,$new_height,ImageSX($oldimg),ImageSY($oldimg)) or die('Problem In resizing'); imagejpeg($newimg,$s1DIR,90) or die('Problem In saving'); imagedestroy($newimg); Hey guy's i have a script i did a few months ago and now noticed that it is doing its job but keeps the old file ..so i got the image a few times but on a different angle...
how can i optimize this code to delete the old image when doing the rotation?
<?php session_start(); include_once 'dbconnect.php'; if (!isset($_SESSION['userSession'])) { header("Location: index.php"); } $degrees = -270; $path = $_GET['Folder']; $file =$_GET['Pic']; $fileid =$_GET['id']; $image = $path.'/'.$file; $imageN = $path.'/New_'.$file; //load the image $source = imagecreatefromjpeg($image); //rotate the image $rotate = imagerotate($source, $degrees, 0); $NewImg='New_'.$file ; //set the Content type //header('Content-type: image/jpeg'); //display the rotated image on the browser //imagejpeg($rotate); imagejpeg($rotate,$imageN,100); //free the memory imagedestroy($source); imagedestroy($rotate); $sql = "UPDATE Coupon_list SET product_image_thumb = '$NewImg' WHERE id = '$fileid'"; if (mysqli_query($DBcon, $sql)) { echo "Rotation ok"; echo('<script language="Javascript">opener.window.location.reload(false); window.close();</script>'); } else { echo "Error Rotating: " . mysqli_error($DBcon); } mysqli_close($DBcon); ?> <img src="gears.gif" alt="" />
I am using a WordPress theme that uses some of its own functions besides WP functions. Let me make clear from the start that when I say "Multiple Checkboxes" in the paragraphs below I am NOT talking about checkboxes that each hold a single value. I am talking about one Checkbox field that allows multiple values to be selected and puts those values into an array with one Name value and stores the output in a string in a single mysql table field. Right up front, what I need during the Edit Ad functions is the inbuilt function that will Delete the previous Array of values in any multiple checkbox when the ad is updated. Right now updating the ad works for every situation except NO values selected or for Unchecking all previously selected values in a Multiple Checkbox. If I have, for example, 4 checkboxes selected and unselect all of them before submitting the edited ad it will return the last saved array of values but not an Empty array with no checkboxes selected. This theme has a Form Builder with a Custom fields builder used by the admin to create forms for a classified ads website. According to which category of ad the Ad creation procedure will show different forms, with different fields. I had to manually create the capability to generate multiple checkboxes...so that the different multiple checkboxes when selected and updated to the mysql table might hold a variety of values in a comma-delimited array. That works fine. When the Ad is edited on its own page, (outside of the Wordpress admin dashboard) the problem is that if a user would uncheck all checkboxes in a particular multiple checkbox then the unselected state does not overwrite the previous array of values. What returns after editing is the previous selected values. I have tried jquery functions but none of them are working the way I had hoped. so one type of checkbox might have a hypothetical value like this "name="cp_checkbox_help[]" and if three options are selected then on submit the value could be--- name="cp_checkbox_help[Sunday,Monday,Tuesday]" I use implode and explode to store the array as comma separated and retrieve the array for editing or display. I guess I need to create a Null or empty value as a default that only changes when selections are made. But, since I use implode and explode to make the array "pretty" I don't know if simply specifying nothing will erase a whole array on update. Here is some of the code used to see how I get what I get-- This displays the checkboxes that I create and name and fill with different values-- case 'checkbox': ?> <?php $options = explode(',', $result->field_values); echo '<div id="checkboxes"><table width="100%" border="0" cellspacing="0" cellpadding="5"> <tr> <th colspan="2" scope="col">' . $result->field_label. '</th> </tr>'; $myvals= explode(',', $post_meta_val); foreach ($options as $option) { { ?> <tr> <td width="4%"><input style="display:inline-block; float:left;" type="<?php echo $result->field_type; ?>" name="<?php echo $result->field_name; ?>[]" class="checkbox<?php if($result->field_req) echo ' required'?>" id="<?php echo $field_label; ?>" value="<?php echo $option; ?>" <?php foreach ($myvals as $myval) { if (in_array($myval, array($option), true)) {echo 'checked="yes"';}}?>/></td> <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" ><?php echo $option . '</td> </tr> ' ?> <?php } } echo ' </tr> </table></div><div class="clr"></div>'; break; Following is the main part of the code that updates the Ad form-- // update the ad and return the ad id $post_id = wp_update_post($update_ad); if($post_id) { // now update all the custom fields foreach($_POST as $meta_key => $meta_value) { if (cp_str_starts_with($meta_key, 'cp_')) if (cp_str_starts_with($meta_key, 'cp_checkbox_charley')) $meta_value= implode(',', $_POST['cp_checkbox_charley']); if (cp_str_starts_with($meta_key, 'cp_checkbox_help')) $meta_value = implode(',', $_POST['cp_checkbox_help']); if (cp_str_starts_with($meta_key, 'cp_checkbox_hello')) $meta_value= implode(',', $_POST['cp_checkbox_hello']); //echo $meta_key . ' <--metakey <br/>' . $meta_value . ' <--metavalue<br/><br/>'; // for debugging update_post_meta($post_id, $meta_key, $meta_value); } $errmsg = '<div class="box-yellow"><b>' . __('Your ad has been successfully updated.','cp') . '</b> <a href="' . CP_DASHBOARD_URL . '">' . __('Return to my dashboard','cp') . '</a></div>'; } else { // the ad wasn't updated so throw an error $errmsg = '<div class="box-red"><b>' . __('There was an error trying to update your ad.','cp') . '</b></div>'; } return $errmsg; } Back on the Edit Ad page this is the Submit <p class="submit center"> <input type="button" class="btn_orange" onclick="window.location.href='<?php echo CP_DASHBOARD_URL ?>'" value="<?php _e('Cancel', 'cp')?>" /> <input type="submit" class="btn_orange" value="<?php _e('Update Ad »','cp') ?>" name="submit" /> I have a feeling what I need is just a couple of lines to detect no posted values and then... but if one checkbox array has 6 values in it and another checkbox array has only 3 values, for example, do I need to count each specific checkbox for number of values and then overwrite or will one function completely delete the previous array and its commas? I would really appreciate some expert assistance here! I am trying to create an index page which contains registration and login field the problem that i get is on successful login a warning is displayed session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\xampp\htdocs\Eventz.com\index.php:116) in C:\xampp\htdocs\Eventz.com\index.php on line 235 This is the login part of my index.php this tag is inside an html table below the login form I also have a registration form and its php code above the login form Code: [Select] <?php if (isset($_REQUEST['pass'])) { $id=$_POST['id']; $pass=$_POST['pass']; $conn =mysql_connect("localhost","root",""); if (!$conn) { die('Could not connect: ' . mysql_error()); } /* checking connection....success! */ $e=mysql_select_db('test', $conn); if(!$e) { die(''.mysql_error()); } else { echo 'database selected successfully'; } if (isset($_REQUEST['id']) || (isset($_REQUEST['pass']))) { if($_REQUEST['id'] == "" || $_REQUEST['pass']=="") { echo "login fields cannot be empty"; } else { $sql=mysql_query("Select email,password from login where email='$id' AND password='$pass'"); $count=mysql_num_rows($sql); if($count==1) /* $count checks if username and password are in same row */ { session_start(); $_SESSION['id']=$id; echo "</br>Login Successful</br>"; } else { echo "</br>invalid</br>"; echo "please try to login again</br>"; } } } } ?> Any help or suggestion would be appreciated |