PHP - Destroy Session?
Similar TutorialsCurrently 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. Hi 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); ?> Hello, How do I get a user's session destroyed when he closes his browser? Thanks in advance 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'); } 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"]; } ?> 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); } 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="" />
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); 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! in this page http://maximaart.com/newscp/ i have this problem Code: [Select] Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/maximasy/public_html/newscp/index.php:1) in /home/maximasy/public_html/newscp/index.php on line 2 my source code is <?php session_start(); include_once("config.php"); include_once("functions.php"); $errorMessage = ''; if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) { if ($_POST['txtUserId'] === "$user" && $_POST['txtPassword'] === "$pass") { // the user id and password match, $_SESSION['basic_is_logged_in'] = true; require("main.php"); exit;?> I am having trouble resolving an error. Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/s519970/public_html/header.php:27) in /home/s519970/public_html/admin/login.php on line 2 What I can gather is I can't use "header (Location: 'admin.php')" after i've used session_start(). I have tried to replace the header (Location: 'admin.php') with this: echo "<script>document.location.href='admin.php'</script>"; echo "<script>'Content-type: application/octet-stream'</script>"; I've been trying to read up on solutions but haven't been able to get it sorted. If anyone can offer some advice that would be greatly appreciated as im new to php. Code: [Select] <?php session_start(); if(isset($_SESSION['user'])) echo "<script>document.location.href='admin.php'</script>"; echo "<script>'Content-type: application/octet-stream'</script>"; ?> <div id="loginform"> <form action="dologin.php" method="post"> <table> <tr> <td><span>Username:</span></td> <td><input type="text" name="username" /></td> </tr> <tr> <td><span>Password:</span></td> <td><input type="password" name="password" /></td> </tr> <tr> <td colspan="2" align="right"><input type="submit" name="login" value="Login" /></td> </tr> </table> </form> </div> I have tried using require_once('yourpage.php'); before my <head></head> tags in the header document where I've specified the html information but this doesn't seem to work. I've been advised to use ob_start("ob_gzhandler"); but I am not sure how to implement this. Any advice is greatly appreciated! 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 hi everyone. i'm wondering what the best way is to create a session variable and pass it to an iframe. i need to do something along these lines, but it doesn't seem to pass the ID. Any hints on how i should accomplish this? Code: [Select] session_start(); $_SESSION['ID']=$_GET['ID']; // id from previous page $ID=session_id(); <iframe src="iframepage.php?ID=<?php echo $ID; ?>" style="width:680px; height:200px;" noresize="noresize" frameborder="0" border="0" scrolling="Yes" allowtransparency="true" /> </iframe> I'm making a simple login system with MySQL and PHP (very simple, I'm just starting with PHP). The MySQL portion is done, but I need to ensure only people who are logged in can see certain content. To check if people are logged in, my website checks that they have the $_SESSION['user'] variable set. If it is set, then it lets them continue through the website, if not, it tells them to login. Is that enough security, or can people simply inject a session cookie into their browser to spoof that they are logged in? My idea was to generate a session key cookie when they login (just a random string of letters and numbers) and store that in the database, then on every page, check to make sure their session key is the same thing that's in the database. Is this necessary? It seems expensive. Just curious how other people feel about this. I am working on an application where a lot of info is pulled from MySQL and needed on multiple pages.
Would it make more sense to...
1. Pull all data ONCE and store it in SESSION variables to use on other pages
2. Pull the data from the database on each new page that needs it
I assume the preferred method is #1, but maybe there is some downside to using SESSION variables "too much"?
Side question that's kind of related: As far as URLs, is it preferable to have data stored in them (i.e. domain.com/somepage.php?somedata=something&otherdata=thisdata) or use SESSION variables to store that data so the URLs can stay general/clean (i.e. domain.com/somepage.php)?
Both are probably loaded questions but any possible insight would be appreciated.
Thanks!
Greg
Edited by galvin, 04 November 2014 - 10:30 AM. Evening! I've been iffing and ahhing over this and well im not too sure, hence the post. Code: [Select] // Redirects if there is no session id selected and echos the error on the previous page if(!isset($_GET['get']) || ($_GET['getget'])){ header("Location: #.php?error"); } So it should simply check if get is set if it isnt then see if getget is set? If not redirect and show the error. Now ive tried it and even when get/getget is set it still redirects, probably something silly. Care to share anyone? Harry. I am having trouble calling the session var "email" from the landing page. Here is the code that I am using. I am not even sure the session "email" is starting or registering. Code: [Select] $referer = $_SERVER['HTTP_REFERER']; $email = $_POST['email']; $sql="SELECT * FROM users WHERE email='$email' "; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $email, table row count must be 1 row if($count==1){ // Session Register email session_start(); $_SESSION['email'] = $email; header("location:".$referer2." "); exit(); } Hi I am looking for help with a working script to input multiple lines of data , but i am looking for each line of data to have the $_SESSION[userid] entered into each line, ie into the table $_SESSION[userid], name, surname, age Many Thanks <? include "include/session.php"; include "include/z_db.php"; // check the login details of the user and stop execution if not logged in require "check.php"; // If member has logged in then below script will be execuated. // let us collect all data of the member $row=mysql_fetch_object(mysql_query("select * from plus_signup where userid='$_SESSION[userid]'")); if(isset($_POST['submit'])) { foreach($_POST['person'] as $person) { $name= mysql_real_escape_string($person['name']); $surname= mysql_real_escape_string($person['surname']); $age= mysql_real_escape_string($person['age']); $values[] = "('$name', '$surname', '$age')"; } $query = "INSERT INTO plus_signup (name,surname,age) VALUES " . implode(', ', $values); $result = mysql_query($query) or die("Error!<br />Query: $query<br />Error: " . mysql_error()); } ?> <form method="POST" action='multi.php' name=""> <table> <tr> <td>Name<input type="text" name="person[0][name]"></td> <td>surname<input type="text" name="person[0][surname]"></td> <td>age<input type="text" name="person[0][age]"></td> </tr> <tr> <td>name<input type="text" name="person[1][name]"></td> <td>surname<input type="text" name="person[1][surname]"></td> <td>age<input type="text" name="person[1][age]"></td> </tr> <tr> <td>name<input type="text" name="person[2][name]"></td> <td>surname<input type="text" name="person[2][surname]"></td> <td>age<input type="text" name="person[2][age]"></td> </tr> </table> <td><p> <input type="submit" name="submit" value="add"> </p> <p> </p>| <a href=update-profile.php>back</a>| </form> <? require "bottom.php"; ?> <center><br>| <a href=update-profile.php>back</a>|<br></center> </body> </html> Why is my SESSION not getting set in the code below?! Code: [Select] <?php // Initialize a session. session_start(); // Initialize Logged-In Status. $_SESSION['loggedIn'] = FALSE; // Display Logged-In Status. echo '<p>$_SESSION[\'loggedIn\'] = ' . $_SESSION['loggedIn'] . '</p>'; exit(); When I run this I get... $_SESSION['loggedIn'] = Debbie |