PHP - Reset Session Timeout Without Submitting Form
I have a form that is very long. Sometimes the logged-in user will spend over 20 minutes on this screen and then when they hit submit, the session has already expired and they are redirected to the login screen and anything on that form is lost.
Is there a way to reset the session timeout to zero everytime they either click the screen with the mouse, or type something into a form field (without submitting the form)? Not sure if this would only work with javascript or if there is php code that I would put in the beginning of the action.php that looks for whether the session has timed out and if so, add the form contents to the database first before logging them out? A php solution like that would be preferable to a javascript one. But also if the sessiopn has already expired, then the action.php script would be less secure if I put the code there because then anyone not logged in could use that page so that's probably not the solution. Best solution would be to reset the session timer whenever they click ont he screen or start typing in the form. Similar TutorialsI am trying to learn how to program in PHP. For a long time i was using WAMP and my localhost. When i ran into trouble i searched the web, watched videos and eventually find a solution.
Trying to upload my scripts into a shared hosting web server i had some difficulties in basic things, like using $_SESSION superglobal variable.
What i want to do is to use a hidden field with a value inside a form, and after submitting the form, to compare the $_SESSION variable to the $_POST variable in order to check for CSRF.
<?php //call all custom functions require_once('Custom_Functions/functions.php'); //session must be send before HTML headers secure_session_start(); ?> <!DOCTYPE html> <html lang="en"> <body> <?php if(isset($_POST['submit'])) { $postvalue = $_POST['input1']; $sessionvalue = $_SESSION['hashed_token']; echo '<br />==========================<br />'; echo '<br />AFTER PRESSING SUBMIT<br />'; echo '<br />==========================<br />'; echo 'Value of $_POST["hashed_token"] = '.$postvalue.'<br />'; echo 'Value of $_SESSION["hashed_token"] = '.$sessionvalue.'<br />'; } $hashed_token = hash('sha256', uniqid(mt_rand(), TRUE)); $_SESSION['hashed_token'] = $hashed_token; echo '<br />==========================<br />'; echo '<br />BEFORE PRESSING SUBMIT<br />'; echo '<br />==========================<br />'; echo '<br />Value of $_SESSION["hashed_token"] = '.$hashed_token.'<br />'; ?> <form action="" method="POST"> <input type="hidden" name="input1" value="<?php echo $hashed_token; ?>" /> <p><input type="submit" name="submit" /></p> </form> </body> </html>In this script i have 1 custom function: a) secure_session_start() function secure_session_start(){ //Set a custom session name $session_name = 'TESTSESSID'; ini_set('session.use_only_cookies', 1); ini_set('session.entropy_file', '/dev/urandom'); if (in_array('sha512', hash_algos())) { ini_set('session.hash_function', 'sha256'); } ini_set('session.use_trans_sid', 0); ini_set('session.hash_bits_per_character', 5); ini_set('session.cookie_secure', 1); $secure = TRUE; $httponly = TRUE; $cookieParams = session_get_cookie_params(); session_set_cookie_params($cookieParams['lifetime'], $cookieParams['path'], $cookieParams['domain'], $secure, $httponly); session_name($session_name); ini_set("session.save_path", "/home/SESSIONS"); session_start(); }The procedure goes as follows: FIRST COMMUNICATION WITH THE SERVER: The superglobal variable $_SESSION['hashed_token'] is assigned the random hash value, which is then passed to the hidden input field. I then echo it. RESULT: ========================== BEFORE PRESSING SUBMIT ========================== Value of $_SESSION["hashed_token"] = 93438a1b9b72085ce9430291acebdc4cfdee9d001b91a26207aebc22e04689fc SECOND COMMUNICATION WITH THE SERVER: The user press the submit button, the script then checks if the submit button is pressed, and gets in the if statement(because is TRUE). Then i collect the $_POST and $_SESSION values and echo them. New random hash is assigned to the $_SESSION superglobal variable. RESULT: ========================== AFTER PRESSING SUBMIT ========================== Value of $_POST["hashed_token"] = 93438a1b9b72085ce9430291acebdc4cfdee9d001b91a26207aebc22e04689fc Value of $_SESSION["hashed_token"] = 8f176aeb3a09a1b30e0ea862c78625d7c11743da933d366cface3fa238388e57 ========================== BEFORE PRESSING SUBMIT ========================== Value of $_SESSION["hashed_token"] = c3442382b146f03394ad86911018247c57fa19d4a653d0bf6bb9bc7506e88ca0 For me this is very weird. The random hash is assigned to the $_SESSION variable, but when i try to call it after the submit is pressed its giving me a complete different value. If i remove the function secure_session_start() and just use session_start() it works: RESULT (using session_start() ) ========================== AFTER PRESSING SUBMIT ========================== Value of $_POST["hashed_token"] = a5eaaaa38c428af623a599e664ea9c64a2ff0674e18e9250c54e52bbc586b614 Value of $_SESSION["hashed_token"] = a5eaaaa38c428af623a599e664ea9c64a2ff0674e18e9250c54e52bbc586b614 ========================== BEFORE PRESSING SUBMIT ========================== Value of $_SESSION["hashed_token"] = e2d4acc239a747217860d71a80553abd41142dbeb8f6fafab511caff8a081fc4 Any ideas why this is happening? The problem is inside the secure_session_start() function but i cant find out why. Also, when i use the secure_session_start() function and more specifically the ini_set("session.save_path", "/home/SESSIONS"); i am forcing the session to be stored inside the /home/SESSIONS folder. But when i only use the session_start() the session i still gets stored inside that path. I checked my .htaccess and there is nothing storing the sessions in that folder. Why is that? One last thing: When using FIREBUG-->Cookies is see 2 names: the custom one (TESTSESSID) and PHPSESSID(which is the default). Shouldnt i only see the custom session name only? Thanks in advance. Hi Im trying to keep a session open once a user logs in for a large amount of time ( months) I have set the following in a .htaccess file php_value session.cookie_lifetime 99999999 php_value session.gc_maxlifetime 99999999 But i still lose the session and get logged out after 10 minutes or so i have created a phpinfo page and see that for these values the following is set session.cookie_lifetime 99999999( local) 0 (global) session.gc_maxlifetime 99999999 ( local) 1440 (global) What is the difference between the local and global? Any other ides why might session keeps timing out after 10 mins or so of inactivity? Ok i know the default session timeout is set to 25 minues if they are idle, but will it still timeout if the are on a constant refresh page, like if the page there on refreshes every minute will they time out after the 25 still. Hey I was wondering is there a way I can set my sessions to timeout/end a session after a certain amount of time? Here is what I am dealing with... Code: [Select] <?php session_start(); $username = $_SESSION['username']; $userid = $_SESSION['userid']; ?> I have 500 users using software I have developed, and 495 do not have a timeout problem. Our default is to timeout after 60 minutes, but one particular office times out randomly and without warning. The normal procedure is, like online banking, a pop up comes up to let them know they will be logged out in 60 seconds, or they can click continue to stay logged in.
The timer is based on JS, but on each page load a PHP function checks to see if they are timed out, and if they are, redirect them to the login page. The JS pop up never occurs, so obviously the countdown hasn't happened, but when they click on a link, they are redirected to the login page.
Since the issue only occurs in one office, it leads me to believe it is a firewall or anti-virus issue, but I'm not sure...
Anyone have any thoughts on this?
Hi there, I am wondering if you guys can help me make it so my session times out after a previously set time. I have researched this and found no luck. Here is my code.... Code: [Select] <?php session_start(); $username = $_SESSION['username']; $userid = $_SESSION['userid']; ?> Thanks in advance! Hi: How do I set a password-protected page to time out after 20 minutes or so? I thought it was doing it on the below page, but it is not working. A tutorial I found online. Login.php Code: [Select] <form name="form1" method="post" action="myLogin.php"> <input name="myUserName" type="text" size="40" id="myUserName"> <br /><br /> <input name="myPassword" type="password" size="40" id="myPassword"> </div> <input type="submit" name="Submit" value="Login"> </form> myLogin.php Code: [Select] <?php ob_start(); // Connect to server and select database. //mysql_connect("$host", "$username", "$password")or die("cannot connect"); //mysql_select_db("$db_name")or die("cannot select DB"); // Define $myUserName and $myPassword $myUserName=$_POST['myUserName']; $myPassword=$_POST['myPassword']; // To protect MySQL injection (more detail about MySQL injection) $myUserName = stripslashes($myUserName); $myPassword = stripslashes($myPassword); $myUserName = mysql_real_escape_string($myUserName); $myPassword = mysql_real_escape_string($myPassword); $sql="SELECT * FROM myAdmins WHERE myUserName='$myUserName' and myPassword='$myPassword'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $myUserName and $myPassword, table row must be 1 row if($count==1){ // Register $myUserName, $myPassword and redirect to file "a_Home.php" session_register("myUserName"); session_register("myPassword"); header("location:a_Home.php"); } else { echo " <html> ... </html> "; } ob_end_flush(); ?> myCheckLogin.php (added to each page to see if the person logged-in via Login.php): Code: [Select] <? session_start(); if(!session_is_registered(myUserName)){ header("location:Login.php"); } ?> Any help would be great. Thanks. When a user logs on, I authenticate them with a session. How do I use php to determine the time until the session will expire? I realize I could go into the ini file but is there a php code that can query this info and echo it back? Is there a way to reset a session? Here is my code... Code: [Select] <?php session_start(); if (!isset($_SESSION['logged_in'])) { header("Location: login.php"); } mysql_connect("localhost", "user", "password")or die("cannot connect"); mysql_select_db("database")or die("cannot select DB"); $bio = $_POST['Bio']; $location = $_POST['Location']; $username = $_SESSION["user_name"]; $sql = "UPDATE users SET bio = '$bio', location = '$location' WHERE username = '$username'"; $result = mysql_query($sql) or die ("Error in query: $sql. " . mysql_error()); ?> Now I have a session called bio that I need to reset so that it will store the new bio information. How can I do this? I tried to unset the session and start it again but this didn't work. I have a session variable called $_SESSION['patchurl'] in a php file , if i get in to an else statement this session variable gets set and i go to http://yyy page. below is the snippet of the code <?php session_start(); ?> <?php echo '<script type="text/javascript">' . "\n"; if(isset($_SESSION["Email"])){ echo 'window.location="http://www.xxx";'; } else{ $_SESSION['patchurl'] = "true"; echo 'window.location="http://yyy";'; } echo '</script>';?>once the patchurl session variable is set i call a php file which sets an other session variable called $_SESSION["Email"]. now what happens is the $_SESSION['patchurl'] is gone and ONLY the $_SESSION["Email"] is accessible ...can i not set two session variables? why does creating a new session varible overwrites an other one even though they are called different ? am i doing something wrong ? Edited by Ch0cu3r, 08 September 2014 - 01:05 PM. Hello All, I have a PHP web application which will refresh itself(ajax calls connecting to the server and get the latest data) periodically. These also update the Database-based session handler class. i.e. There is NO UPDATE to the session data but the timestamp is constantly updated. Our problem is that garbage collection does not kick in as it looks at the difference between timestamp and session_gc.maxlifetime. So, if and the user is not interacting with the application. Now my question is how can I force the timeout even though refreshing happens but the user is not interacting with the application and there are "phantom" session updates made by these ajax calls. Please let me know. Thanks. My contact form works, but how can I reset it so that when someone fills in the required information and the send the email, I want the information from the text boxes to clear. Right now, it doesnt do that, the name,email address, and message remains in the text boxes. Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Author: Reality Software Website: http://www.realitysoftware.ca Note: This is a free template released under the Creative Commons Attribution 3.0 license, which means you can use it in any way you want provided you keep the link to the author intact. --> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Contact</title> <link href="style.css" rel="stylesheet" type="text/css" /></head> <body> <!-- header --> <div id="header"> <div id="logo"><a href="#">Header</a></div> <div id="menu"> <ul> <li><a href="#">Home</a></li> <li><a href="#">Link 1</a></li> <li><a href="#">Link 2</a></li> <li><a href="#">Link 3</a></li> <li><a href="#">Contact</a></li> <li><a href="#">Guestbook</a></li> </ul> </div> </div> <!--end header --> <!-- main --> <div id="main"> <div id="content"> <div id="text"> <h1><strong>Contact</strong></h1> </div> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <?php if (isset($_POST['Submit'])) { if ($_POST['name'] != "") { $_POST['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING); if ($_POST['name'] == "") { $errors .= 'Please enter a valid name.<br/><br/>'; } } else { $errors .= 'Please enter your name.<br/>'; } if ($_POST['email'] != "") { $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors .= "$email is <strong>NOT</strong> a valid email address.<br/><br/>"; } } else { $errors .= 'Please enter your email address.<br/>'; } if ($_POST['message'] != "") { $_POST['message'] = filter_var($_POST['message'], FILTER_SANITIZE_STRING); if ($_POST['message'] == "") { $errors .= 'Please enter a message to send.<br/>'; } } else { $errors .= 'Please enter a message to send.<br/>'; } if (!$errors) { $first_name=$_POST['name']; $email_address=$_POST['email']; $subject = 'Email Submission'; $message=$_POST['message']; mail("myemailaddress@gmail.com","$subject", $message,"From: $first_name <$email_address>"); echo "Thank you for your email!<br/><br/>"; } else { echo '<div style="color: red">' . $errors . '<br/></div>'; } } ?> <form name="form1" method="post" action="contact.php"> Name: <br/> <input type="text" name="name" value="<?php echo $_POST['name']; ?>" size="50" /><br/><br/> Email Address: <br/> <input type="text" name="email" value="<?php echo $_POST['email']; ?>" size="50"/> <br/><br/> Message: <br/> <textarea name="message" rows="5" cols="50"><?php echo $_POST['message']; ?></textarea> <br/> <input type="Submit" name="Submit" value="Submit"/> <input type="Reset" name="Reset" value="Reset"/> </form> <!-- footer --> <br/> <br/> <br/> <div id="footer"> <div id="left_footer">© Copyright 2011<strong> Author </strong></div> <div id="right_footer"> <!-- Please do not change or delete this link. Read the license! Thanks. :-) --> Design by <a href="http://www.realitysoftware.ca" title="Website Design">Reality Software</a> <!-- end footer --></div> <!-- end main --></div> </body> </html> Hi all I have a form where there are three fields, category, type, colour. On the top drop down (Category) I need it to reset the form and remove the url parameters when it is selected. Here's my code: <form id="filter" name="filter" method="get" action="product.php"> <br /><strong>Categories:</strong><br /><br /> <select name="category" id="category_filter" style="width: 200px" onChange="this.form.submit();"> <option value="0" selected class="meter-calc-text">All Categories</option> <?php $fetchcategories=mysql_query("SELECT * FROM `product_categories` ORDER BY id ASC"); while($returnedcategories=mysql_fetch_array($fetchcategories)) { echo "<option value=\"".$returnedcategories['id']."\"".(($returnedcategories['id']==$_GET['category']) ? ' selected="selected"':'').">".$returnedcategories['name']."</option>"; } ?> </select> How do I reset the url when the user clicks the drop down? Many thanks for your help Pete Hi all I have a filter system on a website I am creating and there are three forms each sends a value to the url using get. Every time a user selects the drop down on the first form it send to the url and then a SQL query is run to select items from a database which works great for all three forms. However, the problem I have is when the user goes and re-selects a category from the first form it needs to reset the other two below it and emptying the url parameter for both so it just asks the SQL to select the items from that category again. Please help Many thanks Pete I am new to php and I thought it best to start by using a CMS and creating small functions to extend it's functionality. I will start by explaining the situation around what I want to do. I am trying to create a module for the drupal CMS. The module I am trying to create I am creating for my girlfriends son (for when it is complete he will be the one maintaining it through the web interface). He wants a game server (WOW) and a web site that once they create an account on the web site it will create an account on the game server as well. If I understand the way this works correctly for this game server to work you need a logon database and then a character and world database for each realm you have. With that basically what happens is you go to the drupal web site and click create account, input a username, email address and password and agree to terms of service. Then drupal does some checks and writes the information to the drupal database and with the module I creating it will write to the logon database as well. I am working on the admin forms so you can edit how many realms the server has the sql statement to login to the game and add and delete realms. I have been looking at an example of a form for drupal here http://drupal.org/node/717746 but have converted it to my purpose and it brings up some questions here is what I have so far: function wowcp_gameserver_settings($form_state) { $form['server'] = array( '#type' => 'fieldset', '#title' => t('WOW Game Server Core'), ); $form['server']['decision'] = array( '#type' => 'select', '#title' => 'Select the Server Core that your WOW server runs on', '#options' => array('TrinityCore2', 'ArcEMU', 'Aspire', 'Mangos'), '#default_value' => TrinityCore2, ); $form['server']['sql_command'] = array( '#type' => 'textfield', '#title' => 'Select the SQL command for your server core', '#size' => 150, ); $form['server']['max_realms'] = array( '#type' => 'textfield', '#title' => t('Select the maximum realms allowed'), '#size' => 2, ); $form['logon'] = array( '#type' => 'fieldset', '#title' => t('WOW Game Server LOGON database setup') ); $form['logon']['logon_db'] = array( '#type' => 'textfield', '#title' => t('Enter the name of the LOGON database'), '#size' => 25, ); $form['logon']['logon_username'] = array( '#type' => 'textfield', '#title' => t('Enter the username for the LOGON database'), '#size' => 25, ); $form['logon']['logon_password'] = array( '#type' => 'textfield', '#title' => t('Enter the password for the LOGON database'), '#size' => 25, ); $form['realm']['character'] = array( '#type' => 'fieldset', '#title' => t('WOW Game Server first realm'), ); $form['realm']['character']['character_db'] = array( '#type' => 'textfield', '#title' => t('Enter the name of the CHARACTER database'), '#default_value' => $form_state['values']['character_db'], '#size' => 25, ); $form['realm']['character']['character_username'] = array( '#type' => 'textfield', '#title' => t('Enter the username for the CHARACTER database'), '#default_value' => $form_state['values']['character_username'], '#size' => 25, ); $form['realm']['character']['character_password'] = array( '#type' => 'textfield', '#title' => t('Enter the password for the CHARACTER database'), '#default_value' => $form_state['values']['character_password'], '#size' => 25, ); $form['realm']['world']['world_db'] = array( '#type' => 'textfield', '#title' => t('Enter the name of the WORLD database'), '#defaule_value' => $form_state['values']['world_db'], '#size' => 25, ); $form['realm']['world']['world_username'] = array( '#type' => 'textfield', '#title' => t('Enter the username for the WORLD database'), '#defaule_value' => $form_state['values']['world_username'], '#size' => 25, ); $form['realm']['world']['world_password'] = array( '#type' => 'textfield', '#title' => t('Enter the password for the WORLD database'), '#defaule_value' => $form_state['values']['world_password'], '#size' => 25, ); if (isset($form_state['storage']['new_name'])) { $form['character2'] = array( '#type' => 'fieldset', '#title' => t('WOW Game Server CHARACTER database setup for realm2'), ); $form['character2']['character_db2'] = array( '#type' => 'textfield', '#title' => t('Enter the name of the CHARACTER database for relam2'), '#default_value' => $form_state['values']['character_db2'], '#size' => 25, ); $form['character2']['character_username2'] = array( '#type' => 'textfield', '#title' => t('Enter the username for the CHARACTER database for realm2'), '#default_value' => $form_state['values']['character_username2'], '#size' => 25, ); $form['character2']['character_password2'] = array( '#type' => 'textfield', '#title' => t('Enter the password for the CHARACTER database for realm2'), '#default_value' => $form_state['values']['character_password2'], '#size' => 25, ); $form['world2'] = array( '#type' => 'fieldset', '#title' => t('WOW ame Server WORLD database setup for realm2'), ); $form['world2']['world_db2'] = array( '#type' => 'textfield', '#title' => t('Enter the name of the WORLD database for realm2'), '#defaule_value' => $form_state['values']['world_db2'], '#size' => 25, ); $form['world2']['world_username2'] = array( '#type' => 'textfield', '#title' => t('Enter the username for the WORLD database for realm2'), '#defaule_value' => $form_state['values']['world_username2'], '#size' => 25, ); $form['world2']['world_password2'] = array( '#type' => 'textfield', '#title' => t('Enter the password for the WORLD database for realm2'), '#defaule_value' => $form_state['values']['world_password2'], '#size' => 25, ); } $form['submit'] = array( '#type' => 'submit', '#value' => 'Submit', ); $form['clear'] = array( '#type' => 'submit', '#value' => 'Reset', '#validate' => array('wowcp_form_clear'), ); if (empty($form_state['storage']['new_name'])) { $form['new_name'] = array( '#type' => 'submit', '#value' => 'Add Realm', '#validate' => array('wowcp_form_new_name'), ); $form['delete'] = array( '#type' => 'submit', '#value' => 'Delete Realm', '#validate' => array('wowcp_form_delete'), ); } return $form; } If max_realms is set to a large number the way I see it you would have to hard code everything into the php file. Instead of that could you not remove from the if(isset) and have it that when they click on the add realm button check to make sure the textfield contains a number if it doesn't return an error if it does contain a number make sure it is not greater then max_realms and then use a start count and adding that number to all the arrays for that realm and validate all the information is what you expect. I think this would work for adding realms, I think where the problem would come in is in deleting realms (or it could be me over thinking it). For example if you have max_realms set to 4 you could have 5 the one default one that can't be deleted plus 4 others and the ones that can be deleted would be called realm1 - realm4 if you delete the first 2 you would minus count by 2 so if you clicked add realm again it would try and create realm3 which already exists. Is there another way on doing this that you could create the realms and delete them and it not try to add realms with the same array name? I have this HTML form that isn't doing anything when the submit button pressed, I am using PHP to validate it. I know I am missing something, can you help me? :/ Thanks in advance! Code: [Select] <?php require("styles/top.php");?> <div id="head_reg"> <div id="head_cen_reg"> <div id="head_sup_reg" class="head_height_reg"> <p class="search"> <label>SEARCH</label> <input name="search" type="text" class="txt" /> <input name="search-btn" type="submit" class="btn" value="SEARCH" /> </p> <h1 class="logo"></h1> <?php require("scripts/links.php"); ?> </div> </div> </div> <div id="content"> <br /> <div id="register_form"> <form action="register.php" method="post" enctype="multipart/form-data"> <center> <table> <tr> <td>Desired Username </td> <td><input type="text" name="username" class="textbox" /></td> </tr> <tr> <td>E-Mail </td> <td><input type="text" name="email" class="textbox" /></td> </tr> <tr> <td>Password </td> <td><input type="text" name="pass" class="textbox" /></td> </tr> <tr> <td>Confirm Password </td> <td><input type="text" name="repass" class="textbox" /></td> </tr> <tr> <td><p class="register"> <input name="reg-btn" type="submit" class="btn" value="REGISTER" /> </p></td> </tr> </table> </center> </form> </div> <center><a href="#" id="showreg">Why register? Click here</a></center> <div id="content_cen"> <div id="content_sup"> <div id="welcom_pan"> <h3><span>Why</span> Register?</h3> <p>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla vitae diam magna, eget fringilla tellus. Curabitur est velit, suscipit eu faucibus eget, aliquam ac enim. per inceptos himenaeos. Nulla vitae diam magna, eget fringilla tellus.</p> </div> </div> </div> </div> <div id="foot"> <div id="foot_cen"> <ul> </ul> <p></p> </div> </div> <?php if(isset($_POST['reg_btn'])){ $username = $_POST['username']; $email = $_POST['email']; $password = $_POST['pass']; $repassword = $_POST['repass']; if ($username && $password && $repassword && $email){ if ($password == $repassword){ if (strstr($email, "@") && strstr($email, ".") && (strlen($email) >= 6)){ $query = mysql_query("SELECT * FROM users WHERE username='$username'"); $numrows = mysql_num_rows($query); if ($numrows == 0){ $query = mysql_query("SELECT * FROM users WHERE email='$email'"); $numrows = mysql_num_rows($query); if ($numrows == 0){ $pass = md5(md5($password)); $ip = $_SERVER['REMOTE_ADDR']; $date = date("F,d,Y:g:i:s A"); mysql_query("INSERT INTO users VALUES ('', '$username', '$pass', '$email','Member', '$date', '', '$ip', '0')"); } else echo"That email is already in use!"; } else echo"That username is already taken!"; } else echo"That email is too short!"; } else echo"Those passwords do not match!"; } else echo"<script type='text/javascript'>alert('You did not fill out the entire form!')</script>"; } ?> I have a firm that post to my database. When I tested it always posted my information correctly. I require the user to be logged in before they can access the page with the form. I do I ensure that each php variable has a value in it before the data is posted? Any help would be appreciated. I can post my code if needed. i have a php script and i want it to submit to itself having the php script on the same page, the problem is when i do it it tries to upload the file without waiting for the form resaulting in format you tried to upload was not allowed" (its an image uploader) heres my code Code: [Select] <?php // Configuration - Your Options $allowed_filetypes = array('.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation. $max_filesize = 1524288; // Maximum filesize in BYTES (currently 1.5MB). $upload_path = './files/'; // The place the files will be uploaded to (currently a 'files' directory). $filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension). $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename. // Check if the filetype is allowed, if not DIE and inform the user. if(!in_array($ext,$allowed_filetypes)) die('<font size="4"><font color="red">The file you attempted to upload is not allowed.</font></font>'); // Now check the filesize, if it is too large then DIE and inform the user. if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize) die('The file you attempted to upload is too large.'); // Check if we can upload to the specified path, if not DIE and inform the user. if(!is_writable($upload_path)) die('You cannot upload to the specified directory, please CHMOD it to 777.'); // Upload the file to your specified path. if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename)) echo '<font size="4"><span style="color: white; text-shadow: lime 0px 0px 3px;"><h2>Upload Successful!</h2><br> <img src="' . $upload_path . $filename . '"><br> <p id="codes"><label for="codedirect">Direct Link:</label><br /> <input type="text" id="codebb" value="http://imageplanet.site90.net/' . $upload_path . $filename . '" onclick="javascript:this.focus();this.select();" readonly="true" /><br /> <label for="codehtml">HTML code:</label><br /> <input type="text" id="codehtml" value="<img src="http://imageplanet.site90.net/' . $upload_path . $filename . '">" onclick="javascript:this.focus();this.select();" readonly="true" /><br /> <label for="codebb">IMG code:</label><br /> <input type="text" id="codebb" value="[IMG]http://imageplanet.site90.net.info/' . $upload_path . $filename . '[/IMG]" onclick="javascript:this.focus();this.select();" readonly="true" /></p></div> </span></font>'; // It worked. else echo '<font size="4"><font color="red">There was an error during the file upload. Please try again.</font</font>'; // It failed :(. ?> <form action="upload.php" method="post" enctype="multipart/form-data"> <p> <label for="file"><font color="white">Select a image:</font></label> <br><br> <input type="file" name="userfile" id="file"> <br /> <button>Click Here To Upload</button> <p> <br> <br> <font color="#006FFF"><span style="font-family: Criovision; font-weight: normal; font-style: normal; text-decoration: none; font-size: 15pt;">Max File Upload Size: 1.5MB<br></span></font> </div> </span> i just want it so it doesn't display that error Code: [Select] <?php include 'config.php'; //include 'dbc.php'; ?> <?php function filter($data) { // <--line 6 $data = trim(htmlentities(strip_tags($data))); if (get_magic_quotes_gpc()) $data = stripslashes($data); $data = mysql_real_escape_string($data); return $data; } ?> <?php /******************* ACTIVATION BY FORM**************************/ if ($_POST['doReset']=='Reset') { $err = array(); $msg = array(); foreach($_POST as $key => $value) { $data[$key] = filter($value); } if(!isEmail($data['email'])) { $err[] = "ERROR - Please enter a valid email"; } $email = $data['email']; //check if activ code and user is valid as precaution $rs_check = mysql_query("select id from users where email='$email'") or die (mysql_error()); $num = mysql_num_rows($rs_check); // Match row found with more than 1 results - the user is authenticated. if ( $num <= 0 ) { $err[] = "Error - Sorry no such account exists or registered."; //header("Location: forgot.php?msg=$msg"); //exit(); } if(empty($err)) { $new_pass = GenPwd(); $pass_reset = MD5($new_pass); //$sha1_new = sha1($new); //set update sha1 of new password + salt $rs_activ = mysql_query("update users set pass='$pass_reset' WHERE email='$email'") or die(mysql_error()); $host = $_SERVER['HTTP_HOST']; $host_upper = strtoupper($host); //send email $message = "Here are your new password details ...\n User Email: $email \n Passwd: $new_pass \n Thank You Administrator $host_upper ______________________________________________________ THIS IS AN AUTOMATED RESPONSE. ***DO NOT RESPOND TO THIS EMAIL**** "; mail($email, "Reset Password", $message, "From: \"Member Registration\" <auto-reply@$host>\r\n" . "X-Mailer: PHP/" . phpversion()); $msg[] = "Your account password has been reset and a new password has been sent to your email address."; //$msg = urlencode(); //header("Location: forgot.php?msg=$msg"); //exit(); } } ?> <html> <head> <title>Forgot Password</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <script language="JavaScript" type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <script language="JavaScript" type="text/javascript" src="js/jquery.validate.js"></script> <script> $(document).ready(function(){ $("#actForm").validate(); }); </script> <link href="styles.css" rel="stylesheet" type="text/css"> </head> <body> <table width="100%" border="0" cellspacing="0" cellpadding="5" class="main"> <tr> <td colspan="3"> </td> </tr> <tr> <td width="160" valign="top"><p> </p> <p> </p> <p> </p> <p> </p> <p> </p></td> <td width="732" valign="top"> <h3 class="titlehdr">Forgot Password</h3> <p> <?php /******************** ERROR MESSAGES************************************************* This code is to show error messages **************************************************************************/ if(!empty($err)) { echo "<div class=\"msg\">"; foreach ($err as $e) { echo "* $e <br>"; } echo "</div>"; } if(!empty($msg)) { echo "<div class=\"msg\">" . $msg[0] . "</div>"; } /******************************* END ********************************/ ?> </p> <p>If you have forgot the account password, you can <strong>reset password</strong> and a new password will be sent to your email address.</p> <form action="forgot.php" method="post" name="actForm" id="actForm" > <table width="65%" border="0" cellpadding="4" cellspacing="4" class="loginform"> <tr> <td colspan="2"> </td> </tr> <tr> <td width="36%">Your Email</td> <td width="64%"><input name="email" type="text" class="required email" id="txtboxn" size="25"></td> </tr> <tr> <td colspan="2"> <div align="center"> <p> <input name="doReset" type="submit" id="doLogin3" value="Reset"> </p> </div></td> </tr> </table> <div align="center"></div> <p align="center"> </p> </form> <p> </p> <p align="left"> </p></td> <td width="196" valign="top"> </td> </tr> <tr> <td colspan="3"> </td> </tr> </table> </body> </html> Fatal error: Cannot redeclare filter() (previously declared in/forgot.php:6) what is wrong ? I have PHP forms that are not submitting to my database. I think it is something minor but I just can't see it! Can anyone help? At the beginning of index.php, the page holding the forms, I have this: Code: [Select] [b]<?php include("functions/globals.php"); ?> <?php include("functions/userfunctions.php"); ?>[/b] [b]Here are these pages:[/b] [b]globals.php[/b] <?php ob_start();//Required for the redirect to work?> <?php include("loginstatus.php");?> <?php session_start(); ?> [b]((Here's loginstatus.php for good measu [/b] <?php class cUser { public $username = "";//The User Name public $userid = "";//The User ID public $type = "";//The Type Of User } ?> [b]))[/b] [b]And here is userfunctions.php[/b] <?php include_once("databasefunctions.php"); (this holds the connection) $userdbtable = "users"; function GetHeaders() { $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Additional headers $headers .= "To: {$username} <{$email}>" . "\r\n"; $headers .= 'From: My Website <[email]noreply@myswebsite.com[/email]>' . "\r\n"; return $headers; } function CreateAccount($firstname, $lastname, $username, $password, $email, $type) { global $userdbtable; openDatabase(); $firstname = mysql_real_escape_string($firstname); $lastname = mysql_real_escape_string($lastname); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); $email = mysql_real_escape_string($email); $type = mysql_real_escape_string($type); $nonencrypted = $password; $password = sha1($password); $result = QuickQuery("INSERT INTO {$userdbtable}(firstname, lastname, username, password, email, type) VALUES('{$firstname}','{$lastname}','{$username}','{$password}','{$email}',{$type}')"); if($result) { $headers = GetHeaders(); $message = "\"Welcome to my website!\"<br /> <br /> Your username is: {$username}<br /> Your password is: {$nonencrypted}<br /> <br /> Signed,<br /> <br /> Me "; mail($email, "Account Creation", $message, $headers); mail("[email]myemailaddress@me.com[/email]", "Account Created", "{$username} has created a new account", $headers); } } function ValidateUser($username, $password) { global $userdbtable; openDatabase(); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); $result = QuickQuery("SELECT * FROM {$userdbtable} WHERE username = '{$username}'"); closeDatabase(); if(!mysql_result($result,0,"username"))//Make sure the user exists return "User Does Not Exist"; $temppwd=mysql_result($result,0,"password");//Make sure the passwords match if(sha1($password) != $temppwd) return "Password Does Not Match"; return 1; } function GetUserID($username) { global $userdbtable; openDatabase(); $username = mysql_real_escape_string($username); $result = QuickQuery("SELECT id FROM {$userdbtable} WHERE username = '{$username}'"); closeDatabase(); if($result) return(mysql_result($result,0,"id"));//Get the user id else return 0; return(mysql_result($result,0,"id"));//Get the UserID } function GetUserType($username) { global $userdbtable; openDatabase(); $username = mysql_real_escape_string($username); $result = QuickQuery("SELECT type FROM {$userdbtable} where username = '{$username}'"); closeDatabase(); return(mysql_result($result,0,"type"));//Get the user type } function GetUserEmail($username) { global $userdbtable; openDatabase(); $username = mysql_real_escape_string($username); $result = QuickQuery("SELECT email FROM {$userdbtable} WHERE username = '{$username}'"); closeDatabase(); return(mysql_result($result,0,"email"));//Get the user email } function ConfirmPassword($id, $password) { global $userdbtable; openDatabase(); $password = mysql_real_escape_string($password); $password = sha1($password); $result = QuickQuery("SELECT * FROM {$userdbtable} WHERE id = '{$id}' AND password = '{$password}'"); closeDatabase(); if(!$result) return 0; else return 1; } function ChangePassword($id, $password) { global $userdbtable; openDatabase(); $password = mysql_real_escape_string($password); $password = sha1($password); return QuickQuery("UPDATE {$userdbtable} SET password='{$password}' WHERE id={$id}"); } function ResetPassword($email) { global $userdbtable; openDatabase(); $email = mysql_real_escape_string($email); $result = QuickQuery("SELECT * FROM {$userdbtable} WHERE email = '{$email}'"); $num = mysql_numrows($result); if(!$num) return 0; $user = mysql_result($result, 0, "username"); $email = mysql_result($result, 0, "email"); $randompwd = RandomPwd(); $temp = sha1($randompwd); $headers = GetHeaders(); mail($email, "Blah blah blah. Your newusername is: {$user}, and your new password is: {$randompwd}. ", $headers); if(QuickQuery("UPDATE {$userdbtable} SET password='{$temp}' WHERE email='{$email}'")) return 1; } function RandomPwd() { $length = 10; $characters = '0123456789abcdefghijklmnopqrstuvwxyz'; $string = ""; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))]; } return $string; } ?> [b]Here is the info on index.php for login and registration[/b] [b]Login:[/b] <?php if($_GET['logout'] == 'logout') { session_destroy(); Redirect("index.php"); } if($_POST['submitted'] == "login") { // echo ValidateUser("Jimmy", "password"); //CreateAccount($name, $password, $email, $type); if(ValidateUser($_POST['username'], $_POST['password']) == 1) { $_SESSION['user'] = new cUser; $_SESSION['user']->username = $_POST['username']; $_SESSION['user']->usertype = GetUserType($_POST['username']); $_SESSION['user']->userid = GetUserID($_POST['username']); Redirect("index.php"); } // CreateAccount("test", "test", "[email]me@website.com[/email]", "user"); } ?> [b]Registration[/b] <?php if($_POST['submitted'] == "register") { $firstname = $_POST['firstname']; $lastname = $_POST['lastname']; $username = $_POST['username']; $email = $_POST['email']; $password = $_POST['password']; $confirmpwd = $_POST['confirmpwd']; if(!$firstname) $error = "Invalid First Name"; else if(!$lastname) $error = "Invalid Last Name"; else if(!$username) $error = "Invalid User Name"; else if(!$email) $error = "Invalid Email"; else if(!$password) $error = "Invalid Password"; } ?> <?php if($_POST['submitted'] && !$error) { $result = QuickQuery("SELECT username FROM users WHERE username='{$username}'"); if(mysql_numrows($result) > 0) $error = "Be More Creative. Someone Already is Using That Username."; else { $result = QuickQuery("SELECT email FROM users WHERE email='{$email}'"); if(mysql_numrows($result) > 0) $error = "Email Already Being Used. Maybe you already registered."; else if($confirmpwd != $password) $error = "Matching passwords means the second password must be exactly like this first."; else { CreateAccount($firstname, $lastname, $username, $password, $email, "user"); } } } ?> [b]Both forms are here[/b] <div class="btn-show"> <p>Login</p> </div> <div class="pushup-form"> <div class="btn-close"> Close </div> <div class="clear"> </div> <form action="index.php" method="post"> <p style="font-size:14px">Login</p> <p>Username:<input type="text" name="username" style="font-size:12px;"/></p> <p>Password:<input type="password" name="password" style="font-size:12px;"/></p> <p><input class="login" type="submit" name="submitted" value="login" /></p> <p><a href="pwd.php?pwd=lostpwd" style="font-size:10px">Forgot Username or Password?</a></p> </form> <div class="panel"> <form action="index.php" method="post"> <p>First Name:<input type="text" name="firstname" value="<?php echo $firstname;?>" /></p> <p>Last Name:<input type="text" name="lastname" value="<?php echo $lastname;?>" /></p> <p>Username:<input type="text" name="username" value="<?php echo $username;?>" /></p> <p>Email:<input type="text" name="email" class="clear" value="<?php echo $email;?>" /></p> <p>Password:<input type="password" name="password" value="<?php echo $password;?>" /></p> <p>Confirm Password:<input type="password" name="confirmpwd" value="<?php echo $confirmpwd;?>" /></p> <p class="clear"> <p><input class="register" type="submit" name="submitted" value="register"/></p> </p> </form> </div> <p style="text-align:center;" class="flip">Need to Register?</p> </div> [code] These forms open from the right side of my website by clicking "Register." The top of the form has an option for login and by clicking "Need to Register?" The rest of the form expands. Any ideas? My database is set up correctly. MOD EDIT: code tags added. |