Jump to content

Search the Community

Showing results for tags 'session'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. SO I have been developing a log in system and wanted to make my own simple CAPTCHA. I found one on the internet and ported the code across to get started and see how someone had made it. The issue I am having is that the dynamically generated image that I have created it seems is one step ahead of the session variable (the string is generated and then saved into session - then generates the image). But when i echo back the session it is always one step behind the actual image... Anyway here is my code and ask away please <?php require('includes/util.inc.php'); $form = ' <form action="register.php" method="post"> <p>username <input type="text" name="username" id="usrinp"></p> <p>email <input type="text" name="email" id="emainp"></p> <p>password <input type="password" name="password1" id="psw1inp"></p> <p>re-enter password <input type="password" name="password2" id="psw2inp"></p> <p><img src="captcha.php"/></p> <p>captcha <input type="text" name="captcha" id="capinp"></p> <p><input type="submit" value="Register" id="subinp"></p> </form> '; if(isset($_SESSION['captcha'])) { echo $_SESSION['captcha']; } if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['username']) && !empty($_POST['email'])) { if($_POST['captcha'] == $_SESSION['captcha']) { $username = $_POST['username']; $email = $_POST['email']; $password = SHA1($_POST['password1']); $password = SHA1($_POST['password2']); $q = 'SELECT username FROM users WHERE username = :username'; $stmt = $pdo->prepare($q); $stmt->bindParam(':username', $username); $stmt->execute(); if($stmt->rowCount() > 0) { echo "<pre>This username has already been taken</pre>"; } else { $qi = 'INSERT INTO users ( username, password, email ) VALUES ( :username, SHA1(:password), :email )'; $query = $pdo->prepare($qi); $result = $query->execute( array( ':username'=>$username, ':password'=>$password, ':email'=>$email ) ); if($result) { header("location:login.php"); exit; } else { echo '<pre>Error, please try again</pre>'; } } } } $pageTitle = 'Register'; include('includes/header.inc.php'); include('pages/register.html'); ?> <?php require('includes/util.inc.php'); $string = ''; for ($i = 0; $i < 5; $i++) { $string .= chr(rand(97, 122)); } $_SESSION['captcha'] = $string; $font_path = 'includes/fonts/'; $captcha_image = imagecreatetruecolor(150, 60); $text_color = imagecolorallocate($captcha_image, 0, 0, 0); $bg_color = imagecolorallocate($captcha_image, 255, 255, 255); imagefilledrectangle($captcha_image, 0, 0, 399, 99, $bg_color); imagettftext($captcha_image, 30, 0, 10, 40, $text_color, $font_path . "dashdot.ttf", $_SESSION['captcha']); header("Content-type: image/png"); imagepng($captcha_image); ?> <?php session_start(); function class_loader($class) { require 'classes/' . $class . '.class' . '.php'; } spl_autoload_register('class_loader'); $user = (isset($_SESSION['user'])) ? $_SESSION['user'] : null; $cat = (isset($_SESSION['cat'])) ? $_SESSION['cat'] : null; try { $pdo = new PDO('mysql:dbname=phpcat; host=localhost', 'root', ''); } catch (PDOException $e) { $pageTitle = 'Error!'; include('header.inc.php'); include('../pages/error.html'); exit(); }
  2. I 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.
  3. I am having a very strange issue on one server. I have the same code in a development server running fine, but in my prod server it is failing. Here is the main issue: I have a user authentication routine that accepts UserID and Password from a form and validates it against a MySQL database. So to start, UserId and Password are entered via POST variables as is standard: $UserId=@$_POST['UserId']; $Password=@$_POST['Password']; The Password is encrypted using a standard crypt method such as: $encrypt = crypt($Password,'6!68$7435!'); And this is stored in a MySQL database. This part is working fine, that is, the password is encrypted in value and stored in the MySQL database as 'epasswd'. On login, I am using session, so a standard session_start() and eventual session_destroy() on logout are used. The reason I mention this is because I suspect my issue is session related. So normally this works well. User logs in and I check credentials as follows in one part of my auth routine: elseif(UserAuth($UserId,$Password)){ $UserLogin=$UserId; session_start(); $_SESSION['UserLogin'] = $UserLogin; sql_insertActivity(); header("Location: home.php"); And the auth routine is as follows: <? function UserAuth($UserId,$Password){ global $conn; $Stmt="select epasswd from Users where UserId='$UserId' and Approved='1' or Approved='-1' or Approved='-2'"; $Result = mysql_query($Stmt, $conn) or die(mysql_error()); $Result=mysql_fetch_row($Result); $epasswd=$Result[0]; $retval=($epasswd==crypt($Password,$epasswd)); return($retval); } ?> So I am checking for a valid UserID and Password on form input, and I have a few other variables set for approved status. The retval checks the password they enter versus the encrypted value for a match. This usually works well. Then login occurs and session started, etc. Here is the issue. I added a quick admin routine a little while ago which helps reset a user's password to a temporary value. Once this value is set, along with a setting of approved=-1 in my database, then the user is re-directed to a Change Password screen to update his or her password. *Note: I changed the value to 'Charlie' for this discussion purpose. Here is that quick admin routine I run when I need to change a User to a temp setting: // ----- Establish database connection ----- require "../inc_php/inc_mysql_prod.php"; // $UserId=@$_GET['UserId']; $Password='Charlie'; $encrypt = crypt($Password,'6!68$7435!'); $sql = "UPDATE Users set epasswd='$encrypt', approved='-1' where UserId='$UserId'"; mysql_query($sql, $conn) or die(mysql_error()); So this does work as I validate the UserID is updated in the MySQL database along with an encrypted value for 'Charlie'. However, this is where things breakdown going forward. When the user logs in with the temp credentials, and enters in the Change password routine, their new password is saved in the table. However, when logging back in with the new credentials, the new password is not valid. And what's odd is that 'Charlie', the temp password, works for them on login and nothing else, no matter how many times they change the password in the form. So seems a case of session management out of control? What is the issue? I am defining session on all Php pages used, and have a logout to destroy session, etc. The temp password routine is something I run as an admin in the system and it doesn't have a session start statement. And I am not defining any global vars for Password. I lloked into session management and tried some UNSET paths and such, but may not be doing this correctly. Also I did a complete stop apache, remove all php sess_ files, restart and to no avail. I tried the clear my client side cookies deal in the browser, and still the same problem. What is odd is that this same set of code works fine on my other server, but breaks down on the mirrored server. They are essentially twins in all setup. Some minor differences between the two servers regarding PHP setup that might(?) make a difference. DEV server: SERVER_SOFTWARE Apache/2.2.3 (Red Hat) PROD server: (server showing the issues): SERVER_SOFTWARE Apache/2.2.3 (CentOS) HTTP_COOKIE PHPSESSID=3gocr0hhelvsjjlt63pp4qlnp3 _REQUEST["PHPSESSID"] 3gocr0hhelvsjjlt63pp4qlnp3 _COOKIE["PHPSESSID"] 3gocr0hhelvsjjlt63pp4qlnp3 _SERVER["HTTP_COOKIE"] PHPSESSID=3gocr0hhelvsjjlt63pp4qlnp3 Thanks appreciate the help! -Eddie
  4. 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 ?
  5. Hi to everyone, I'm new to the forum and I'm posting here because I ended up in a logical problem for my next script development. I need to get some data of external websites (with vbulletin board), perfectly legal. Using file_get_contents i can print the page content on my server and then use jquery's powerful selectors to get my data. The problem is that these data are shown only to logged in users so i would need this script (maybe using cURL?) to either login to the external website and then persists the connection or maybe if the user who is executing my script is already logged in that website then use his login? (most likely impossible I think..) This is my code so far (found on some sites and merged into this) $data = array('vb_login_username' => 'Scanu', 'vb_login_password' => 'grgfgrgrfbtgbt'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.vbulletin.org/forum/login.php?do=login"); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_COOKIESESSION, true); curl_setopt($ch, CURLOPT_FAILONERROR, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); curl_setopt($ch, CURLOPT_FRESH_CONNECT, true); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $result = curl_exec($ch); curl_close($ch); $pattern = "#Set-Cookie: (.*?; path=.*?;.*?)\n#"; preg_match_all($pattern, $result, $matches); array_shift($matches); $cookie = implode("\n", $matches[0]); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.vbulletin.org/forum/"); curl_setopt($ch, CURLOPT_COOKIE, $cookie); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_COOKIESESSION, true); curl_setopt($ch, CURLOPT_FAILONERROR, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); curl_setopt($ch, CURLOPT_FRESH_CONNECT, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_POST, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); $result = curl_exec($ch); curl_close($ch); echo $result; ?> It just shows the same page for unregistered users. Any help or advice is appreciated, i'm very new to this type of script..
  6. I am using PHP 5.3 iis7 and SLQ Server 2005. I know the script gets to the session part and creates a temp file in C:/windows/temp folder (see info below), but when I try to login and redirect to the index.php it give a 500 error on the login.php page. login.php index.php conifg.php temp file - C:\windows\temp <?php //set ini ini_set('session.gc_maxlifetime', 900); if(!ini_get('session.auto_start')){ session_start(); } // include file include ('config.php'); include (LIB_PATH.'functions.php'); include(LIB_PATH.'sqlsrv_connect.php'); if($_SESSION['user_id']){ Header("Location: index.php"); } if($_POST['submit']){ $user1 = trim($_POST['user']); $pass1 = trim($_POST['pass']); $user= "'$user1'"; $pass= "'$pass1'"; if($user == '' or $pass == ''){ $error = 'You forgot to enter your user_name and your password!'; }else{ $query = "SELECT * FROM users WHERE user_name = $user and pass = $pass"; $params = array(); $options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET ); $r = sqlsrv_query ($database, $query, $params, $options); $num = sqlsrv_num_rows($r); if ($num >0) { while ($user_data = sqlsrv_fetch_array($r, SQLSRV_FETCH_ASSOC)) { $_SESSION['user_id'] = $user_data['user_id']; $_SESSION['user_name'] = $user_data['user_name']; $_SESSION['user_level'] = $user_data['user_level']; $_SESSION['user_rep'] = $user_data['rep'];} Header("Location: index.php"); }else{ $error = 'Wrong username or password!'; } } } //template include(TEMP_PATH.'login_tpl.php'); ?> <?php //set ini ini_set('session.gc_maxlifetime', 900); if(!ini_get('session.auto_start')){ session_start(); } // include file include ('config.php'); //include (LIB_PATH.'functions.php'); include(LIB_PATH.'sqlsrv_connect.php'); if(!$_SESSION['user_id']){ Header("Location: login.php"); } $database //template include(TEMP_PATH.'index_tpl.php'); ?> <?php date_default_timezone_set('America/Los_Angeles'); //config directory define( 'DS', DIRECTORY_SEPARATOR ); define( 'DS', D ); define('SITE_PATH', dirname(__FILE__) . DS); define('LIB_PATH', SITE_PATH . 'lib' . DS); define('TEMP_PATH', SITE_PATH . 'templates' . DS); define('SO_PER_PAGE',20); ?> user_id|s:1:"6";user_name|s:2:"EM";user_level|s:1:"1";user_rep|s:0:"";
  7. Hello. I' have a Table in MySQL That stores data (name/email/time) of when a person last run X script. I'm trying to pull that information for each user unique to their account to display so they know that they've already ran that script today How it works. Run script > Create's Row storing the data > MySQL Events deletes row after 24 hours. My code to display notification if they have already ran it; $sql = 'SELECT a.name, a.time FROM timecheck a, users b WHERE a.name = b.name'; mysql_select_db('My_DB'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not get data: ' . mysql_error()); } while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) { echo "Account: {$row['name']} <br> ". "Last Time Run: {$row['time']} GMT -1<br> "; } echo "It seems you have done this already today!"; ?> Now my problem is. It's displaying every row to every user. I want it to only show the user their row... What I've tried. Creating a session variable "$sessionID" $sql = 'SELECT a.name, a.time FROM timecheck a, users b WHERE a.name = b.name AND a.name=$sessionID"'; But I'm not getting any lucky. All help is appreciated, thank you in advance.
  8. Hi all, In the login systems on the web, I have found that some use sessions and some others use cookies to validate a login. Normally for login systems with sessions, a hashed login string is created using say the password and HTTP_USER_AGENT is stored in a $_SESSION['logincheck'] variable. $login_check = hash('sha512', $password . $user_browser); and Before access is provided to the secure login page this SESSION variable is checked against a hashed string created again from values of password retrieved from the database again. $_SESSION['logincheck']== $login_check and if the two are same then the user is allowed to access his secure area. A similar approach is also provided in some cases where cookies are used. The values stored in cookies are checked against hashed values created with values of variables from the database and if they match access to the user page is granted. What I wish to ask and know is that would it be a good idea or a bad idea to implement both of these in a login system? What would be the advantages or disadvantages in both cases. I thought that using both would be a good idea but i am not sure. I have also not come across any system where both of these have been used simultaneously. Thanks all !
  9. Hello Friends, Please Help. The following the code for simple post method using session. Please read the codes. page1.php <?php session_start(); if(isset($_POST['seat'])) { $seat=$_POST['seat']; if (isset($_SESSION['seat'])) { if ($_SESSION['seat'] == "") { $_SESSION['seat']=$_POST['seat']; } else { $_SESSION['seat'] .=",".$_SESSION['seat']; } } else { $_SESSION['seat']=$_POST['seat']; } } ?> <html> <body> <form name="form1" action="<?php $_PHP_SELF; ?>" method="POST"> Select No. Of Seats: <select name="seat"> <option value=""></option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> <input type="submit" name="submit" value="Book Now" /> </form> <a href = "newpage.php">Results</a> </body> </html> ->In Page1.php i was selected the options one by one and clicked the submit. After that i was clicked the 'Results' link which redirect to newpage.php. newpage.php <?php session_start(); if(isset($_SESSION['seat'])) { $seat1=explode(",",$_SESSION['seat']); foreach($seat1 as $stt) { echo $stt."<br>"; } } session_destroy(); ?> ->In newpage.php, the actual result should be 1 2 3 4 5. But i get only the first result like 1 1 1 1 1. Please help me, what i did a mistake in the coding...???
  10. Hi, Im making a basic encryption program and have the encryption side working, but want to add in the feature to "decrypt" the encoded message if need be. Im using the POST method so that my program outputs to the same page that the form is on. I have tried the following : if ( isset($_POST["decrypt"]) ) { echo $_SESSION[$old_ascii]; } if ( $key < 1 || $key > 125 ) { echo "Please enter a key between 1 and 125</br>"; } else { foreach ( $userText as $old_ascii ) { echo $new_ascii = chr(imp_circular_position(32,126, ord( $old_ascii ), $key)); $_SESSION[$old_ascii] .= $old_ascii; } All i really want to do is store the users first entered text and relay that when the decrypt button is pressed the code for that is : <div id="buttons"> <input type="submit" value="Encrypt" name="Encrypt" /> <input name="decrypt" type="submit" value="De-crypt" /> </div> if( isset($_POST["userText"]) && $_POST["key"] ) { if( empty($_POST["userText"]) || empty($_POST["key"]) ) { die("Please enter a key between 1 and 125 and enter some secret message for me to encrypt!</br>"); } $userText = $_POST["userText"]; $key = $_POST["key"]; } If anyone could help with this id really appreciate it , so all i want to do is store the text first entered in a variable if I was using GET then it would be easy but this is my first time outputting text to the same page as the form and am a little lost! Thanks!
  11. Howdy folks, I am trying to get sessions to cooperate, but am at a loss. I am trying to copy the variable of userlevel in a session. The array displays correctly on pointerface.php. For some reason, the session doesn't seem to carry over to other pages, and the session ID's are different. I'd appreciate some input as to where I may be going wrong. pointerface.php: session_start(); { include('../htconfig/dbConfig.php'); mysql_connect("$hostname","$username","$password"); mysql_select_db("$database")or die("cannot select DB"); $tbl_name="members"; $sql2="SELECT * FROM members WHERE username='$myusername' and password='$mypassword'"; $result2=mysql_query($sql2); $userlevel=mysql_result($result2,$i,"userlevel"); $_SESSION["userlevel"] = "$userlevel" ; echo session_id(); echo "<br>"; Print_r ($_SESSION); adminnotes.php: session_start(); print_r ($_SESSION); echo session_id(); if($_SESSION['userlevel']=='Admin'){
  12. Hi all! I have a very strange situation. I have a webpage, built using PHP, where a visitor shall register his/her first name, last name, e-mail, phone and that choose a dish from a drop-down list. All this takes place using a form that is posted to a "process.php" script which validates the form and then put the data into SESSIONs. A confirm page shows the entered data to the visitor before it is being stored into a database. Pretty common scenario I would assume. The problem I face, is that empty data are being put into the database. After some communication with some of the visitors, I've managed to narrow it down to be related to Apple iPad and/or iPhone users who try to enter their information. Pretty weird! Anyone else who have experienced this? Maybe someone have a solution? Many thanks in advance! Sincerely, Andreas
  13. I have site that was written as a custom job several years ago. Part of the site uses authorize.net allowing new customers to register and buy products online. It is all php/mysql. There is no framework involved. Most of the code is 3 - 5 years old. I am starting to go through it as we are migrating it to a new hosting platform and I"m realizing there are some changes that need to be made. One glaring annoyance is that the buynow.php page which is where people register and buy stuff has a link to enter a coupon code. The link takes the user to a new page with a simple form to enter a coupon code. Once the code is entered and the user hits submit, the code is validated and if all is well, the user is taken back to the buynow.php page. The only problem is that the user has entered a bunch of data (name, address, email etc..) and then got to the coupon code link, clicked it, came back to buynow.php, and the form is empty again. What is the best way to keep the form data saved and repopulate the form with that data when the coupon code is entered? I think it may be better to change the coupon code logic so it happens on the same buynow.php page, and updates the price when the user hits and "apply coupon" button. I am a php novice - I have done programming before but it's been a while and it certainly wasn't php. I've been through lots of php tutorials and read a lot about it. I'm hoping I can get some guidance here so I can make these changes myself and turn it into a learning experience. Thanks Patrick buynow.php
  14. Hi everyone. I'm working on a simple app for internal use for a small company. I am having difficulties getting the account logins working correctly, and I believe it has something to do with $_SESSION not being set like I expected it to. Now I am fairly new to PHP, and have been learning as I go. index.php contains this: <?php session_start(); require_once('includes/config.inc.php'); require_once('includes/functions.inc.php'); // Check login status -- if not logged in, redirect to login screen if (check_login_status() == false) { redirect('login.php'); } So when I load the app, I'm redirected to login.php: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-type" content="text/html;charset=utf-8" /> <title>Login Page</title> <link rel="stylesheet" type="text/css" href="css/login.css" /> </head> <body> <form id="login-form" method="post" action="includes/login.inc.php"> <fieldset> <legend>Login to Inventory System</legend> <p>Please enter your username and password to access the Inventory system</p> <label for="username"> <input type="text" name="username" id="username" />Username: </label> <label for="password"> <input type="password" name="password" id="password" />Password: </label> <label> <input type="submit" name="submit" id="submit" value="Login" /> </label> </fieldset> </form> </body> </html> When I hit submit on the login page, includes/login.inc.php is called: <?php session_start(); require_once('config.inc.php'); require_once('functions.inc.php'); // Escape any unsafe characters before querying database $username = $con->real_escape_string($_POST['username']); $password = $con->real_escape_string($_POST['password']); // Construct SQL statement for query & execute $query = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . MD5($password) . "'"; $result = mysqli_query($con,$query) or die(mysqli_error($con)); // If one row is returned, username and password are valid if (is_object($result) && $result->num_rows == 1) { $_SESSION['logged_in'] = true; redirect('../index.php'); } else { redirect('../login.php'); } ?> Now I've been able to determine that the login is being processed successfully, because if I disable the check_login_status function in index.php, I'm redirected to index.php if I login with a valid account. Under the same conditions, an incorrect password will reload login.php. With the function disabled, I've also tried adding "print_r($_SESSION)" at the top of index.php, but nothing ever loads, which makes me think something is wrong with my function. functions.inc.php: <?php function redirect($page) { header('Location: ' . $page); exit(); } function check_login_status() { // IF $_SESSION['logged_in'] is set, return the status if (isset($_SESSION['logged_in'])) { return $_SESSION['logged_in']; } return false; } ?> config.inc.php: <?php $con=mysqli_connect("server_name","user","pass","db_name"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } ?> I'm really at a loss, and I don't know where the problem is. I've checked for syntax errors with "php -l file.php" and found no syntax errors. I'm not sure how to do any other debugging with this, or what I'm missing. Help is truly appreciated! EDIT: Yes, I know MD5 passwords are not recommended, and that will be changed to use salt once I can get functionality in my app. I will also be escaping/preparing all MySQL queries once I get the login piece working.
  15. hello, I am writing an application that stores values in a session. At the end of the session, the session variables are stored in the db, there is some magic with these data and then a result is generated after which the session is destroyed. Everything is running as expected but for one thing. When the session is destroyed, I get to another page (eg by mistakingly clicking on something) and then want to go back to the result, the result gets destroyed as well. This is not what I want, I want the users to be able to keep the result (which is a page containing about 1000 words). I'd prefer not to store the complete result (again: 1000 words) in the database or in a new session, because when things are up and running there may be hundreds of users using the app simultaneously. I thought it would be possible to create a new session after the previous one is destroyed and setting the db id connected to the stored variables in a session variable so that the result could be recalculated every time the user gets back to the page. I am in doubt is this is the best way to handle this. What would be the best way to handle this situation?
  16. Hi The following php code is to update values and pass it to the database . The problem is it's not updating the $lastlogin value and I can't see anything wrong with it, can anybody tell me what I'm doing wrong. Any help would be appreciated. public function login($postArray) { $jsonArr = array("status" => "unknown"); $username = $postArray['username']; $pass = sha1($postArray['password']); $ip = $_SERVER['REMOTE_ADDR']; $date = gmdate("Y-m-d H:i:s"); //login time $rowsNum = self::$dbConnection->rows_num("SELECT * FROM `users` WHERE `username`='$username' AND `password`='$pass'"); //successfully logged in if($rowsNum == 1) { //update the record self::$dbConnection->exec_query("UPDATE `users` SET `cur_ip`='$ip', `last_login`='$date' WHERE `username`='$username', `password`='$pass'"); //pull the information from the database $f = self::$dbConnection->query("SELECT * FROM `users` WHERE `username`='$username' AND `password`='$pass'"); $userid = $f['id']; $lastlogin = $f['last_login']; //set the login session $dataArray = array("userid" => $userid, "username" => $username, "lastlogin" => $lastlogin); //set status $jsonArr['status'] = "login_success"; $jsonArr['userdata'] = $dataArray; } else { //set status $jsonArr['status'] = "login_fail"; } return $jsonArr; }
  17. Hi guys, I am trying to pass an ID with a session to another page. -------- ID: 10 - edit link -------- ID: 11 - edit link -------- ID: 12 - edit link -------- The problem that I am having is that the session stored is always the last ID, in this case 12. $info["HostID"]; comes from the DB. <?php $link = $info["HostID"]; echo '<td><a href="edit.php?id='.$link.'">Edit</a></td>'; ?> <?php if(isset($_GET['$link'])){$_SESSION['hostid'] = $_GET['$link'];} ?> Any suggestions?
  18. Please the when ever i open signin.php which is the second code I get an error as a result "if($_SESSION['signed_in']) { echo 'Hello' . $_SESSION['user_name'] . '. Not you? <a href="signout.php">Sign out</a>'; } " in the first code saying that the variable _SESSION is undefined. Please what can i do about this? //header.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="description" content="A short Description." /> <meta name="keywords" content="put, keywords, here" /> <link rel="stylesheet" href="style.css" type="text/css" /> <title>PHP-MySQL Forum</title> </head> <body> <div id="wrapper"> <div id = "menu"> <a class="item" href="index.php">Index</a> <a class="item" href="create_topic.php">Create Topic</a> <a class="item" href="create_cat.php">Create Category</a> <?php echo '<div id="userbar">'; if($_SESSION['signed_in']) { echo 'Hello' . $_SESSION['user_name'] . '. Not you? <a href="signout.php">Sign out</a>'; } else { echo '<a href="signin.php">Sign in</a> or <a href="sign up">create an account</a>.'; } echo'</div>'; ?> </div> <div id="content"> <div id="footer">Created by Christech for Learning Only</div> </div> </div> </body> </html> <?php //signin.php include 'connect.php'; include 'header.php'; echo '<h3>Sign in</h3>'; //first, check if the user is already signed in. If that is the case, there is no need to display this page if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true) { echo 'You are alredy signed in, you can <a href="signout.php>Sign Out</a> if you wish"'; } else { if($_SERVER['REQUEST_METHOD'] != 'POST') { /*the form hasn't been posted yet, display it note that the action="" will cause the form to post to the same page it is on */ echo'<form method="post" action=""> Username: <input type="text" name="user_name" /> Password: <input type="text" name="user_pass" /> <input type="submit" value="Sign in" /> </form>'; } else { /* so, the form has been posted, we'll process the data in three steps: 1. Check the data 2. Let the user refill the wrong fields (if necessary) 3. Varify if the data is correct and return the correct response */ $errors = array(); /* declare the array for later use */ if(!isset($_POST['user_name'])) { $errors[] = 'The username field must not be empty.'; } if(!isset($_POST['user_pass'])) { $errors[] = 'The password field must not be empty.'; } if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/ { echo 'Uh-oh.. a couple of fields are not filled in correctly..'; echo '<ul>'; foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */ { echo '<li>' . $value . '</li>'; /* this generates a nice error list */ } echo '</ul>'; } else { //the form has been posted without, so save it //notice the use of mysql_real_escape_string, keep everything safe! //also notice the sha1 function which hashes the password $sql = "SELECT user_id, user_name, user_level FROM users WHERE user_name = '". mysql_real_escape_string($_POST['user_name']) ."' AND user_pass = '". sha1($_POST['user_pass']) ."'"; $result = mysql_query($sql); if(!$result) { //something went wrong, display the error echo 'Something went wrong while signing in. Please try again later.'; //echo mysql_error(); //debugging purposes, uncomment when needed } else { //the query was successfully executed, there are 2 possibilities //1. the query returned data, the user can be signed in //2. the query returned an empty result set, the credentials were wrong if (mysql_num_rows($result) == 0){ echo'You have supplied a wrong user/password combination. Please try again'; } else { //set the $_SESSION['signed_in'] variable to TRUE $_SESSION['signed_in'] = true; //we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages while($row = mysql_fetch_assoc($result)) { $_SESSION['user_id'] = $row['user_id']; $_SESSION['user_name'] = $row['user_name']; $_SESSION['user_level'] = $row['user_level']; } echo 'Welcome, ' . $_SESSION['user_name'] . '. <a href="index.php">Proceed to the forum overview</a>.'; } } } } } include 'footer.php'; ?>
  19. Could some one tell me how to use session variable across multiple domain. For example I have created a project in open cart. Need to pass the sessiion variables once user logged in same to another domain www.domain1.com www.subdomain1.com How to achieve this. please someone help me to do this using php
  20. Hi, I'm not sure if either I just have had a stupid error or what. Here is my code on the page with the functions for my script, which is called using require_once() on my other page. session_start(); function log_in($username, $password) { global $ss_con; $_SESSION['logged_in'] = 'true'; $_SESSION['username'] = $username; } This is the code for the other page that has require once... require_once('firstpage.php'); log_in(); if ($_SESSION['logged_in'] != 'true') { echo $_SESSION['logged_in']; echo 'fail!'; } The responce I get is "fail!" Don't worry about log_in() being set. I did that on another page on the same host that just forwards to this. Please help me!
  21. Hi, I am having trouble with this code and would like to see if anyone can help me. I have been trying to write a bit of code that would check in the database if the users role is either admin or something else. and then allow them to view the page or show a message stating "they are not the admin" Heres is the code. <?php require("head.php"); include("navbar.php"); require("common.php"); { $query = " SELECT id, username, password, salt, email, role FROM users WHERE username = :username "; $query_params = array( 'role' => $_POST['role'] ); $row = $stmt->fetch(); $_SESSION['role'] = $row; if($_SESSION["role"]=='admin'){ echo "<h1 class='container well'>YOU ARE IN!</h1>"; } else { echo "<h1 class='container well'>you need the admin role!!!!</h1>"; } } include("footer.php"); ?> I think I have mucked this up completely and might be writing the wrong thing? or I am missing a big chunk. Any help would be much appreciated.
  22. Hey guys if the user exits the browser will this code still run the user_logout.php ? Thanks session_cache_expire( 20 ); session_start(); // NEVER FORGET TO START THE SESSION!!! $inactive = 1200; //20 minutes *60 if(isset($_SESSION['start']) ) { $session_life = time() - $_SESSION['start']; if($session_life > $inactive){ header("Location: user_logout.php"); } } $_SESSION['start'] = time(); if($_SESSION['valid_user'] != true){ header('Location: ../....php'); }else{
  23. How can you run a query or a piece of code when a session ends or the user exits the browser with out logging out? Thanks. <?php session_start(); include('C:\inetpub\wwwroot\connect.php'); $provider_id = $_SESSION['provider_id']; $sql2 = "INSERT INTO provider_submits (provider_sub) values( '$provider_id')"; $result2 = sqlsrv_query($link, $sql2); exec('c:\\dblocal\\notes.bat'); ?>
  24. Hi everybody, I created a trivia game which lets the user answer questions. So far I have created a skeleton version of it. The problem I am having is my variables are not saving in an array - the way I would like them to. I have a session array created. Also if you are using it the questions aren't answered yet. Here is my code : <html> <head> <title>Trivia</title> </head> <?php //Hides non-harmful errors error_reporting(E_ALL ^ E_NOTICE); //Gets the content from the question text file $file = $_SERVER['DOCUMENT_ROOT'] . "/class/Assignment1/questions.txt"; $contents = file($file); //Session Start session_start(); $answerOne = $_POST['answerOne']; $answerTwo = $_POST['answerTwo']; $answerThree = $_POST['answerThree']; $answerFour = $_POST['answerFour']; $answerFive = $_POST['answerFive']; $answerSix = $_POST['answerSix']; //Declaring my session variables for answers/questions $_SESSION['answers'] = array($answerOne, $answerTwo, $answerThree, $answerFour, $answerFive, $answerSix); $_SESSION['contents'] = array($contents[0], $contents[1], $contents[2], $contents[3], $contents[4], $contents[5]); $answerArray = $_SESSION['answers']; $questionsArray = $_SESSION['contents']; //Declaring my variables $answer = "answerOne"; $text = "text"; $submit = "submit"; $questions = $questionsArray[0]; //If the button is clicked. if (isset($_POST['submit']) == true ){ $clickCount = intval($_POST['clickCount']); $clickCount += 1; $questions = $questionsArray[1]; //If the clickCount = 1 if($clickCount == 1){ $answer = "answerTwo"; //If the clickCount = 2 }if($clickCount == 2){ $answer = "answerThree"; $questions = $questionsArray[2]; //if the clickCount = 3 }if($clickCount == 3){ $answer = "answerFour"; $questions = $questionsArray[3]; //If the clickCount = 4 }if($clickCount == 4){ $answer = "answerFive"; $questions = $questionsArray[4]; //If the clickCount = 5 }if($clickCount == 5){ $answer = "answerSix"; $questions = $questionsArray[5]; //If the clickCount = 6 }if($clickCount == 6){ $text = "hidden"; $submit = "hidden"; $questions = ""; print_r($answerArray) . "<br />"; } } ?> <body> <form action="trivia1.php" method="post"> <input type="hidden" name="clickCount" value="<?php echo $clickCount; ?>"> <label><?php echo $questions; ?></label> <input type="<?php echo $text; ?>" name="<?php echo $answer; ?>"> <input type="<?php echo $submit; ?>" name="submit"> </form> </body> </html>
  25. I have a problem with my sessions and header redirects when I move my files from the local development machine to production server. Everything works well on the localhost but sessions cease to store data as required when moved to production. I have tried uploading to a different server to test whether it was a problem with how the other server was configured and it turns out I was right since the code works just as well as it did on my local development machine. Can anyone point out what pitfalls I might be overlooking. The system is a simple shopping cart that redirects shoppers to the previous page they came from to continue shopping or to check out immediately after adding the product details. I have attached the code. The buyer moves from: pricing.php -> wholesale.php -> addproduct.php then finally -> cart.php pricing.php wholesale.php addproduct.php cart.php
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.