PHP - Issue Using Session With Objects
I was told that using a Session will allow me to capture an Object and pass it between pages.
I tried following what I read online and what someone sugegsted but it is not working. This is the error I get when running my test application... Quote Catchable fatal error: Argument 1 passed to Microwave::receiveItem() must be an instance of Bowl, instance of __PHP_Incomplete_Class given, called in /Users/user1/Documents/DEV/++htdocs/Soup/cook.php on line 13 and defined in /Users/user1/Documents/DEV/++htdocs/Soup/classes/Soup.class.php on line 31 Call Stack # Time Memory Function Location 1 0.0095 56412 {main}( ) ../cook.php:0 2 0.0101 68272 Microwave->receiveItem( ) ../cook.php:13 I would really appreciate it if someone could look at my code and see where the problem is at. My guess is that it is in cook.php, but who knows?! Attached is a ZIP of my entire directory structure. Thanks, TomTees Similar TutorialsI have a page in which the print_r ($session) displays the following: Array ( [securityToken] => 23b1f22bffd9f5097878618da57b14a2 [cartID] => [cart] => shoppingCart Object ( [contents] => Array ( ) [total] => 0 [weight] => 0 [cartID] => [content_type] => [free_shipping_item] => 0 [free_shipping_weight] => 0 [free_shipping_price] => 0 ) [navigation] => navigationHistory Object ( [path] => Array ( [0] => Array ( [page] => index [mode] => NONSSL [get] => Array ( [cPath] => 2_9_843_845_852_856_858_863 ) [post] => Array ( ) ) [1] => Array ( [page] => product_info [mode] => NONSSL [get] => Array ( [cPath] => 2_9_843_845_852_856_858_863 [products_id] => 2299 [action] => add_product ) [post] => Array ( ) ) [2] => Array ( [page] => shopping_cart [mode] => NONSSL [get] => [post] => Array ( ) ) [3] => Array ( [page] => checkout_shipping [mode] => NONSSL [get] => [post] => Array ( ) ) [4] => Array ( [page] => checkout_payment [mode] => NONSSL [get] => [post] => Array ( ) ) [5] => Array ( [page] => checkout_confirmation [mode] => NONSSL [get] => [post] => Array ( ) ) [6] => Array ( [page] => checkout_process [mode] => NONSSL [get] => [post] => Array ( ) ) [7] => Array ( [page] => checkout_success [mode] => NONSSL [get] => [post] => Array ( ) ) ) [snapshot] => Array ( ) ) [check_valid] => true [language] => english [languages_id] => 1 [languages_code] => en [currency] => USD [today_is] => 2010-11-26 [updateExpirations] => 1 [session_counter] => 1 [new_products_id_in_cart] => 2299 [valid_to_checkout] => 1 [cart_errors] => [customer_id] => 2 [customer_first_name] => test [customer_default_address_id] => 2 [customer_country_id] => 223 [customer_zone_id] => 2 [customers_authorization] => 0 [messageToStack] => [payment_attempt] => 1 ) What I need to do is loop through the navigationHistory Object , grab the product id, and then get the cPath for that particular product id. I have worked with sessions a lot, but I cannot seem to ever get the session object and loop thing down. At this point I am ripping out my hair trying to figure out what is most likely a simple solution to this - can anyone help me? Hello all!
I have this array of objects:
Array ( [0] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => p@yahoo.com [date] => 2014-09-21 07:23:12 [status] => 2 [approval_date] => 2014-09-21 07:31:10 [assessment_id] => 1 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-21 07:31:27 [mainmanger] => 3 ) [1] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => p@yahoo.com [date] => 2014-09-20 07:39:55 [status] => 2 [approval_date] => 2014-09-20 07:40:41 [assessment_id] => 3 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-20 07:41:07 [mainmanger] => 3 ) [2] => stdClass Object ( [first_name] => jimmy john john [last_name] => john [title] => Lorad and Master [id] => 32 [type] => 4 [manager] => 3 [email] => j@j.com [date] => 2014-09-21 07:38:50 [status] => 2 [approval_date] => 2014-09-19 07:39:25 [assessment_id] => 2 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-19 07:39:25 [mainmanger] => 0 ) )Where "id" = the user ID. If there are two or more entries for a user, I want to remove all but the most recent by the "approval_date",... So for the above example it would return: Array ( [0] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => piznac@yahoo.com [date] => 2014-09-21 07:23:12 [status] => 2 [approval_date] => 2014-09-21 07:31:10 [assessment_id] => 1 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-21 07:31:27 [mainmanger] => 3 ) [1] => stdClass Object ( [first_name] => jimmy john john [last_name] => john [title] => Lorad and Master [id] => 32 [type] => 4 [manager] => 3 [email] => j@j.com [date] => 2014-09-21 07:38:50 [status] => 2 [approval_date] => 2014-09-19 07:39:25 [assessment_id] => 2 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-19 07:39:25 [mainmanger] => 0 ) )I'm having a hard time wrapping my head around this concept, so I don't have any example code. And I don't really need or expect someone to code this for me,. just a push in the right direction would be awesome. I'm using the PHPmotion script, with a use-a-credit to view-a-video mod. When the user logs out, the viewed video should not be available again to view, until he logs back in and chooses it chooses it, via a credit, but it is still available when he logs back in. Any ideas on what file may be responsible for what I guess you could call 'clearing the session'? I'm having an issue with sessions and session_set_save_handler. Note: new at OO PHP I'm using an MVC written mostly from a tutorial and it all seems to be working, except for sessions. I've got session_set_save_handler as a class SessionHandler. If I include it into the main index page and create an instance, I get an error 'Undefined variable: _SESSION' for my index view file. If I instead include a global.php file into the main index page and include the session class into the global.php page, and create an instance, the error goes away and session_set_save_handler saves the session variables into my database. (1)On my index page for debugging I've got a var_dump of $_SESSION to see which session variables are set. On my login page I've got a form token that is saved to a session variable. When I go to the login page that session token variable is set and doing a var_dump on the page shows it is indeed being set, however, when I click back to the main index page, the index var_dump(1) shows the session variable is no longer set. But then if I login it correctly redirects me to a user logged in page and echos the username of the user logged in correctly, but still does not show the form token session variable in the var_dump for index(1). But then if I navigate to the login form page where the form token should be initially set, it now sets it correctly and going to the index page indeed shows the token set. form token being set on login view page: Code: [Select] $login_token = $_SESSION['login_token'] = md5(uniqid(mt_rand(),true)); var_dump on index page before login (even if I navigate to login page then back to index it remains blank when it should instead show the form token session variable) Code: [Select] array empty var_dump on index page after login. Code: [Select] array 'lu_user' => string 'admin' (length=5) 'lu_user_id' => string '6' (length=1) 'user_sess_time' => int 1326544148 var_dump on index page after login, navigating to login form page (where login_token is set), then navigating back to index: Code: [Select] array 'lu_user' => string 'admin' (length=5) 'lu_user_id' => string '6' (length=1) 'user_sess_time' => int 1326544148 'login_token' => string 'c260e76dd65f0d9b6e881cfc9a4b33e1' (length=32) Magically the login_token now shows, but only after logging in and setting the other variables. It seems it's not saving the login_token when it's initially set, but only after logging in which it shouldn't be doing. The same issue arises with any other session variables that I set elsewhere (only displayed after user login). If I remove session_set_handler the sessions set correctly but naturally the data is no longer added to the database. If I do var_dump(get_included_files()); it shows the session class is correctly being included. I was thinking it's an issue with session_start() but if I add that in or try to create another instance of the session class on the other pages, I get an error stating they've already been called and cannot be called again. So then they must be getting called, right? So now I'm thoroughly confused. More code below, sorry for the long post. Hopefully I've provided all necessary information. Index includes global.php, which contains: Code: [Select] require 'framework/SessionHandler.php'; $sess = new SessionHandler(); And the session handler class is (Database class is included into index which is why you cannot see it instantiated here): Code: [Select] <?php class SessionHandler { function __construct() { session_set_save_handler ( array(&$this, 'open'), array(&$this, 'close'), array(&$this, 'read'), array(&$this, 'write'), array(&$this, 'destroy'), array(&$this, 'gc') ); session_start(); ini_set('session.gc-maxlifetime', 1800); if (isset($_SESSION['lu_user'])) { if (!isset($_SESSION['user_sess_time'])) { $_SESSION['user_sess_time'] = time(); } elseif (time() - $_SESSION['user_sess_time'] > 1800) // 30 mins { session_regenerate_id(TRUE); $_SESSION['user_sess_time'] = time(); } } } function open() { $this->db = new Database(); } function close() { return $this->db = null; } function read($id) { $stmt = $this->db->prepare('SELECT * FROM sessions WHERE id = :id'); $stmt->execute(array(':id' => $id)); if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { return $data = $row['data']; } else { return ''; } } function write($id, $data) { $access = time(); if (isset($_SESSION['lu_user'])) { $session_id = session_id(); $username = $_SESSION['lu_user']; $stmt = $this->db->prepare('REPLACE INTO sessions (id, access, data) VALUES (:id, :access, :data)'); $stmt->execute(array(':id' => $id, ':access' => $access, ':data' => $data)); } } function destroy($id) { if (ini_get("session.use_cookies")) { $params = session_get_cookie_params(); setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]); } $stmt = $this->db->prepare('DELETE FROM sessions WHERE id = :id'); $stmt->execute(array(':id' => $id)); } function gc($max) { $old = time() - $max; $stmt = $this->db->prepare('DELETE FROM sessions WHERE access < :old'); $stmt->execute(array(':old' => $old)); } function __destruct() { session_write_close(); } } Hi All, I'm running trying to add key and values to an array on multiple pages, but it seems to override the array each time I add variables on the next page, even though the keys are different. Each page has something like this: Code: [Select] <label class="yes"><input type="radio" name="form_field[<?php echo "number".$f1; ?>]" value="0" > Yes</label> <label class="no"><input type="radio" checked="checked" name="form_field[<?php echo "number".$f1; ?>]" value="1" > No</label> <label class="unsure"><input type="radio" name="form_field[<?php echo "number".$f1; ?>]" value="2" > Unsure</label> I then collect it as well as other page variables with: Code: [Select] session_start(); foreach($_POST as $name => $value) { $_SESSION[$name] = $value; } on all following pages. But rather than adding to the array it writes over it each time. Any ideas on what's going wrong here. Should the array simply be able to continue to collect the keys or do I need to do something else? Thanks. Hi guys i've spent 3 whole days trying to get this to work but it dosent. My issue is very similar almost the same as: http://www.phpfreaks.com/forums/index.php?topic=296100.15 but with the code i have. Basically i have custom member pages. member1.php member2.php the design and content will be custom to each member, they also have their own login page. Each member should be able to access their page and simply view their secure area. They should not be able to log into another users area if they dont have the username or password for it. Now the problem is, i have this entire script setup and it works, however i fear there is something wrong with the sessions which allows other members to access other members pages with their own passwords and usernames because they share the same database. So the script executes thinking its a valid user and lets them in. Here is my login checker once the user is validated they are sent to their own folder header("Location: ../{$loginusername}/index.php"); and are able to view the page. Code: [Select] <?php require_once('../config.php'); // Connect to the server and select the database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db")or die("Unable to select database"); // The username and password sent from login.php $loginusername=$_POST['username']; $loginpassword=$_POST['password']; //The following bit of coding protects from MySQL injection attacks $loginusername = stripslashes($loginusername); $loginpassword = stripslashes($loginpassword); $loginusername = mysql_real_escape_string($loginusername); $loginpassword = mysql_real_escape_string($loginpassword); $sql="SELECT * FROM $tbl WHERE username='$loginusername' and password='$loginpassword'"; $result=mysql_query($sql); // Count how many results were pulled from the table $count=mysql_num_rows($result); // If the result equals 1, continue if($count==1){ session_start(); $_SESSION["loginusername"] = $loginusername; $_SESSION['user1'] = $username; // store session data //echo "User: = ". $_SESSION['loginusername']; //retrieve data header("Location: ../{$loginusername}/index.php"); } // If not successful, inform the user of error else { echo "Wrong Username or Password"; } ?> Now here is the secure page sample: Code: [Select] <?php session_start(); if (!$_SESSION['user1']){ header("Location: login.php"); }else{ print "its working!"; } ?> <html> <body> Login Successful for </body> </html> For each login page i have given each user it's own session.. this works, however if user1 logs in and simply changes the url to user2 and enters his user2 password he is granted access giving him new sessions which means he has access to everything. Im pretty sure im missing something really small any help would be appreciated. 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?
About to pull my hair out. Looks simple, I think it's simple, but something is not behaving. I have a simple login page (loginpage.php) which checks a database for the FamilyID and Password, if it is a match, then it redirects them to userspage.php. I eventually want to use the FamilyID as a filter for my database so I only show the stuff relative to that FamilyID. Using CS5 and the built in functions, and it looks to me that the session variable 'MM_Username' should contain the FamilyID which is "adminid" in my database. It appears to work since it sends me to my userspage.php when I enter a valid FamilyID and Password, but it will not show me my session variable on the that page!!! PLEASE PLEASE HELP...Slap me in the face if it's a stupid question, but I have spent WAY too much time trying to figure what is wrong. I have included my code: CODE FOR LOGINPAGE.PHP <?php require_once('Connections/MyTest.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } ?> <?php // *** Validate request to login to this site. if (!isset($_SESSION)) { session_start(); } $loginFormAction = $_SERVER['PHP_SELF']; if (isset($_GET['accesscheck'])) { $_SESSION['PrevUrl'] = $_GET['accesscheck']; } if (isset($_POST['familyid'])) { $loginUsername=$_POST['familyid']; $password=$_POST['password']; $MM_fldUserAuthorization = ""; $MM_redirectLoginSuccess = "userspage.php"; $MM_redirectLoginFailed = "loginpage.php"; $MM_redirecttoReferrer = false; mysql_select_db($database_MyTest, $MyTest); $LoginRS__query=sprintf("SELECT adminid, password FROM `admin` WHERE adminid=%s AND password=%s", GetSQLValueString($loginUsername, "int"), GetSQLValueString($password, "text")); $LoginRS = mysql_query($LoginRS__query, $MyTest) or die(mysql_error()); $loginFoundUser = mysql_num_rows($LoginRS); if ($loginFoundUser) { $loginStrGroup = ""; if (PHP_VERSION >= 5.1) {session_regenerate_id(true);} else {session_regenerate_id();} //declare two session variables and assign them $_SESSION['MM_Username'] = $loginUsername; $_SESSION['MM_UserGroup'] = $loginStrGroup; if (isset($_SESSION['PrevUrl']) && false) { $MM_redirectLoginSuccess = $_SESSION['PrevUrl']; } header("Location: " . $MM_redirectLoginSuccess ); } else { header("Location: ". $MM_redirectLoginFailed ); } } ?> <!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" /> <title>Untitled Document</title> </head> <body> <form id="form1" name="form1" method="POST" action="<?php echo $loginFormAction; ?>"> <p> <label for="familyid">FamilyID:</label> <input type="text" name="familyid" id="familyid" /> </p> <p> <label for="password">Password:</label> <input type="text" name="password" id="password" /> </p> <p> <input type="submit" name="Submit" id="Submit" value="Submit" /> </p> </form> </body> </html> CODE FOR USERSPAGE.PHP <?php if (!isset($_SESSION)) { session_start(); } ?> <!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" /> <title>Untitled Document</title> </head> <body> <strong>YOU MADE IT! </strong> <?php echo $_SESSION['MM_Username']; ?> </body> </html> THANKS IN ADVANCED!!! Hi Everyone I have a weird session issue going on and i'm not sure what is causing it. Basically any sessions that i set are randomly expiring sooner than they should be. As a test I did the following: Code: [Select] <?php session_start(); if(isset($_SESSION['views'])){ $_SESSION['views'] = $_SESSION['views']+ 1; }else{ $_SESSION['views'] = 1; } echo "views = ". $_SESSION['views']; echo '<p><a href="testpage.php">Refresh</a></p>'; ?> If i continue to click the refresh button, i sometimes get to 30 and then it starts at 1 again. Other times ill get to 20 and then back to 1. It has also sometimes skips a couple of counts from 7 to 11 as an example in one click. Any one come across this before? I have been reading up online and some have mentioned PHP upgrades from php4 to php5 cause some issues and specifically the hosting company changing the session.save_path. If this was the case, it wouldn't even count to 10, would it? Any help would be really appreciated. thanks in advance 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 I am createing a simply quiz site, where in order to participate in the quiz, you must first be logged in. While working on my local machine, the code works perfectly. I use the followin to create a session ID; $_SESSION['SESS_ID'] = $member['id']; Then, on my main page where i want dynamic code i include the following; if(!isset($_SESSION['SESS_ID']) || (trim($_SESSION['SESS_ID']) == '')) { print (" <div style='float:left; width:400px; height:215px; margin-left:500px;'> <form class='login' method='post' action='login-form.php' style='float:right; margin-top:120px;' > <input type='submit' class='button' name='submit' value='Sign In' style='float:right ; margin-right:20px;'> </form> <p style=' margin-top:170px; margin-left:160px;'>New Member? Start <a href='register-form.php'>Here</a></p> </div> " ); } else { print "<h4 style='float:right; text-align: right; margin-top:150px; margin-right:50px;'>Welcome ". $_SESSION['SESS_NAME']. " <a href='logout.php' style='float:right; text-align:right;'>Sign Out</a></h4> "; For some reason, when the site is on the server, the session ID does not seam to get passed along. Any Ideas how to remediy this? the website is kingdomquiz.com if anybody is interested. I have a website uploaded onto Host Gator hosting and the sessions are carried over to the other pages ok. When using the same website in XAMPP it does not carry over the session to the next page and need to login again. If i log in it puts the following after the URL - ?sid=3b71942d410d84c45f9f4433561c325a The when i go to another link it loses the sid and i'll need to manualy past it into the next URL to get it working unless i log in again on the new page. This is only happening with XAMPP but working fine in the Host Gator hosting environment. Please help! My login is integrated with the phpbb3 login. This is the code at the beginning of every page - Code: [Select] <?php ob_start(); define('IN_PHPBB', true); $phpbb_root_path = './phpbb3/'; $phpEx = substr(strrchr(__FILE__, '.'), 1); include($phpbb_root_path . 'common.' . $phpEx); // Start session management $user->session_begin(); $auth->acl($user->data); $user->setup(); ?> I have the following three tables (and also delta_point and hist_point which are purposely left out and just mentioned for context). Before going down the Doctrine ORM long curvy road, aggrType was just used to restrict possible values so that I didn't need to use MySQL's ENUM, but now I am thinking there may be value to making it an entity and include some methods (and a second reason because I still can't figure out how to make Doctrine create a FK constraint yet not populate the parent entity with a AggrType object). point -id (int PK) -data -dType /* descriminator. Options are AggregatePoint, DeltaPoint, and HistoricPoint */ aggr_point -id (int PK, FK to point) -aggrType (char FK to aggrType) -data aggrType -type (char PK) /* there are about five types */ I have a service to create a new point based on the provided desired type and user data. I don't like the switch statement to determine which type of point to create, but don't know a better way. Also my entity is responsible to provide the appropriate validation rules for the given point type which might not be considered proper but it seems to work for me. Any constructive criticism is welcomed. <?php namespace NotionCommotion\PointMapper\Api\Point; use NotionCommotion\PointMapper\Domain\Entity\Point; class PointService { public function create(string $type, array $params):integer { $class=[ 'aggr'=>'AggregatePoint', 'delta'=>'DeltaPoint', 'hist'=>'HistoricPoint', ][$type]; //$class='Point\\'.$class; //This doesn't seem to be possible and I needed to use the fully qualifed name without the short cut used namespace. $class='\\Greenbean\Datalogger\Domain\Entity\Point\\'.$class; $point=new $class(); $validator=$this->getValidator($point); $params=$validator->sanitize($params); $validator->validate($params); $point->setAccount($this->account); $point->populate($params, $this->em); //Will be addressed later $this->em->persist($point); $this->em->flush(); $point->setIdPublic($this->em->getRepository(Point\Point::class)->getPublicId($point->getId())); return $point->getIdPublic(); } } Now, this is the part I am struggling with the most. I only have one service to create any type of point, so I do wish to put a bunch of if/thens in it and instead move logic to the individual point type being created. The AggrPoint in question requires a sub-point and I don't think it is appropriate to inject the entity manager into a point entity and as an alternative solution find an existing point which is associated with the account which resides in the new AggrPoint. Maybe not appropriate, but it works. This type of point also has a sub-object AggrType as discussed at the very beginning of this post, so I first attempt to create a new one from scratch, but that doesn't work and I need to set $aggrType with an existing one. As an alternative, I passed the entity the entity manager, but as stated I think this is a bad idea. Any recommendations where to go from here? Thank you namespace NotionCommotion\PointMapper\Domain\Entity\Point; class AggregatePoint extends Point { public function populate(array $params, \Doctrine\ORM\EntityManager $em):\NotionCommotion\PointMapper\Domain\Entity\Entity{ $criteria = \Doctrine\Common\Collections\Criteria::create() ->where(\Doctrine\Common\Collections\Criteria::expr()->eq("id_public", $params['pointId'])); if(!$subpoint = $this->getAccount()->getPoints()->matching($criteria)->current()){ throw new \Exception("Invalid subpoint ID $params[pointId]"); } $this->setSubpoint($subpoint); //This won't work since I must use an existing AggregateType and not create a new one $aggrType=new AggregateType(); $aggrType->setType($params['aggrType']); //This just seems wrong and I shouldn't be passing the entity manager to an entity $aggrType=$em->getRepository(AggregateType::class)->findOneBy(['type'=>$params['aggrType']]); $this->setAggregateType($aggrType); unset($params['pointId'], $params['aggrType']); // parent::populate($params) not shown, but it basically calles appropriate setters based on the property name return parent::populate($params); } public function getValidatorRules():array { return $this->filesToArr(['/point/base.json', '/point/aggr.json']); } }
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! 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 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. 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. |