Subject Re: [firebird-php] Connecting to a db with a specific role
Author soumya parida
I have attached a copy of the main script that runs our surfbar.
please have a look at it and
suggest,
in general terms, how you would optimise it to make it more efficient
and
reduce load on the database.
This script runs every 20 seconds for every user. The database, which
runs
on it's own new dedicated dual Xeon, 4GB RAM, directly connected
server,
falls behind with selects and updates when we have over 1,000 users
surfing.


shann0n110yd <sjlloyd@...> wrote:


Hi,
I'm trying to implement a user login facility, but am having trouble
getting my users to connect using roles. I've created two roles for my
db - a USERS role and an ADMIN role. I then created a number of users
and gave each of them membership of the USERS role. I then call
ibase_connect twice - the first time using "ADMIN" as the role, and
the second time using "USERS" as the role, the theory being that if
the first connection succeeds, my function is designed to return
immediately (after setting a session variable indicating admin
privileges), and if the connection does not succeed, it goes on to
attempt to connect as a regular user. The problem I am having is that
all users are being permitted to connect with the ADMIN role, even
though they have only been granted membership of USERS.
The specific piece(s) of code is/are as follows:

function getConnection ($user, $pass, $role)
{
$host = 'localhost:C:\firebirdsql\db\thedatabase.fdb';
if ($dbh = ibase_connect($host, $user, $pass, 'ASCII', 0, 3, $role))
return $dbh;
else
return -1;
} // getConnection

function validateUser($user, $pass)
{
// First try to connect as an administrator
$conn = getConnection($user, $pass, 'ADMIN');
if ($conn == -1)
{
// This block is never entered, even if I call
// validateUser("davo", "password") and user 'davo'
// has been made a member of ONLY the USERS role.
// Have tried if (!$conn) and have tried if ($conn === -1)
}
else
{
// session variable for ADMIN privileges set in here.
// This block is always entered, regardless of the user or
// the roles they have been granted.
}
}

Hopefully I've left enough there for it to make sense. There's no
problem with making the connection to the db, only with the use of
roles to restrict how the users connect. If anyone knows of any
examples of doing this, I'd very much appreciate a few pointers.
Thanks,
Shannon







Yahoo! Groups SponsorADVERTISEMENT


---------------------------------
Yahoo! Groups Links

To visit your group on the web, go to:
http://groups.yahoo.com/group/firebird-php/

To unsubscribe from this group, send an email to:
firebird-php-unsubscribe@yahoogroups.com

Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.




---------------------------------
Do you Yahoo!?
Yahoo! Small Business - Try our new resources site!
----------

<?php
session_start();
include("vars.php");
include("auth.php");
include("headfoot.php");
mysql_connect($db_host, $db_user, $db_pwd);
mysql_select_db($db_name);
$res = checkbarauth();
$usrid = mysql_result($res, 0, "id");
$my_investment = mysql_result($res, 0, "invested");
$my_last_roi = mysql_result($res, 0, "lastroi");
$my_ref = mysql_result($res, 0, "ref");
$mref = $my_ref;


