I am having trouble converting my PHP SQL query to Vb.Net.
This is my PHP code:
<?php
$ServerName = "Farbod-PC\SQLExpress";
$User = "sa";
$Pass = "admin123";
$DB = "Account";
$user = sql_clean($_GET['Username']);
$passhash = sql_clean($_GET['Password']);
$connectionInfo = array("UID"=>$User,"PWD"=>$Pass,"DATABASE"=>$DB);
$conn = sqlsrv_connect( $ServerName, $connectionInfo) or die('Database connect Fail.');
if( $conn ) {
} else {
echo " <br> Connection could not be established. <br> <br>";
die( print_r( sqlsrv_errors(), true));
}
$exec = sqlsrv_query($conn, "SELECT nEMID, nAuthID, sUserPass FROM tAccounts where sUsername = '$user'");
$AccountData = sqlsrv_fetch_array($exec);
$file = file('LauncherInfo.txt', FILE_IGNORE_NEW_LINES);
$sql = "SELECT nEMID, nAuthID, sUserPass FROM tAccounts where sUsername = '$user'";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $sql , $params, $options );
$row_count = sqlsrv_num_rows( $stmt );
foreach ($file as $line) {
$line = trim($line);
if ($line) {
$splitLine = explode(' = ',$line);
$data[$splitLine[0]] = $splitLine[1];
}
}
if($exec)
{
if($row_count != 1)
{
die('wud');
}
if ($AccountData ['nAuthID'] == -2) {
die ('INV');
} else if ($AccountData ['nAuthID'] == -1) {
die ('BAN');
} else if ($AccountData ['nAuthID'] == 0) {
die ('EVR');
} else if ($AccountData ['nAuthID'] == 1) {
if ($data['MAINT'] == "True") {
die ('MM');
}
} else if ($AccountData ['nAuthID'] == 2) {
//Continue and allow user to log in.
} else {
die ('NAUTH');
}
$PlaintxtPass = $AccountData['sUserPass'];
$PlaintxtnEMID = $AccountData['nEMID'];
if (MD5($PlaintxtPass) == $passhash)
{
$Token = RandomToken(35);
$setToken = null;
if (sqlsrv_num_rows(sqlsrv_query($conn, "SELECT * FROM tTokens WHERE nEMID = '".$PlaintxtnEMID."'")) >= 1)
{
sqlsrv_query($conn, "DELETE FROM tTokens WHERE nEMID = '".$PlaintxtnEMID."'");
$setToken = sqlsrv_query($conn, "INSERT INTO tTokens (nEMID, sToken) VALUES('".$PlaintxtnEMID."', '".$Token."')");
}
else
$setToken = sqlsrv_query($conn, "INSERT INTO tTokens (nEMID, sToken) VALUES('".$PlaintxtnEMID."', '".$Token."')");
if ($setToken)
die('OK#'.$Token.'#'.$AccountData ['nAuthID']);
else
die('SetToken Error');
}
else
{
die('wud');
}
}
else
{
die('Query Failed');
}
sqlsrv_close();
function sql_clean($str)
{
$search = array("\\", "\0", "\n", "\r", "\x1a", "'", '"');
$replace = array("", "", "", "", "", "", "");
return str_replace($search, $replace, $str);
}
function RandomToken( $length )
{
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = "";
$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ ) {
$str .= $chars[ rand( 0, $size - 1 ) ];
}
return $str;
}
?>
This is my Vb.net code so far:
Imports System.Net
Imports System.Data.SqlClient
Public Class Form1
Dim SQLHost As String = "Farbod-PC\SQLEXPRESS"
Dim SQLUserName As String = "sa"
Dim SQLPassword As String = "admin123"
Dim Server As String = "Account"
Dim conn As SqlConnection = New SqlConnection("Data Source=" & SQLHost & "; Initial Catalog=" & Server & "; User ID=" & SQLUserName & "; Password=" & SQLPassword & ";")
Dim strSQL As String
Dim exec As String = "SELECT nEMID, nAuthID, sUserPass FROM tAccounts where sUsername = 'user'"
End Class
I'm not sure which way I should go about doing this. I would appreciate it if anyone could help. Thanks.
Farbod,
It seems as though you're asking a pretty vague and broad question here. StackOverflow is great if you need help with specific problems, but it seems that what you really need are some VB.NET tutorials.
Although one thing I would say is this; Stored Procedures are your friends.
Related
I'm still a beginner programmer , so I hope you give the solution step by step.
I'm trying to make a private server for a flash game and i have a problem that I don't know how can I solve it at all .
I wanna connect the game with the database , and when someone tries to make an account (register) in the game , the account data supposed to be saved in the database ( like: username,password,mask color,birth date,register date,etc...) but it doesn't happen
The file which is responsible about this step is called " register.php" and
I keep getting this error :
Fatal error: Call to a member function get() on null in C:\appserv\www\Cocolani\php\req\register.php on line 4
the problem is in this line :
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
and this is "register.php" :
<?php
include_once("db.php");
include_once("settings.php");
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
$FROM_EMAIL = $obj->getEmailFrom();
function generateTribeCurrency($ID, $db) {
// $db = new database();
// get init purse amount
$db->setQuery("SELECT init_purse_amount FROM `cc_def_settings`");
$row = $db->loadResult();
$init_purse_amount = $row->init_purse_amount;
// load tribe info
$db->setQuery("SELECT * FROM `cc_tribes`");
$tribeinfo = $db->loadResults();
$newstr = array();
foreach ($tribeinfo as $i) {
if ($ID == $i->ID) array_push($newstr, $init_purse_amount); else array_push($newstr, 0);
}
$newstr = implode(",", $newstr);
return $newstr;
}
$hackchk = false;
foreach($_POST as $POST) {
$POST = mysqli_real_escape_string($POST);
}
function remove_bad_symbols($s) {
return preg_replace(
array(0=>'#/#', 1=>'#\\\#', 2=>'#;#', 3=>'#{#', 4=>'#}#', 5=>'#<#', 6=>'#>#', 7=>'###', 8=>'#\'#', 9=>'# #', 10=>'#"#') // patterns
, '' // replacements
, $s);
}
$username = isset($_POST['username']) ? remove_bad_symbols($_POST['username']) : "";
$password = isset($_POST['password']) ? $_POST['password'] : "";
$email = isset($_POST['email']) ? $_POST['email'] : "";
$birthdate = isset($_POST['birthdate']) ? $_POST['birthdate'] : "";
$firstname = isset($_POST['firstname']) ? $_POST['firstname'] : "";
$lastname = isset($_POST['lastname']) ? $_POST['lastname'] : "";
$sex = isset($_POST['sex']) ? $_POST['sex'] : "";
$tribeid = isset($_POST['clan']) ? $_POST['clan'] : "";
$mask = isset($_POST['mask']) ? $_POST['mask'] : "";
$mask_color = isset($_POST['maskcl']) ? $_POST['maskcl'] : "";
$lang_id = isset($_POST['lang_id']) ? $_POST['lang_id'] : 0;
$error = '';
$purse = generateTribeCurrency((int) $tribeid, $db);
// get language suffix
if ($lang_id != 0) {
$db->setQuery("SELECT * FROM `cc_extra_langs` WHERE id='{$lang_id}'");
$res = $db->loadResult();
$lang = "_".$res->lang;
} else $lang = "";
$db->setQuery("SELECT one_email_per_registration FROM `cc_def_settings`");
$res = $db->loadResult();
$one_registration_per_email = ($res->one_email_per_registration == 1);
$email_check_ok = true;
if ($one_registration_per_email == true) {
$sql = "SELECT COUNT(*) AS counter FROM `cc_user` WHERE email='{$email}'";
// for several registrations per one email address -- no check
$db->setQuery($sql);
$res1 = $db->loadResult();
$email_check_ok = $res1->counter == "0";
}
// first check there is no username with this name already registered.
$db->setQuery("SELECT COUNT(*) AS counter FROM `cc_user` WHERE username='".$username."'");
$res = $db->loadResult();
if ($username && $email && $sex && $birthdate) {
if ($email_check_ok) {
if ($res->counter == "0") {
// check that there are no registrations from this same IP in the last 2 hours
$db->setQuery("SELECT COUNT(*) as counter FROM `cc_userreginfo` WHERE IP='".$_SERVER['REMOTE_ADDR']."' AND (DATE_SUB(CURDATE(), INTERVAL 2 HOUR)<register_date)");
$regcheck = $db->loadResult();
if (($regcheck != null && (int)($regcheck->counter) == 0) || $hackchk == false) {
// get number of already registered number of registrations with this email address
$query = $db->setQuery("SELECT count(*) as registered_num_emails FROM `cc_user` WHERE email='{$email}'");
$row = $db->loadResult();
$already_registered_num_emails = $row->registered_num_emails;
// get max number of accounts per email from settings table
$query = $db->setQuery("SELECT max_num_account_per_email from `cc_def_settings`");
$row = $db->loadResult();
$max_num_account_per_email = $row->max_num_account_per_email;
if ($already_registered_num_emails < $max_num_account_per_email) {
$uniqid = uniqid();
$newreq = "INSERT INTO `cc_user` (`ID`,`username`, `password`, `email`, `birth_date`, `first_name`, `last_name`, `sex`, `about`, `mask`, `mask_colors`, `clothing`, `tribe_ID` , `money`, `happyness`, `rank_ID`, `status_ID`, `lang_id`, `register_date`, uniqid, permission_id) VALUES ";
$newreq .= "(NULL, '{$username}', '{$password}', '{$email}', '{$birthdate}', '{$firstname}' , '{$lastname}', '{$sex}', '', '{$mask}', '{$mask_color}', '', '{$tribeid}', '{$purse}', 50, 0, 3, '{$lang_id}', NOW(), '{$uniqid}', 4)";
$db->setQuery($newreq);
$res = $db->runQuery();
if ($res) {
// add registration info into the userreginfo table as well.
$iid = $db->mysqlInsertID();
$db->setQuery("INSERT INTO `cc_userreginfo` (`ID`, `user_id`, `register_IP`, `register_date`, `last_update`) VALUES (NULL, ".$iid.",'".$_SERVER['REMOTE_ADDR']."', NOW(), NOW())");
$res2 = $db->runQuery();
$counter = ($regcheck != null) ? $regcheck->counter : 0;
echo 'response=true®='.$counter;
// ----------------------------------
// send confirmation email
// ----------------------------------
$cur_lang = ($lang != "") ? substr($lang, 1)."/" : "";
$msg = $obj->getTranslation(-13, $lang, "email_templates", "id", "content");
$msg = str_replace("%FIRST_NAME%", $firstname, $msg);
$msg = str_replace("%LAST_NAME%", $lastname, $msg);
$msg = str_replace("'", "'", $msg);
$msg = str_replace("%CONFIRM%", 'confirm', $msg);
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf8' . "\r\n";
$headers .= 'From: '.$FROM_EMAIL."\r\n";
//mail($email, $obj->getTranslation(-13, $lang, "email_templates", "id", "subject"), $msg, $headers);
include "../../admin/php_mailer/class.phpmailer.php";
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = $msg;
$body = eregi_replace("[\]",'',$body);
$mail->SetFrom($FROM_EMAIL);
$mail->AddAddress($email);
$mail->Subject = $obj->getTranslation(-13, $lang, "email_templates", "id", "subject");
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
if(!$mail->Send()) {
die("Mailer Error: " . $mail->ErrorInfo);
} else {
//echo "Message sent!";
}
// ----------------------------------
} else {
echo 'response=false';
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='MAX_NUM_REGISTRATION_REACHED'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='REGISTER_LATER'");
$res = $db->loadResult();
echo 'errorhide='.urlencode($res->{"name".$lang});
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='USERNAME_IN_USE'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
} else {
//if ($one_registration_per_email == true)
$sql = "SELECT * FROM `cc_translations` WHERE caption='DUPLICATED_EMAIL'"; //else $sql = "SELECT * FROM `cc_translations` WHERE caption='DUPLICATED_REGISTRATION'";
// get warning message from db
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='REGFORM_PROBLEM'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
?>
note : "register.php" requires two files so maybe the error is in one of them
settings.php :
<?php
$db_server = "localhost";
$db_user = "root";
$db_password = "qazqazqaz1";
$db_name = "coco";
$connect = mysqli_connect("$db_server","$db_user","$db_password","$db_name");
?>
db.php:
<?php
class database {
var $_debug = 0;
var $_sql = '';
var $_error = '';
var $_prefix = '';
var $_numrows = 0;
var $_DBhost = 'localhost';
var $_DBuser = "root";
var $_DBpass = "qazqazqaz1";
var $_DBname = "cocol";
var $url_root = "localhost/cocolani";
public function __construct($dbname = 'cocolani_battle', $dbuser = 'root', $dbpsw = 'pass1234', $dbhost = 'localhost', $urlroot = 'localhost/cocolani') {
$this->_DBname = 'cocolani_battle';
$this->_DBuser = 'root';
$this->_DBpass = 'pass1234';
$this->url_root = 'localhost/cocolani';
$this->_DBhost = 'localhost';
$this->_connection = mysqli_connect($this->_DBhost, $this->_DBuser, $this->_DBpass) or die("Couldn't connect to MySQL");
mysqli_select_db($this->_connection, $this->_DBname) or die("Select DB Error: ".mysqli_error());
}
public function __destruct() {
mysqli_close($this->_connection);
}
function debug($debug_level) {
$this->_debug = intval($debug_level);
}
function setQuery($sql) {
/* queries are given in the form of #__table need to replace that with the prefix */
$this->_sql = str_replace('#__', $this->_prefix.'_', $sql);
}
function getQuery() {
return "<pre>" . htmlspecialchars( $this->_sql) . "</pre>";
}
function prepareStatement($sql) {
$this->sql = mysqli_prepare($this->_connection, $sql);
return $this->sql;
}
function runQuery($num_rows=0) {
mysqli_select_db($this->_connection, $this->_DBname) or die("Select DB Error: ".mysqli_error());
$this->_numrows = 0;
$result = mysqli_query($this->_connection, $this->_sql);
if ($this->_debug > 1) echo "<pre>" . htmlspecialchars( $this->_sql) . "</pre>";
if (!$result) {
$this->_error = mysqli_error($this->_connection);
if ($this->_debug) {
echo 'Error: ' . $this->getQuery() . $this->_error;
}
return false;
}
if ($num_rows) {
$this->_numrows = mysqli_num_rows($result);
}
return $result;
}
/* Retrieve Mysql insert id */
function mysqlInsertID() {
$insert_id = mysqli_insert_id();
return $insert_id;
}
/* Escapes special characters while inserting to db */
function db_input($string) {
if (is_array($string)) {
$retArray = array();
foreach($string as $key => $value) {
$value = (get_magic_quotes_gpc() ? stripslashes($value) : $value);
$retArray[$key] = mysqli_real_escape_string($value);
}
return $retArray;
} else {
$string = (get_magic_quotes_gpc() ? stripslashes($string) : $string);
return mysqli_real_escape_string($string);
}
}
function getError() {
return $this->_error;
}
/* Load results into csv formatted string */
function loadCsv() {
if (!($res = $this->runQuery())) {
return null;
}
$csv_string = '';
while ($row = mysqli_fetch_row($res)) {
$line = '';
foreach( $row as $value ) {
if ( ( !isset( $value ) ) || ( $value == "" ) ) {
$value = ",";
} else {
$value = $value. ",";
$value = str_replace( '"' , '""' , $value );
}
$line .= $value;
}
$line = substr($line, 0, -1);
$csv_string .= trim( $line ) . "\n";
}
$csv_string = str_replace( "\r" , "" , $csv_string );
//$csv_string .= implode(",", $row) . "\n";
mysqli_free_result($res);
return $csv_string;
}
/* Load multiple results */
function loadResults($key='' ) {
if (!($res = $this->runQuery())) {
return null;
}
$array = array();
while ($row = mysqli_fetch_object($res)) {
if ($key) {
$array[strtolower($row->$key)] = $row;
} else {
$array[] = $row;
}
}
mysqli_free_result($res);
return $array;
}
function loadResult() {
if (!($res = $this->runQuery())) {
if ($this->_debug) echo 'Error: ' . $this->_error;
return null;
}
$row = mysqli_fetch_object($res);
mysqli_free_result($res);
return $row;
}
/* Load a result field into an array */
function loadArray() {
if (!($res = $this->runQuery())) {
return null;
}
$array = array();
while ($row = mysql_fetch_row($res)) {
$array[] = $row[0];
}
mysqli_free_result($res);
return $array;
}
/* Load a row into an associative an array */
function loadAssoc() {
if (!($res = $this->runQuery())) {
return null;
}
$row = mysqli_fetch_assoc($res);
mysqli_free_result($res);
return $row;
}
/* Return one field */
function loadField() {
if (!($res = $this->runQuery())) {
return null;
}
while ($row = mysql_fetch_row($res)) {
$field = $row[0];
}
mysqli_free_result($res);
return $field;
}
?>
I tried to solve it myself but I lost hope , so please tell me the accurate solution in steps .
thanks.
The error is referring to $obj->get. Basically you're executing the get method on a null variable, meaning it doesn't exist. After looking through all the code you have there, you aren't declaring $obj at any point.
I think you might need to check how you're passing in your settings to your Database object. For example:
$db = new database($db_server, ... , ...);
Updated:
You're hardcoding your connection anyway, just don't pass anything to the DB object.
Change this:
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
To this:
$db = new database();
I get an error in my file "checkusername.php".
The error I get is:
( ! ) Fatal error: Call to a member function get() on null in
C:\wamp\www\Cocolani\php\req\checkusername.php on line 4
There is a "checkusername.php" file :
<?php
include_once("../../includes/db.php");
include_once("settings.php");
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
$username = isset($_POST['username']) ? mysqli_real_escape_string($_POST['username']) : "";
$password = isset($_POST['password']) ? mysqli_real_escape_string($_POST['password']) : "";
$email = isset($_POST['email']) ? mysqli_real_escape_string($_POST['email']) : '';
$birthdate = isset($_POST['birthdate']) ? mysqli_real_escape_string($_POST['birthdate']) : "";
$firstname = isset($_POST['firstname']) ? mysqli_real_escape_string($_POST['firstname']) : "";
$lastname = isset($_POST['lastname']) ? mysqli_real_escape_string($_POST['lastname']) : "";
$sex = isset($_POST['sex']) ? mysqli_real_escape_string($_POST['sex']) : "";
$tribeid = isset($_POST['clan']) ? mysqli_real_escape_string($_POST['clan']) : "";
$mask = isset($_POST['mask']) ? mysqli_real_escape_string($_POST['mask']) : "";
$mask_color = isset($_POST['maskcl']) ? mysqli_real_escape_string($_POST['maskcl']) : "";
$lang_id = isset($_POST['lang_id']) ? addslashes($_POST['lang_id']) : 0;
$error = '';
// get language suffix
if ($lang_id != 0) {
$db->setQuery("SELECT * FROM `cc_extra_langs` WHERE id='{$lang_id}'");
$res = $db->loadResult();
$lang = "_".$res->lang;
} else $lang = "";
$reg_ok = true;
$db->setQuery("SELECT one_email_per_registration FROM `cc_def_settings`");
$res = $db->loadResult();
$one_registration_per_email = ($res->one_email_per_registration == 1);
$email_check_ok = true;
if ($one_registration_per_email == true) {
$sql = "SELECT COUNT(*) AS counter FROM `cc_user` WHERE email='{$email}'"; // for several registrations per one email address -- no check
$db->setQuery($sql);
$res1 = $db->loadResult();
$email_check_ok = $res1->counter == "0";
}
if ($email_check_ok == false) {
$sql = "SELECT * FROM `cc_translations` WHERE caption='DUPLICATED_EMAIL'";
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
/*if ($reg_ok && $email != '') {
// get number of already registered number of registrations with this email address
$sql = "SELECT count(*) as registered_num_emails FROM `cc_user` WHERE email='{$email}'";
$query = $db->setQuery($sql);
$row = mysql_fetch_object($query);
$registered_num_emails = $row->registered_num_emails;
$sql = "SELECT max_num_account_per_email from `cc_def_settings`";
$query = $db->setQuery($sql);
$row = mysql_fetch_object($query);
// it's possible to create new registration using this email address
if ($registered_num_emails >= $row->max_num_account_per_email) {
$sql = "SELECT * FROM `cc_translations` WHERE caption='MAX_NUM_REGISTRATION_REACHED'";
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
}*/
////////
// echo 'error=111';
// $reg_ok = false;
////////
if ($reg_ok) {
// check for swear words
$db->setQuery("SELECT COUNT(*) as counter from `cc_swear_words` where INSTR('".$username."', `name`)");
$res2 = $db->loadResult();
if ((int)($res2->counter) > 0) { // swear word founded!
$sql = "SELECT * FROM `cc_translations` WHERE caption='USERNAME_NOT_PERMITTED'";
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
}
if ($reg_ok) {
// first check there is no username with this name already registered.
$db->setQuery("SELECT COUNT(*) AS counter FROM `cc_user` WHERE username='".$username."'");
$res = $db->loadResult();
if ((int)($res->counter) > 0) { // swear word founded!
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='USERNAME_IN_USE'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
}
if ($reg_ok) echo 'result=true';
?>
The problem on line 4 which is :
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
There is a "settings.php" :
<?php
$db_server = "localhost";
$db_user = "root";
$db_password = "pass1234";
$db_name = "cocolani_battle";
$appsecret = "80f730a73ac60417c36c341bc975f6f1";
$connect = mysqli_connect("$db_server","$db_user","$db_password","$db_name");
?>
and there is a "db.php" :
<?php
/*
Usage
$db = new database($dbname);
for selects:
$db->setQuery("SELECT * FROM `table`")
$resultArray = $db->loadResults();
$db->setQuery("SELECT * FROM `table` WHERE `primary_id` = '1'");
$resultObject = $db->loadResult();
for inserts:
$db->setQuery("INSERT INTO `table` (`id`, `example`) VALUES ('1', 'abc')");
if (!$db->runQuery()) {
echo $db->getError();
}
*/
class database {
var $_debug = 0;
var $_sql = '';
var $_error = '';
var $_prefix = '';
var $_numrows = 0;
var $_DBhost = 'localhost';
var $_DBuser = "root";
var $_DBpass = "pass1234";
var $_DBname = "cocolani_battle";
var $url_root = "localhost/cocolani";
public function __construct($dbname = 'cocolani_battle', $dbuser = 'root', $dbpsw = 'pass1234', $dbhost = 'localhost', $urlroot = 'localhost/cocolani') {
$this->_DBname = 'cocolani_battle';
$this->_DBuser = 'root';
$this->_DBpass = 'pass1234';
$this->url_root = 'localhost/cocolani';
$this->_DBhost = 'localhost';
$this->_connection = mysqli_connect($this->_DBhost, $this->_DBuser, $this->_DBpass) or die("Couldn't connect to MySQL");
mysqli_select_db($this->_connection, $this->_DBname) or die("Select DB Error: ".mysqli_error());
}
public function __destruct() {
mysqli_close($this->_connection);
}
function debug($debug_level) {
$this->_debug = intval($debug_level);
}
function setQuery($sql) {
/* queries are given in the form of #__table need to replace that with the prefix */
$this->_sql = str_replace('#__', $this->_prefix.'_', $sql);
}
function getQuery() {
return "<pre>" . htmlspecialchars( $this->_sql) . "</pre>";
}
function prepareStatement($sql) {
$this->sql = mysqli_prepare($this->_connection, $sql);
return $this->sql;
}
function runQuery($num_rows=0) {
mysqli_select_db($this->_connection, $this->_DBname) or die("Select DB Error: ".mysqli_error());
$this->_numrows = 0;
$result = mysqli_query($this->_connection, $this->_sql);
if ($this->_debug > 1) echo "<pre>" . htmlspecialchars( $this->_sql) . "</pre>";
if (!$result) {
$this->_error = mysqli_error($this->_connection);
if ($this->_debug) {
echo 'Error: ' . $this->getQuery() . $this->_error;
}
return false;
}
if ($num_rows) {
$this->_numrows = mysqli_num_rows($result);
}
return $result;
}
/* Retrieve Mysql insert id */
function mysqlInsertID() {
$insert_id = mysqli_insert_id();
return $insert_id;
}
/* Escapes special characters while inserting to db */
function db_input($string) {
if (is_array($string)) {
$retArray = array();
foreach($string as $key => $value) {
$value = (get_magic_quotes_gpc() ? stripslashes($value) : $value);
$retArray[$key] = mysqli_real_escape_string($value);
}
return $retArray;
} else {
$string = (get_magic_quotes_gpc() ? stripslashes($string) : $string);
return mysqli_real_escape_string($string);
}
}
function getError() {
return $this->_error;
}
/* Load results into csv formatted string */
function loadCsv() {
if (!($res = $this->runQuery())) {
return null;
}
$csv_string = '';
while ($row = mysqli_fetch_row($res)) {
$line = '';
foreach( $row as $value ) {
if ( ( !isset( $value ) ) || ( $value == "" ) ) {
$value = ",";
} else {
$value = $value. ",";
$value = str_replace( '"' , '""' , $value );
}
$line .= $value;
}
$line = substr($line, 0, -1);
$csv_string .= trim( $line ) . "\n";
}
$csv_string = str_replace( "\r" , "" , $csv_string );
//$csv_string .= implode(",", $row) . "\n";
mysqli_free_result($res);
return $csv_string;
}
/* Load multiple results */
function loadResults($key='' ) {
if (!($res = $this->runQuery())) {
return null;
}
$array = array();
while ($row = mysqli_fetch_object($res)) {
if ($key) {
$array[strtolower($row->$key)] = $row;
} else {
$array[] = $row;
}
}
mysqli_free_result($res);
return $array;
}
function loadResult() {
if (!($res = $this->runQuery())) {
if ($this->_debug) echo 'Error: ' . $this->_error;
return null;
}
$row = mysqli_fetch_object($res);
mysqli_free_result($res);
return $row;
}
/* Load a result field into an array */
function loadArray() {
if (!($res = $this->runQuery())) {
return null;
}
$array = array();
while ($row = mysql_fetch_row($res)) {
$array[] = $row[0];
}
mysqli_free_result($res);
return $array;
}
/* Load a row into an associative an array */
function loadAssoc() {
if (!($res = $this->runQuery())) {
return null;
}
$row = mysqli_fetch_assoc($res);
mysqli_free_result($res);
return $row;
}
/* Return one field */
function loadField() {
if (!($res = $this->runQuery())) {
return null;
}
while ($row = mysql_fetch_row($res)) {
$field = $row[0];
}
mysqli_free_result($res);
return $field;
}
}
/*if ($_SERVER["SERVER_ADDR"] == '127.0.0.1') {
$url_root = "http://cocolani.localhost";
} else {
$url_root = "http://dev.cocolani.com";
}*/
?>
How can I fix this error?
As I mentioned in my comment, you can either use the variables you defined in your settings.php:
$db = new database($db_name, $db_server, $db_user, $db_password, $db_urlroot); // You didn't define $db_urlroot anywhere, but you can define it
OR hard-code it into your class. You're not using the variables you pass in anyway, so there's no need to ask for them.
public function __construct() {
I've written the following PHP script that will pull Base64 encoded pictures out of a database and write them to file. It also outputs a CSV, where each line has the Serial, Main Picture, Main Modified Date, Extra Pics, Extra Pics Modified Date.
<?php
date_default_timezone_set('America/Edmonton');
$serverName = "database";
$connectionInfo = array( "Database"=>"CRM_MSCRM");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false )
{
echo "Unable to connect.\n\n";
die( print_r( sqlsrv_errors(), true));
}
else
{
echo "Connected. Selecting trucks...\n\n";
}
$tsql = "SELECT * FROM CRM_MSCRM.dbo.Trader_Export_Simple";
$stmt = sqlsrv_query( $conn, $tsql);
if( $stmt === false )
{
echo "Error executing query.\n\n";
die( print_r( sqlsrv_errors(), true));
}
$csvData = array();
while ($row = sqlsrv_fetch_array($stmt))
{
$count = 1;
$mainpicsql = "SELECT * FROM CRM_MSCRM.dbo.TruckImages WHERE Serial = '".$row[0]."' AND MainPic = 1";
$mainpicstmt = sqlsrv_query( $conn, $mainpicsql);
while ($mainpicrow = sqlsrv_fetch_array($mainpicstmt))
{
$truck = $mainpicrow[1];
$mainfilename = $truck ."-". $count . ".png";
file_put_contents($mainfilename, base64_decode($mainpicrow[0]));
$mainpicdate = $mainpicrow[3]->format("d/m/Y h:m:s");
$mainfilename = "http://images.website/images/".$mainfilename;
echo $mainpicdate."\n";
}
$picsql = "SELECT * FROM CRM_MSCRM.dbo.TruckImages WHERE Serial = '".$row[0]."' AND MainPic = 0";
$picstmt = sqlsrv_query( $conn, $picsql);
$extrapicsdate = "";
$filenames = "";
while ($picrow = sqlsrv_fetch_array($picstmt))
{
$count++;
$filename = $picrow[1] ."-". $count . ".png";
file_put_contents($filename, base64_decode($picrow[0]));
$picdate = $picrow[3]->format("d/m/Y h:m:s");
$filenames .= "http://images.website/images/".$filename.";";
$extrapicsdate .= $picdate.";";
}
$filenames = rtrim($filenames, ";");
$extrapicsdate = rtrim($extrapicsdate, ";");
echo $filenames."\n";
echo $extrapicsdate."\n";
if ($truck != "") {
$csvData[] = array($truck, $mainfilename, $mainpicdate, $filenames, $extrapicsdate);
}
if ($filenames != "")
{
$filenames = "";
}
if ($extrapicsdate != "")
{
$extrapicsdate = "";
}
echo "Next truck...\n\n";
$truck = "";
$mainfilename = "";
$mainpicdate = "";
}
$fp = fopen('file.csv', 'w');
foreach ($csvData as $fields) {
fputcsv($fp, $fields);
}
//print_r($csvData);
sqlsrv_free_stmt( $stmt);
sqlsrv_free_stmt( $picstmt);
sqlsrv_close( $conn);
?>
I'd like to take the $truck from each line in this file, and search another CSV for the row containing that $truck, and append the columns from the matching row in this CSV to that one. Rinse and repeat for all lines in this CSV file
I just spent a while making this work after not using PHP for several years so my head's a little sore. Anyone want to point me in the right general direction on this part??
Thanks for the help!
Ok, so I have downloaded mibew messenger and I want to customize the buttons, so I go into login.php and the actual submit button for the login is type="image" so I changed to to type="submit" and when I submit the form I get a incorrect username/password error, anyway I was very confused so I was looking through loads of the other files to see if I can find anything that's related to the type="image" just in-case there's something that identifies the type="image", well I dunno, I didn't find anything but what I did notice is that when I type in admin into the username and click login the submit button it returns the login error but also in the box where I put admin there is now the value of the type="submit" so in this case it says login because the value is value="login", I'm really confused, I think maybe it is submitting "login" instead of "admin" as the username.
Here is the before and after submit buttons:
NEW
<input type="submit" name="login" value="login" >
ORIGINAL
<input type="image" name="login" src='<?php echo $webimroot.getlocal("image.button.login") ?>' alt='<?php echo getlocal("button.enter") ?>'/>
If i change it back to the original it works fine, but i want to use css not images.
Also, it would be quite hard to make a jsfiddle, otherwise i would have made one.
This is login.php where is posts the data
require_once('../libs/common.php');
require_once('../libs/operator.php');
$errors = array();
$page = array('formisRemember' => true, 'version' => $version);
if (isset($_POST['login']) && isset($_POST['password'])) {
$login = getparam('login');
$password = getparam('password');
$remember = isset($_POST['isRemember']) && $_POST['isRemember'] == "on";
$operator = operator_by_login($login);
if ($operator && isset($operator['vcpassword']) && $operator['vcpassword'] == md5($password)) {
$target = isset($_SESSION['backpath'])
? $_SESSION['backpath']
: "$root/agent/index.php";
login_operator($operator, $remember);
header("Location: $target");
exit;
} else {
$errors[] = getlocal("page_login.error");
$page['formlogin'] = $login;
}
}
$page['localeLinks'] = get_locale_links("$root/agent/login.php");
start_html_output();
require('../display/login.php');
This is the included operator.php in login.php
$can_administrate = 0;
$can_takeover = 1;
$can_viewthreads = 2;
$can_modifyprofile = 3;
$can_count = 4;
$permission_ids = array(
$can_administrate => "admin",
$can_takeover => "takeover",
$can_viewthreads => "viewthreads",
$can_modifyprofile => "modifyprofile"
);
function operator_by_login($login)
{
global $mysqlprefix;
$link = connect();
$operator = select_one_row(
"select * from ${mysqlprefix}chatoperator where vclogin = '" . mysql_real_escape_string($login) . "'", $link);
mysql_close($link);
return $operator;
}
function operator_by_email($mail)
{
global $mysqlprefix;
$link = connect();
$operator = select_one_row(
"select * from ${mysqlprefix}chatoperator where vcemail = '" . mysql_real_escape_string($mail) . "'", $link);
mysql_close($link);
return $operator;
}
function operator_by_id_($id, $link)
{
global $mysqlprefix;
return select_one_row(
"select * from ${mysqlprefix}chatoperator where operatorid = $id", $link);
}
function operator_by_id($id)
{
$link = connect();
$operator = operator_by_id_($id, $link);
mysql_close($link);
return $operator;
}
function operator_get_all()
{
global $mysqlprefix;
$link = connect();
$query = "select operatorid, vclogin, vclocalename, vccommonname, istatus, (unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " .
"from ${mysqlprefix}chatoperator order by vclogin";
$operators = select_multi_assoc($query, $link);
mysql_close($link);
return $operators;
}
function operator_is_online($operator)
{
global $settings;
return $operator['time'] < $settings['online_timeout'];
}
function operator_is_available($operator)
{
global $settings;
return $operator['istatus'] == 0 && $operator['time'] < $settings['online_timeout'] ? "1" : "";
}
function operator_is_away($operator)
{
global $settings;
return $operator['istatus'] != 0 && $operator['time'] < $settings['online_timeout'] ? "1" : "";
}
function update_operator($operatorid, $login, $email, $password, $localename, $commonname)
{
global $mysqlprefix;
$link = connect();
$query = sprintf(
"update ${mysqlprefix}chatoperator set vclogin = '%s',%s vclocalename = '%s', vccommonname = '%s'" .
", vcemail = '%s', vcjabbername= '%s'" .
" where operatorid = %s",
mysql_real_escape_string($login),
($password ? " vcpassword='" . md5($password) . "'," : ""),
mysql_real_escape_string($localename),
mysql_real_escape_string($commonname),
mysql_real_escape_string($email),
'',
$operatorid);
perform_query($query, $link);
mysql_close($link);
}
function update_operator_avatar($operatorid, $avatar)
{
global $mysqlprefix;
$link = connect();
$query = sprintf(
"update ${mysqlprefix}chatoperator set vcavatar = '%s' where operatorid = %s",
mysql_real_escape_string($avatar), $operatorid);
perform_query($query, $link);
mysql_close($link);
}
function create_operator_($login, $email, $password, $localename, $commonname, $avatar, $link)
{
global $mysqlprefix;
$query = sprintf(
"insert into ${mysqlprefix}chatoperator (vclogin,vcpassword,vclocalename,vccommonname,vcavatar,vcemail,vcjabbername) values ('%s','%s','%s','%s','%s','%s','%s')",
mysql_real_escape_string($login),
md5($password),
mysql_real_escape_string($localename),
mysql_real_escape_string($commonname),
mysql_real_escape_string($avatar),
mysql_real_escape_string($email), '');
perform_query($query, $link);
$id = mysql_insert_id($link);
return select_one_row("select * from ${mysqlprefix}chatoperator where operatorid = $id", $link);
}
function create_operator($login, $email, $password, $localename, $commonname, $avatar)
{
$link = connect();
$newop = create_operator_($login, $email, $password, $localename, $commonname, $avatar, $link);
mysql_close($link);
return $newop;
}
function notify_operator_alive($operatorid, $istatus)
{
global $mysqlprefix;
$link = connect();
perform_query("update ${mysqlprefix}chatoperator set istatus = $istatus, dtmlastvisited = CURRENT_TIMESTAMP where operatorid = $operatorid", $link);
mysql_close($link);
}
function has_online_operators($groupid = "")
{
global $settings, $mysqlprefix;
loadsettings();
$link = connect();
$query = "select count(*) as total, min(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time from ${mysqlprefix}chatoperator";
if ($groupid) {
$query .= ", ${mysqlprefix}chatgroupoperator where groupid = $groupid and ${mysqlprefix}chatoperator.operatorid = ${mysqlprefix}chatgroupoperator.operatorid and istatus = 0";
} else {
$query .= " where istatus = 0";
}
$row = select_one_row($query, $link);
mysql_close($link);
return $row['time'] < $settings['online_timeout'] && $row['total'] > 0;
}
function is_operator_online($operatorid, $link)
{
global $settings, $mysqlprefix;
loadsettings_($link);
$query = "select count(*) as total, min(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " .
"from ${mysqlprefix}chatoperator where operatorid = $operatorid";
$row = select_one_row($query, $link);
return $row['time'] < $settings['online_timeout'] && $row['total'] == 1;
}
function get_operator_name($operator)
{
global $home_locale, $current_locale;
if ($home_locale == $current_locale)
return $operator['vclocalename'];
else
return $operator['vccommonname'];
}
function append_query($link, $pv)
{
$infix = '?';
if (strstr($link, $infix) !== FALSE)
$infix = '&';
return "$link$infix$pv";
}
function check_login($redirect = true)
{
global $root, $mysqlprefix;
if (!isset($_SESSION["${mysqlprefix}operator"])) {
if (isset($_COOKIE['webim_lite'])) {
list($login, $pwd) = preg_split("/,/", $_COOKIE['webim_lite'], 2);
$op = operator_by_login($login);
if ($op && isset($pwd) && isset($op['vcpassword']) && md5($op['vcpassword']) == $pwd) {
$_SESSION["${mysqlprefix}operator"] = $op;
return $op;
}
}
$requested = $_SERVER['PHP_SELF'];
if ($_SERVER['REQUEST_METHOD'] == 'GET' && $_SERVER['QUERY_STRING']) {
$requested .= "?" . $_SERVER['QUERY_STRING'];
}
if ($redirect) {
$_SESSION['backpath'] = $requested;
header("Location: $root/agent/login.php");
exit;
} else {
return null;
}
}
return $_SESSION["${mysqlprefix}operator"];
}
function get_logged_in()
{
global $mysqlprefix;
return isset($_SESSION["${mysqlprefix}operator"]) ? $_SESSION["${mysqlprefix}operator"] : FALSE;
}
function login_operator($operator, $remember)
{
global $root, $mysqlprefix;
$_SESSION["${mysqlprefix}operator"] = $operator;
if ($remember) {
$value = $operator['vclogin'] . "," . md5($operator['vcpassword']);
setcookie('webim_lite', $value, time() + 60 * 60 * 24 * 1000, "$root/");
} else if (isset($_COOKIE['webim_lite'])) {
setcookie('webim_lite', '', time() - 3600, "$root/");
}
}
function logout_operator()
{
global $root, $mysqlprefix;
unset($_SESSION["${mysqlprefix}operator"]);
unset($_SESSION['backpath']);
if (isset($_COOKIE['webim_lite'])) {
setcookie('webim_lite', '', time() - 3600, "$root/");
}
}
function setup_redirect_links($threadid, $token)
{
global $page, $root, $settings, $mysqlprefix;
loadsettings();
$link = connect();
$operatorscount = db_rows_count("${mysqlprefix}chatoperator", array(), "", $link);
$groupscount = 0;
$groups = array();
if ($settings['enablegroups'] == "1") {
foreach (get_groups($link, true) as $group) {
if ($group['inumofagents'] == 0) {
continue;
}
$groups[] = $group;
}
$groupscount = count($groups);
}
prepare_pagination(max($operatorscount, $groupscount), 8);
$p = $page['pagination'];
$limit = $p['limit'];
$operators = select_multi_assoc(db_build_select(
"operatorid, vclogin, vclocalename, vccommonname, istatus, (unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time",
"${mysqlprefix}chatoperator", array(), "order by vclogin $limit"), $link);
$groups = array_slice($groups, $p['start'], $p['end'] - $p['start']);
mysql_close($link);
$agent_list = "";
$params = array('thread' => $threadid, 'token' => $token);
foreach ($operators as $agent) {
$params['nextAgent'] = $agent['operatorid'];
$status = $agent['time'] < $settings['online_timeout']
? ($agent['istatus'] == 0
? getlocal("char.redirect.operator.online_suff")
: getlocal("char.redirect.operator.away_suff")
)
: "";
$agent_list .= "<li><a href=\"" . add_params($root . "/agent/redirect.php", $params) .
"\" title=\"" . topage(get_operator_name($agent)) . "\">" .
topage(get_operator_name($agent)) .
"</a> $status</li>";
}
$page['redirectToAgent'] = $agent_list;
$group_list = "";
if ($settings['enablegroups'] == "1") {
$params = array('thread' => $threadid, 'token' => $token);
foreach ($groups as $group) {
$params['nextGroup'] = $group['groupid'];
$status = $group['ilastseen'] !== NULL && $group['ilastseen'] < $settings['online_timeout']
? getlocal("char.redirect.operator.online_suff")
: ($group['ilastseenaway'] !== NULL && $group['ilastseenaway'] < $settings['online_timeout']
? getlocal("char.redirect.operator.away_suff")
: "");
$group_list .= "<li><a href=\"" . add_params($root . "/agent/redirect.php", $params) .
"\" title=\"" . topage(get_group_name($group)) . "\">" .
topage(get_group_name($group)) .
"</a> $status</li>";
}
}
$page['redirectToGroup'] = $group_list;
}
$permission_list = array();
function get_permission_list()
{
global $permission_list, $permission_ids;
if (count($permission_list) == 0) {
foreach ($permission_ids as $permid) {
$permission_list[] = array(
'id' => $permid,
'descr' => getlocal("permission.$permid")
);
}
}
return $permission_list;
}
function is_capable($perm, $operator)
{
$permissions = $operator && isset($operator['iperm']) ? $operator['iperm'] : 0;
return $perm >= 0 && $perm < 32 && ($permissions & (1 << $perm)) != 0;
}
function prepare_menu($operator, $hasright = true)
{
global $page, $settings, $can_administrate;
$page['operator'] = topage(get_operator_name($operator));
if ($hasright) {
loadsettings();
$page['showban'] = $settings['enableban'] == "1";
$page['showgroups'] = $settings['enablegroups'] == "1";
$page['showstat'] = $settings['enablestatistics'] == "1";
$page['showadmin'] = is_capable($can_administrate, $operator);
$page['currentopid'] = $operator['operatorid'];
}
}
function get_all_groups($link)
{
global $mysqlprefix;
$query = "select ${mysqlprefix}chatgroup.groupid as groupid, vclocalname, vclocaldescription from ${mysqlprefix}chatgroup order by vclocalname";
return select_multi_assoc($query, $link);
}
function get_groups($link, $checkaway)
{
global $mysqlprefix;
$query = "select ${mysqlprefix}chatgroup.groupid as groupid, vclocalname, vclocaldescription" .
", (SELECT count(*) from ${mysqlprefix}chatgroupoperator where ${mysqlprefix}chatgroup.groupid = ${mysqlprefix}chatgroupoperator.groupid) as inumofagents" .
", (SELECT min(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " .
"from ${mysqlprefix}chatgroupoperator, ${mysqlprefix}chatoperator where istatus = 0 and ${mysqlprefix}chatgroup.groupid = ${mysqlprefix}chatgroupoperator.groupid " .
"and ${mysqlprefix}chatgroupoperator.operatorid = ${mysqlprefix}chatoperator.operatorid) as ilastseen" .
($checkaway
? ", (SELECT min(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " .
"from ${mysqlprefix}chatgroupoperator, ${mysqlprefix}chatoperator where istatus <> 0 and ${mysqlprefix}chatgroup.groupid = ${mysqlprefix}chatgroupoperator.groupid " .
"and ${mysqlprefix}chatgroupoperator.operatorid = ${mysqlprefix}chatoperator.operatorid) as ilastseenaway"
: ""
) .
" from ${mysqlprefix}chatgroup order by vclocalname";
return select_multi_assoc($query, $link);
}
function get_operator_groupids($operatorid)
{
global $mysqlprefix;
$link = connect();
$query = "select groupid from ${mysqlprefix}chatgroupoperator where operatorid = $operatorid";
$result = select_multi_assoc($query, $link);
mysql_close($link);
return $result;
}
And it wont let me add any more code if you need common.php let me know
Without seeing your PHP it's hard to tell, but it could be that image submits "login" as POST/GET variable value array(x, y), where the submit type will just a string value. If you are checking the submission based on that value, you will need to make some changes.
EDIT:
Looking at your code, it looks like you might be using 'login' as the username and the submit button. Try changing the submit button name to something else.
<input type="submit" name="loginButton" value="login" />
i have 2 server codes written in php that I want to merge.
the first code is to work with the mysql database and fire queries at the database and give back results
<?php
//TODO: show error off
require_once("mysql.class.php");
$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "project";
$db = new MySQL($dbHost,$dbUsername,$dbPassword,$dbName);
// if operation is failed by unknown reason
define("FAILED", 0);
define("SUCCESSFUL", 1);
// when signing up, if username is already taken, return this error
define("SIGN_UP_USERNAME_CRASHED", 2);
// when add new friend request, if friend is not found, return this error
define("ADD_NEW_USERNAME_NOT_FOUND", 2);
// TIME_INTERVAL_FOR_USER_STATUS: if last authentication time of user is older
// than NOW - TIME_INTERVAL_FOR_USER_STATUS, then user is considered offline
define("TIME_INTERVAL_FOR_USER_STATUS", 60);
define("USER_APPROVED", 1);
define("USER_UNAPPROVED", 0);
$username = (isset($_REQUEST['username']) && count($_REQUEST['username']) > 0)
? $_REQUEST['username']
: NULL;
$password = isset($_REQUEST['password']) ? md5($_REQUEST['password']) : NULL;
$port = isset($_REQUEST['port']) ? $_REQUEST['port'] : NULL;
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : NULL;
if ($username == NULL || $password == NULL)
{
echo FAILED;
exit;
}
$out = NULL;
error_log($action."\r\n", 3, "error.log");
switch($action)
{
case "authenticateUser":
// code for generating list of shares.
if ($port != NULL
&& ($userId = authenticateUser($db, $username, $password, $port)) != NULL)
{
// providerId and requestId is Id of a friend pair,
// providerId is the Id of making first friend request
// requestId is the Id of the friend approved the friend request made by providerId
// fetching friends,
// left join expression is a bit different,
// it is required to fetch the friend, not the users itself
$sql = "select u.Id, u.username, (NOW()-u.authenticationTime) as authenticateTimeDifference, u.IP,
f.providerId, f.requestId, f.status, u.port
from friends f
left join users u on
u.Id = if ( f.providerId = ".$userId.", f.requestId, f.providerId )
where (f.providerId = ".$userId." and f.status=".USER_APPROVED.") or
f.requestId = ".$userId." ";
if ($result = $db->query($sql))
{
$out .= "<data>";
$out .= "<user userKey='".$userId."' />";
while ($row = $db->fetchObject($result))
{
$status = "offline";
if (((int)$row->status) == USER_UNAPPROVED)
{
$status = "unApproved";
}
else if (((int)$row->authenticateTimeDifference) < TIME_INTERVAL_FOR_USER_STATUS)
{
$status = "online";
}
$out .= "<friend username = '".$row->username."' status='".$status."' IP='".$row->IP."'
userKey = '".$row->Id."' port='".$row->port."'/>";
// to increase security, we need to change userKey periodically and pay more attention
// receiving message and sending message
}
$out .= "</data>";
}
else
{
$out = FAILED;
}
}
else
{
// exit application if not authenticated user
$out = FAILED;
}
break;
case "signUpUser":
if (isset($_REQUEST['email']))
{
$email = $_REQUEST['email'];
$sql = "select Id from users
where username = '".$username."' limit 1";
if ($result = $db->query($sql))
{
if ($db->numRows($result) == 0)
{
$sql = "insert into users(username, password, email)
values ('".$username."', '".$password."', '".$email."') ";
error_log("$sql", 3 , "error_log");
if ($db->query($sql))
{
$out = SUCCESSFUL;
}
else {
$out = FAILED;
}
}
else
{
$out = SIGN_UP_USERNAME_CRASHED;
}
}
}
else
{
$out = FAILED;
}
break;
case "addNewFriend":
$userId = authenticateUser($db, $username, $password);
if ($userId != NULL)
{
if (isset($_REQUEST['friendUserName']))
{
$friendUserName = $_REQUEST['friendUserName'];
$sql = "select Id from users
where username='".$friendUserName."'
limit 1";
if ($result = $db->query($sql))
{
if ($row = $db->fetchObject($result))
{
$requestId = $row->Id;
if ($row->Id != $userId)
{
$sql = "insert into friends(providerId, requestId, status)
values(".$userId.", ".$requestId.", ".USER_UNAPPROVED.")";
if ($db->query($sql))
{
$out = SUCCESSFUL;
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED; // user add itself as a friend
}
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
break;
case "responseOfFriendReqs":
$userId = authenticateUser($db, $username, $password);
if ($userId != NULL)
{
$sqlApprove = NULL;
$sqlDiscard = NULL;
if (isset($_REQUEST['approvedFriends']))
{
$friendNames = split(",", $_REQUEST['approvedFriends']);
$friendCount = count($friendNames);
$friendNamesQueryPart = NULL;
for ($i = 0; $i < $friendCount; $i++)
{
if (strlen($friendNames[$i]) > 0)
{
if ($i > 0 )
{
$friendNamesQueryPart .= ",";
}
$friendNamesQueryPart .= "'".$friendNames[$i]."'";
}
}
if ($friendNamesQueryPart != NULL)
{
$sqlApprove = "update friends set status = ".USER_APPROVED."
where requestId = ".$userId." and
providerId in (select Id from users where username in (".$friendNamesQueryPart."));
";
}
}
if (isset($_REQUEST['discardedFriends']))
{
$friendNames = split(",", $_REQUEST['discardedFriends']);
$friendCount = count($friendNames);
$friendNamesQueryPart = NULL;
for ($i = 0; $i < $friendCount; $i++)
{
if (strlen($friendNames[$i]) > 0)
{
if ($i > 0 )
{
$friendNamesQueryPart .= ",";
}
$friendNamesQueryPart .= "'".$friendNames[$i]."'";
}
}
if ($friendNamesQueryPart != NULL)
{
$sqlDiscard = "delete from friends
where requestId = ".$userId." and
providerId in (select Id from users where username in (".$friendNamesQueryPart."));
";
}
}
if ( ($sqlApprove != NULL ? $db->query($sqlApprove) : true) &&
($sqlDiscard != NULL ? $db->query($sqlDiscard) : true)
)
{
$out = SUCCESSFUL;
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
break;
default:
$out = FAILED;
break;
}
echo $out;
///////////////////////////////////////////////////////////////
function authenticateUser($db, $username, $password, $port)
{
$sql = "select Id from users
where username = '".$username."' and password = '".$password."'
limit 1";
$out = NULL;
if ($result = $db->query($sql))
{
if ($row = $db->fetchObject($result))
{
$out = $row->Id;
$sql = "update users set authenticationTime = NOW(),
IP = '".$_SERVER["REMOTE_ADDR"]."' ,
port = ".$port."
where Id = ".$row->Id."
limit 1";
$db->query($sql);
}
}
return $out;
}
?>
and the second code is working on file upload
$base=$_REQUEST['image'];
echo $base;
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploaded_image'.time().'.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
both the codes are working properly.
what i have tried to do is make another case in the switch statement in which the action is "filesharing"
Won't that work?
case "filesharing":$base=$_REQUEST['image'];
//echo $base;
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploaded_image'.time().'.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
$out .= "Image upload complete!!, Please check your php file directory……";
break;
can anyone please give some suggestions?
So you have basically two files with two separate bits of functionality. The obvious solution would be to encapsulate each bit of code with a function i.e.
function query() {
/* your database query code here */
}
function file_upload() {
/* your file upload code here */
}
... and then encapsulate those functions in a class.
class MyCoolClass {
function query() {
/* your database query code here */
}
function file_upload() {
/* your file upload code here */
}
}
The advantages (and disadvantages) of Object Oriented Programming have been done to death, just have a google for it and you will undoubtedly find many wonderful, wonderful resources.