Hey I'm new to php need help creating anew page per user. I have a user login and registration system already. I also have a profiles.php page but, how can I let the website make an automatic webpage for every new user.
Whenever I try to connect it through $_GET or $_POST I get an Undefined index error.
include ("includes/profiles.dbh.inc.php");
$requested_user = $_POST['mailuid'];
try{
$stmt2 = $conn2->prepare("SELECT * FROM profile WHERE id = ?");
$stmt2->execute(array($requested_user));
$mydata = $stmt2->fetch();
} catch (Exception $e) {
//error with mysql
die();
}
I've seen this question come up a few times. One of the first things you need to consider is how is the user going to interact with this page.
Are they going to access it via links? http://example.com/index.php?user=1
Or are they going to submit a form via post? http://example.com/index.php
This distinction is important because it changes the way you handle their request.
Let's look at each one:
Via a link: http://example.com/index.php?user=1
This will issue a get request to your server so you need to handle it via $_GET.
if (isset($_GET['user'])) {
$userId = $_GET['user'];
// ... query your DB and output result
}
Via a form using post: http://example.com/index.php (body with contain "user=1").
This will issue a post request to your server so you need to handle it via $_POST
if (isset($_POST['user'])) {
$userId = $_POST['user'];
// ... query your DB and output result
}
On a side note, it is important to know that an HTML <form> can submit either a post or get request. You can control this via it's method attribute. If you don't specify the method attribute, then it defaults to get.
<form method="post">
...
</form>
<form method="get">
...
</form>
So, to answer your question. You're likely getting an undefined error because you're trying to access the post array using the key mailuid ($_POST['mailuid']) but that does not exist. It doesn't exist because:
you're receiving a get request and the post is empty OR
you are receiving a post request but it doesn't contain the key mailuid
To debug, go back to the basics - use $_GET
Change your code to use $_GET['mailuid'] and then make sure you access your page with the corresponding query string - ...?mailuid=1.
Finally, turn on error reporting - https://stackoverflow.com/a/5438125/296555. You should always do this and correct all errors and warnings.
I am trying to read the id of a user from the database when they log in, and save it to a variable to used in other programs for later. my table for the users is such
addressBookUsers
[
userid int(11) PK AUTO_INCREMENT;
firstName;
LastName;
email
]
with some dummy data
userid username password
1 fred 12ewerefds2
2 al 343ed3fe
this is the code in which i use the username to get the user id and store into a variable
<?php
session_start();
include("dbconnect.php");
$con= new dbconnect();
$con->connect();
//create and issue the query
$id = "SELECT userid FROM addressBookUsers WHERE username = '".$_POST["username"]."'";
$userid = mysql_query($id);
while($row = mysql_fetch_array($userid)) {
$me = $row[0]}
$se=$me;
echo($se)
?>
this returns the correct user id however when i try to call $se in another php file to see if it has saved i dont get a resul
test.php
<?php
include ("userloginses.php");
echo $se;
?>
i am unsure why $se which is a int does not get passed to test.php
any help?
and yes there are some html from stuff not included, but that is not related to the problem at hand
You're doing it wrong. You have sessions so use them:
$_SESSION['se'] = $me;
and then test.php would look like this:
<?php
session_start();
include ("userloginses.php");
echo $_SESSION['se'];
?>
You can refer any PHP variable like this. If you want to use preserved value of PHP variable or even any web language you must save it in to SESSION or COOKIE. In user login case, you should use SESSION variable. In your code start session and instead of $e define $_SESSION['e'] and access it any php script of your directory. Don't forget to start session using session_start() in first line of your each and every php script where you want to access this variable.
i have a callback page, that i am using to insert data in a db. when i load this page. and echo $_SESSION['user_id']. it echos the user_id, and inserts it into the db. however when i am trying to insert the data while doing the callback function, the $_SESSSION['user_id'] is ignored and the other data is succesfully inserted. why is this?
echo $_SESSION['user_id'];
$decodedJSON = json_decode(file_get_contents('php://input'), true);
$account = $decodedJSON['account'];
$query_insert = "insert into video (account,userid) values ($account,$_SESSION['user_id'])";
$result_insert = mysql_query($query_insert);
When i refresh the page, $_SESSION['user_id'] is inserted. But when i try to run the callback function, $account is inserted, but $_SESSION['user_id'] is not.
I'm not 100% sure of how this all fits together with your code sample, but if you're trying to pass somethign to stanard input and then run the PHP, you also need to pass the sessionID.
When you call the code from your borwser, cookies magically handle all that for you, and the sessions ID is passed in a cookie. But if you're calling from another source, cookies are not passed.
I could explain how to do it, but nothing better than the PHP manual: http://php.net/manual/en/session.idpassing.php - basically append the SID to the end of hte URL.
But note the comment about "session.use_trans_sid" which is disabled by default and needs to be enabled in php.ini
I have 2 php pages: query.php and result.php.
In query.php, I am executing a query (select) statement. It's returning a resultset
$rs = mysql_query($query);
Now I want to return this resultset from query.php to another page result.php and work with it. Like this:
In query.php:
return $rs
and in result.php:
$result = executeQuery($query) // we get the resultset in this variable
while ($row == mysql_fetch_array($result){
//do something
}
If the above is not recommended, please provide me with alternatives. But I want the query function and resultset in different pages.
You could just include results.php in your query.php page if you're just looking to keep the code separate in the source files but aren't actually required to redirect from one page to another:
In query.php:
$rs = mysql_query($query);
include "results.php";
In results.php:
while ($row == mysql_fetch_array($rs){
//do something
}
As far as trying to "return $rs" from one page to another that's not how PHP works. The return statement is only valid within a function. If you want to actually pass data from one PHP page to another and will be redirecting to that other page then you'll need to use either a session, a cookie, pass it in the URL (i.e. use GET) or use curl and add it as a POST var.
If this is really the way it must be, store the result set in a database somewhere or in a file and give each result a unique name. Then pass that name to the next page so it can be retrieved.
query.php will redirect to result.php?result_set=ab24sdfsdfklls for instance.
This has the added advantage that you can use the result_set as often as you want. Visitors can have multiple result sets during one visit. They can share the URL of the result set page with other people, etc.
Just be sure to eventually prune the data store as it will just keep on growing, but that's another matter entirely.
I heard the best method to share session across multiple domains on same server is to use custom php session handler. (ie, domain name different like abc.com, xyz.com but single application.)
But after i tried it, even custom php session handler that using SAME DATABASE ON 1 SERVER can't share session, when i tried to read cookie value from different domain.
Here's my custom session handler, Please kindly check or fix if something missing here. because i've tried it for a week now. can't get it to work
P.S. To get previous session id, i use link such as: newdomain.com/?ssid=[SESSION_ID]
SESSION_INCLUDE.PHP
<?php
// config
$m_host = "localhost"; //MySQL Host
$m_user = "db_user"; //MySQL User
$m_pass = "db_pass"; //MySQL Pass
$m_db = "db_name"; //MySQL Database
$table = "sess_data";
$session_expire = 600; // Session expire time, in seconds (minutes * 60 = seconds)
$gc_probability = 100; // Probability that the garbage collection function will be called. 50% chance by default
ini_set("session.gc_probability",$gc_probability);
/* Open function; Opens/starts session
Opens a connection to the database and stays open until specifically closed
This function is called first and with each page load */
function open ($s,$n) // do not modify function parameters
{
global $session_connection, $m_host, $m_user, $m_pass, $m_db;
$session_connection = mysql_pconnect($m_host,$m_user,$m_pass);
mysql_select_db($m_db,$session_connection);
return true;
}
/* Read function; downloads data from repository to current session
Queries the mysql database, unencrypts data, and returns it.
This function is called after 'open' with each page load. */
function read ($id) // do not modify function parameters
{
global $session_connection,$session_read,$table;
$query = "SELECT data FROM `$table` WHERE id=\"{$id}\"";
$res = mysql_query($query,$session_connection);
if(mysql_num_rows($res) != 1) return ""; // must return string, not 'false'
else
{
$session_read = mysql_fetch_assoc($res);
$session_read["data"] = base64_decode($session_read["data"]);
return $session_read["data"];
}
}
function write ($id,$data) // do not modify function parameters
{
if(!$data) { return false; }
global $session_connection, $session_read, $session_expire, $table;
$expire = time() + $session_expire;
$data = mysql_real_escape_string(base64_encode($data));
if($session_read) $query = "UPDATE `$table` SET data=\"{$data}\", expire=\"{$expire}\" WHERE id=\"{$id}\"";
else $query = "INSERT INTO sess_data SET id=\"{$id}\", data=\"{$data}\", expire=\"{$expire}\"";
mysql_query($query,$session_connection);
return true;
}
function close ()
{
global $session_connection;
mysql_close($session_connection);
return true;
}
function destroy ($id) // do not modify function parameters
{
global $session_connection,$table;
$query = "DELETE FROM `$table` WHERE id=\"{$id}\"";
mysql_query($query,$session_connection);
return true;
}
function gc ($expire)
{
global $session_connection,$table;
$query = "DELETE FROM `$table` WHERE expire < ".time();
mysql_query($query,$session_connection);
}
// Set custom handlers
session_set_save_handler ("open", "close", "read", "write", "destroy", "gc");
// Start session
session_start();
?>
MySQL Database Description
create table sess_data (
id2 int not null auto_increment,
id text not null,
data text,
expire int not null,
primary key(id2)
);
You can't read cookies from one domain in another domain. That's a security thing implemented in the browser. Using a database for sessions allows you to have multiple servers share sessions on the same domain, but does not allow for multiple domains on the same server to share sessions.
If you want to share sessions between domains, you would need to implement some sort of session transfer method when you switch domains. The simplest way to do this would involve passing the session id as a GET parameter from a page on one domain to a page on the other. Then, on the other domain, you would pick up the session id and create a new session using that ID.
While that is a simple way to do it, it isn't very secure and allows for session hijacking. A better way would be to use the database to create a record with the session id in it, set a short timeout on it, and pass the ID of that record to the other domain. The other domain would then pick up the record from the database and create a session with it. If the record in the database is past it's expiration, it wouldn't pick up the session. This would provide better protection against session hijacking.
This is the purpose of session_name(). Assign a different name to each application's session to avoid collisions between $_SESSION keys. The name will be used as the session cookie's name so although both session cookies will be passed to both applications, only the one matching the application's session_name() will be used to populate $_SESSION.
// App 1
session_name('app1');
session_start();
// App 2
session_name('app2');
session_start();
You really should look into SSO (single sign-on). One option for SSO is to use OpenID (as used on SO), and using it will make your life a lot easier.
Here's an article on it : http://devzone.zend.com/article/3581
the cookies and their visibility is a problem. The browser accessing the new site would not send the session id of the old site to the server.
I think your read() does not use the ssid parameter you provide as session id but as the browser has no session with this domain the system generates one with new id as $id. Have a look if $_REQUEST['ssid'] exist in the database.
Custom session handler might a bit big for this job. You could just check if $_REQUEST['ssid'] exist in the session database and rewrite $_SESSION with it.
I was wondering if anyone could give some suggestions on my method for sharing sessions between domains on same server (same cookie storage folder).
In each pages HEAD tag on all my sites, I call the following PHP code
if(!isset($_SESSION['sso'])) {
require_once('database.php');
$sites = array('http://site1', 'http://site2');
session_regenerate_id(); //Make new session id that will be shared
$session_id = session_id();
foreach($sites as $site) {
if($site != CURRENT_SITE) {
$sesh_key = md5(SALT.$site.$session_id);
$database->insertSessionId($sesh_key, $session_id);
$url = sprintf('%s/sso_set.php?k=%s', $site, $sesh_key);
echo('<link type="text/css" rel="stylesheet" href="'.$url.'" />');
}
}
$_SESSION['sso'] = 'SET';
}
Then on each site I have a file called 'sso_set.php' which contains
<?php
session_start();
if(!isset($_SESSION['sso'])) {
require_once('database.php');
$key = $_GET['k'];
$session_id = $database->getSessionId($key);
if($session_id) {
session_destroy();
session_id($session_id);
session_start();
$database->deleteSessionId($key);
$_SESSION['sso'] = 'SET';
}
}
Is using a text/css link a good idea?
I figured this is always called even if Javascript or Images are disabled?
This code basically makes the first site out of all my sites that gets opened by the user sets the Session ID, and then passes it on to the other sites.
Seems to work pretty well.
You get a slight delay the very first time any of the sites opened and the ID is passed to the sites. But, you could do this via AJAX so the page loads fast. But, then you rely on Javascript being enabled.
Thoughts?