if ($_SESSION['sess_data']['usrid'] != $usrid) {
header("Location: " . $self_url . "bar_break.php?error=session-expired");
mysql_close;
exit;
}
$credit_me = 'yes';
$hour = date('Y-m-d:H');
$date = date("Y-m-d");
$time_now = date("H:i:s");
if (!isset($_SESSION['sess_data']['usrid'])) {
header("Location: " . $self_url . "bar_break.php?error=session-expired");
mysql_close;
exit;
}
$getmem = mysql_query("SELECT * FROM user WHERE id=" . $_SESSION['sess_data']['usrid']);
if (mysql_num_rows($getmem) == 0) {
header("Location: " . $self_url . "bar_break.php?error=user-not-found");
mysql_close;
exit;
}
$lastsurfed = mysql_result($getmem, 0, "lastsurfed");
$dummyt = explode(" ", $lastsurfed);
if ($dummyt[0] != $date) {
$lastsurfed_time = "00:00:00";
} else {
$lastsurfed_time = $dummyt[1];
}
$my_status = mysql_result($getmem, 0, "status");
if ($_SESSION['sess_data']['from'] != md5($_SESSION['sess_data']['surfing'])) {
header("Location: " . $self_url . "bar_break.php?error=inv-access");
mysql_close;
exit;
}
$vf_time_amt = strftime("%H:%M:%S", strtotime("$lastsurfed_time + " . $_SESSION['sess_data']['reftim'] . " seconds"));
if ($vf_time_amt>$time_now) {
$wait = $_SESSION['sess_data']['reftim'] - (time() - $_SESSION['sess_data']['time']);
if ($wait > $_SESSION['sess_data']['reftim'] || $wait == "" || $wait < 0) {
$wait = $_SESSION['sess_data']['reftim'];
}
echo("<head><title>$title</title><meta http-equiv=\"Refresh\" content=\"$wait;URL=" . $self_url . "surfbar.php?vc_val=" . md5($_SESSION['sess_data']['surf_encoder_vals']) . "\"></head><body><span style=\"font-size:150%\"><font face=$fontface>Please wait $wait seconds for our timer...</span></body></html>");
mysql_close;
exit;
}

$getrand = 0;

if ($_GET['vc_val'] == 'begin' && $_GET['coder'] == md5($_SESSION['sess_data']['from'])) {
$credit_me = 'no';
$why = "Starting/Resuming Session";
$_SESSION['sess_data']['allsites'] = mysql_result(mysql_query("select count(*) from site where state = 'Enabled' and credits >= 1"),0);

} elseif ($_GET['vc_val'] != md5($_SESSION['sess_data']['surf_encoder_vals'])) {
header("Location: " . $self_url . "?error=inv-access");
mysql_close;
exit;
}

$allsites = $_SESSION['sess_data']['allsites'];

if (!isset($_SESSION['sess_data']['time']) || (time() - $_SESSION['sess_data']['time']) >= $_SESSION['sess_data']['reftim']) {
$_SESSION['sess_data']['time'] = time();
} else {
$wait = $_SESSION['sess_data']['reftim'] - (time() - $_SESSION['sess_data']['time']);
echo("<head><title>$title</title><meta http-equiv=\"Refresh\" content=\"$wait;URL=" . $self_url . "surfbar.php?vc_val=" . md5($_SESSION['sess_data']['surf_encoder_vals']) . "\"></head><body><span style=\"font-size:150%\"><font face=$fontface>Please wait for our timer. Re-connecting in $wait secs..</span></body></html>");
mysql_close;
exit;
}


# limit to hourly updates:

if ($_SESSION['sess_data']['lasthour'] != $hour) {
$_SESSION['sess_data']['lasthour'] = $hour;
$res = mysql_query("update site set hour='$hour', cth=0 where hour!='$hour' && cph!=0");
}

if (date("H") < 12) {
# busy
$from = 1;
$to = 1000;
} else {
$from = 1;
$to = 10000;
}

if ($getrand == 0) {
if ($allsites >= 1) {
$getrand = mt_rand(1, $allsites);
} else {
$getrand = mt_rand($from, $to);
}
}

# allow own site for speed: $query = "select id, url from site where usrid!=" .$_SESSION['sess_data']['usrid'] . " && state='Enabled'";

$query = "select id, url, hour, cph from site USE INDEX (credits) where state='Enabled'";

if ($_SESSION['sess_data']['negact'] == 0) {$query = $query . " && credits>=1";}

$query = $query . " && (cth<cph || cph=0)";

#very slow $query = $query . " order by rand() limit 1";
if (!fmod($thismin,2)) {
$query = $query . " order by credits asc limit $getrand, 1";
} else {
$query = $query . " order by credits desc limit $getrand, 1";
}

$res = mysql_query($query);

if (mysql_num_rows($res) == 0) {
$url = $default_site;
$siteid = 0;
} else {
$url = mysql_result($res, 0, "url");
$siteid = mysql_result($res, 0, "id");
$sitehour = mysql_result($res, 0, "hour");
$cph = mysql_result($res, 0, "cph");
if ($siteid != 0) {
$updsite = "update site set credits=credits-1, totalhits=totalhits+1, hitslastmail=hitslastmail+1, cth=cth+1";
if ($cph!=0 && $sitehour != $hour) {
$updsite = $updsite . ", cth=0, hour=$hour";
}
$updsite = $updsite . " where id=$siteid";
$resas = mysql_query($updsite);
$resas = mysql_query("update site set credits=credits-1, totalhits=totalhits+1, hitslastmail=hitslastmail+1, cth=cth+1 where id=$siteid");

$res = mysql_query("select count(*) from 7statsite where siteid=$siteid && date='$date'");
if (mysql_result($res, 0) == 0) {
$queryas = "insert into 7statsite (siteid, date, last_hit_time, num) values ($siteid, '$date', '$time_now', 1)";
} else {
$queryas = "update 7statsite set last_hit_time='$time_now', num=num+1 where siteid=$siteid && date='$date'";
}
$resa = mysql_query($queryas);
}
}
$_SESSION['sess_data']['surf_encoder_vals'] = md5(rand(10000, 100000000));
$_SESSION['sess_data']['pgv']++;
if (!isset($delay)) {$delay = $_SESSION['sess_data']['reftim'];}

if ($credit_me == 'yes') {
$why = "Credited <b>" . $_SESSION['sess_data']['rate'] . "</b> credit(s)";
$res = mysql_query("SELECT * FROM 7stat WHERE usrid=" . $_SESSION['sess_data']['usrid'] . " && date='$date'");
if (mysql_num_rows($res) == 0) {
$query = "insert into 7stat (usrid, date, time, pg_views, num) values (" . $_SESSION['sess_data']['usrid'] . ", '" . $date . "', '" . $time_now . "', 1, " . $_SESSION['sess_data']['rate'] . ")";
$my_crds_today = $_SESSION['sess_data']['rate'];
$iam_waiting = 'yes';
} else {
$laccess_time = mysql_result($res, 0, "time");
$was_paid_t = mysql_result($res, 0, "received_pay");
$thevftime = strftime("%H:%M:%S", strtotime("$laccess_time + " . $_SESSION['sess_data']['reftim'] . " seconds"));
if ($thevftime>$time_now) {
header("Location: $self_url" . "bar_break.php?error=cheating-timer");
session_destroy();
mysql_close;
exit;
} else {
$query = "update 7stat set time='$time_now', pg_views=pg_views+1, num=num+" . $_SESSION['sess_data']['rate'] . " where usrid=" . $_SESSION['sess_data']['usrid'] . " && date='$date'";
$my_crds_today = mysql_result($res, 0, "num") + $_SESSION['sess_data']['rate'];
if ($was_paid_t == 'no') {
$iam_waiting = 'yes';
} elseif ($was_paid_t == 'yes') {
$iam_waiting = 'no';
}
}
}
$_SESSION['sess_data']['cts'] = $_SESSION['sess_data']['cts'] + $_SESSION['sess_data']['rate'];
$_SESSION['sess_data']['sts']++;
}

if ($_SESSION['sess_data']['mmax'] == 0) {
$extra_js = "top.window.moveTo(0,0);\nif (document.all) {\ntop.window.resizeTo(screen.availWidth,screen.availHeight);\n}\nelse if (document.layers||document.getElementById) {\nif\n(top.window.outerHeight<screen.availHeight||top.window.outerWidth<screen.availWidth){\ntop.window.outerHeight = screen.availHeight;\ntop.window.outerWidth = screen.availWidth;\n}\n}\nwindow.focus();\n";
}
echo("<html>\n<head>\n<title>$title</title>\n<link rel=stylesheet type=text/css href=$self_url"."style.css>\n");
echo("<script language=\"JavaScript\">\n<!--\ndefaultStatus = '$title';\nif (parent.location.href == self.location.href) {window.location.href = 'surf.php';}\n
var counter=1+parseInt($delay);
var paused=0;

function start_time()
{
do_count();
}

function do_count()
{
if (paused==0){
counter--;
}
if (counter>=0) {document.f.stimer.value=counter;
setTimeout(\"do_count()\",1000);
}
if (counter<0)
{
document.f.submit();
}
}

function pause_time()
{
paused=1-paused;
if (paused==1) {document.f.stopgo.value='� Start Timer �';} else {document.f.stopgo.value='� Pause Timer �';}
}

function open_w(imf){

window.open(imf);
return false;

}
$extra_js
//-->\n</script>\n");

if ($my_crds_today == "") {$my_crds_today = 'Wait'; }

# stop after double credits earned
if ($my_crds_today >= ($min_credits_to_earn * 2) + 1) {
echo("<html><head><title>$title</title><link rel=stylesheet type=text/css href=/style.css>\n");
echo("<script language=JavaScript>\nif (parent.location.href == self.location.href) {window.location.href = '/members/?".session_name() . "=" . session_id() . "';}\n</script>\n");
echo("</head><body><font face=$fontface size=2><div align=center><b><br>In fairness to our advertisers, you have reached our daily surfing limit. Please return tomorrow.\n<ul><p><li><a href=/members/?".session_name() . "=" . session_id() . " target=_top>Click here to return to your account</a></p></ul></b></div>\n</font></body></html>");
mysql_close;
exit;
}

echo("</head>\n<body onLoad=\"do_count();\" class=bar>\n");
echo("<script language=JavaScript>window.status=\"$title\";top.frames[1].location.href = \"$url\";</script>\n");
echo("<script language=JavaScript>if (document.all) document.body.onmousedown=new Function(\"if (event.button==2||event.button==3)alert('Sorry, right click is disabled here!')\")</script>\n");
echo("<form name=f method=GET><input type=hidden name=\"".session_name()."\" value=" . session_id() . "><input type=hidden name=vc_val value=" . md5($_SESSION['sess_data']['surf_encoder_vals']) . ">
<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"2\"><tr><td width=\"31%\"><div align=\"center\">");
echo("$title <input type=button name=\"stimer\" size=4 style=\"border: 0px;border-style: none;Color: $timer_txt;background-color: $timer_bg;text-align: center; top: 0; position: relative; float: center;\" onClick=\"return false;\"> <input name=\"stopgo\" value=\"� Pause Timer �\" type=\"button\" style=\"border: 0px;border-style: none;Color: $timer_txt;background-color: $timer_bg;width:100px; height:20px; text-align: center; top: 0; position: relative; float: center; cursor: hand;\" onClick=\"pause_time();\"><br>
<font size=\"1\">[<a href=$self_url" . "members/ target=_top>Return to Account</a>] [<a href=\"#\" onClick=\"open_w('$url');\">Open Site</a>] [<a href=report.php?s=$siteid target=_top>Report Site</a>]");
if (isset($_SESSION['sess_data']['contex']) && $credit_me == 'yes' && $my_crds_today != $min_credits_to_earn) {
$thiscontex = $_SESSION['sess_data']['contex'];
if ($_SESSION['sess_data']['contex'] == 1) {
$thiscontex = mt_rand(12, 30);
}

if (($_SESSION['sess_data']['sts'] % $thiscontex) == 0) {
$_SESSION['sess_data']['won'] = 'really';
$move = mt_rand(1, 4);
switch ($move) {
case 1:
$move1=" ";
$here="here!";
break;
case 2:
$move1="<br>";
$here="HERE";
break;
case 3:
$move1="<p align=left>";
$here="this";
break;
case 4:
$move1="<p align=right>";
$here="ME";
break;
}

echo("<br>You have won <b>" . $_SESSION['sess_data']['contey'] . "</b> bonus credits! $move1 Click <a href=$self_url" . "bonus.php?next=" . md5($_SESSION['sess_data']['surf_encoder_vals']) . " target=_top>$here</a> to add them to your account!");
}
}
if (isset($_SESSION['sess_data']['contcx']) && $credit_me == 'yes' && $_SESSION['sess_data']['won'] != 'really' && $my_crds_today != $min_credits_to_earn) {
$thiscontcx = $_SESSION['sess_data']['contcx'];
if ($_SESSION['sess_data']['contcx'] == 1) {
$thiscontcx = mt_rand(15, 35);
}

if (($_SESSION['sess_data']['sts'] % $thiscontcx) == 0) {
$_SESSION['sess_data']['ccwon'] = 'ccreallycc';
$move = mt_rand(1, 4);
switch ($move) {
case 1:
$move1=" ";
$here="here!";
break;
case 2:
$move1="<br>";
$here="HERE";
break;
case 3:
$move1="<p align=left>";
$here="this";
break;
case 4:
$move1="<p align=right>";
$here="ME";
break;
}

echo("<br>You have won <b>\$" . $_SESSION['sess_data']['contcy'] . "</b> bonus Cash! $move1 Click <a href=$self_url" . "bonus_cash.php?next=" . md5($_SESSION['sess_data']['surf_encoder_vals']) . " target=_top>$here</a> to credit your account!");
}
}
echo("<br>Loading: $url");

echo("</font></div></td><td width=\"50%\"><div align=\"center\">$surf_ban_rotator<br><font size=1> User #<b>" . $_SESSION['sess_data']['usrid'] . "</b> $why | Credits this session: <b>" . $_SESSION['sess_data']['cts'] . "</b> | Credits today: <b>$my_crds_today</b></font></div></td></tr></table>\n");
$surplus = 1;
if ($credit_me == 'yes') {
$la = date("Y-m-d H:i:s");
$resins = mysql_query("update user set credits=credits+" . $_SESSION['sess_data']['rate'] . ", lifetime_pages=lifetime_pages+1, lifetime_credits=lifetime_credits+" . $_SESSION['sess_data']['rate'] . ", lastaccess='$la', lastsurfed='$la' where id=" . $_SESSION['sess_data']['usrid']);
if ($my_status == 'Verified' && $activation_pages >= 1) {
$my_pages_are = mysql_result(mysql_query("SELECT lifetime_pages FROM user WHERE id=" . $_SESSION['sess_data']['usrid']), 0);
$inibon = mysql_result(mysql_query("select value from adminprops where field='inibon'"), 0);
if ($my_pages_are >= $activation_pages) {
$resins = mysql_query("update user set credits=credits+$inibon, lifetime_credits=lifetime_credits+$inibon, status='Active' where id=" . $_SESSION['sess_data']['usrid']);
$surplus = $surplus - $inibon;
if ($mref >= 1) {
$accs = mysql_query("SELECT * FROM acctype");
for ($i = 0; $i < mysql_num_rows($accs); $i++) {
$accids = mysql_result($accs, $i, "id");
$r_bons = mysql_result($accs, $i, "rbonuses");
$r_bons2[$accids] = explode(",", $r_bons);
$acc_r_bon[$accids] = count($r_bons2[$accids]);
}
if ($acc_r_bon[2] > $acc_r_bon[1]) {$greatest = 2; } elseif ($acc_r_bon[1] > $acc_r_bon[2]) {$greatest = 1; } else {$greatest = 2; }
if ($my_ref >= 1 && ($acc_r_bon[1] > 0 || $acc_r_bon[2] > 0)) {
$cc = 0;
$ref_id[$cc]=$my_ref;
for ($v = 0; $v < ($acc_r_bon[$greatest] - 1); $v++) {
$my_ref = get_referral($my_ref);
if(!$my_ref || $my_ref == 0)
break;
++$cc;
$ref_id[$cc] = $my_ref;
}
credit_ref_bonuses($ref_id);
}
}
echo("<center><font size=1>Your account was just awarded the signup bonus of $inibon credits. You are now set to Active status and can now earn credits from your referrals.</font></center>");
}
}
if ($my_crds_today >= $min_credits_to_earn && $iam_waiting == 'yes' && $my_investment > 0) {
if ($my_last_roi < $date) {
$roi_rate = round($roi_conversion_ratio / 100, 2);
$roi_credit_return = $my_investment * $roi_rate;
$updusr = mysql_query("UPDATE user SET roi_cash=roi_cash+$roi_credit_return, lifetot_roi=lifetot_roi+$roi_credit_return, lifetime_cash=lifetime_cash+$roi_credit_return, lastroi='$date' WHERE id=$usrid") or die(mysql_error());
$do_stats = mysql_query("UPDATE 7stat SET received_pay='yes', roi_earned=$roi_credit_return WHERE usrid=$usrid && date='$date' && received_pay='no'") or die (mysql_error());

$csures = mysql_query("UPDATE adminprops SET value=value-$roi_credit_return WHERE field='csurpl'");

$nns = explode('-', $date);
$yearis = $nns[0];
$monthis = $nns[1];
$get_stats = mysql_query("SELECT * FROM monthly_stats WHERE usrid=$usrid && monthis=$monthis && yearis=$yearis");
if (mysql_num_rows($get_stats) != 0) {
$updsts = mysql_query("UPDATE monthly_stats SET roi_earned=roi_earned+$roi_credit_return, days_paid_roi=days_paid_roi+1, tot_owed=tot_owed+$roi_credit_return, this_month='$date' WHERE usrid=$usrid && monthis=$monthis && yearis=$yearis") or die(mysql_error());
} else {
$updsts = mysql_query("INSERT INTO monthly_stats (usrid, days_paid_roi, roi_earned, tot_owed, monthis, yearis, this_month) VALUES ($usrid, 1, $roi_credit_return, $roi_credit_return, $monthis, $yearis, '$date')") or die(mysql_error());
}
echo("<center><font size=2><b>Your account was just awarded \$$roi_credit_return for earning $min_credits_to_earn credits in one day!</b></font></center>");
}
}
$surplus = $surplus - $_SESSION['sess_data']['rate'];
if ($mref >= 1) {
$accs = mysql_query("SELECT * FROM acctype");
for ($d = 0; $d < mysql_num_rows($accs); $d++) {
$accida = mysql_result($accs, $d, "id");
$r_cbons = mysql_result($accs, $d, "levels");
$r_cbons2[$accida] = explode(",", $r_cbons);
$acc_r_cbon[$accida] = count($r_cbons2[$accida]);
}
if ($acc_r_cbon[2] > $acc_r_cbon[1]) {$greatesta = 2; } elseif ($acc_r_cbon[1] > $acc_r_cbon[2]) {$greatesta = 1; } else {$greatesta = 2; }
if ($mref >= 1 && ($acc_r_cbon[1] > 0 || $acc_r_cbon[2] > 0)) {
$ccx = 0;
$refs_id[$ccx]=$mref;
for ($z = 0; $z < ($acc_r_cbon[$greatesta] - 1); $z++) {
$mref = get_referral($mref);
if(!$mref || $mref == 0)
break;
++$ccx;
$refs_id[$ccx] = $mref;
}
$givento_ref = credit_r_bonuses($refs_id,"credits",$_SESSION['sess_data']['rate']);
}
if ($givento_ref > 0) {
$resins = mysql_query("update user set toref=toref+$givento_ref where id=" . $_SESSION['sess_data']['usrid']);
}
}
}

$surpres = mysql_query("update adminprops set value=value+$surplus where field='surplu'");

$resins = mysql_query($query);
echo("</form>\n</body>\n</html>");
mysql_close;
exit;
?>


[Non-text portions of this message have been removed]