I am working on a site where people can get a bitcoin adres. When I do the GET request to the file, it gives a response of HTTP error 500. But I can't find any wrong things. Her is my script:
<?php
ob_start();
session_start();
error_reporting(0);
include("../includes/config.php");
$db = new mysqli($CONF['host'], $CONF['user'], $CONF['pass'], $CONF['name']);
if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
$db->set_charset("utf8");
$settingsQuery = $db->query("SELECT * FROM btc_settings ORDER BY id DESC LIMIT 1");
$settings = $settingsQuery->fetch_assoc();
include("../includes/block_io.php");
include("../includes/functions.php");
//include(getLanguage($settings['url'],null,2));
if(checkSession()) {
$type = protect($_GET['type']);
if($type == "receive") {
} elseif($type == "new_address") {
$nums = $db->query("SELECT * FROM btc_users_addresses WHERE uid='".$_SESSION['btc_uid']."'");
if($nums->num_rows > $settings['max_addresses_per_account']) {
$data['status'] = 'error';
$data['msg'] = error("You've reached the limit of wallet addresses. Max: $settings[max_addresses_per_account]");
} else {
$label = protect($_POST['label']);
if(!empty($label) && !isValidUsername($label)) { $data['status'] = 'error'; $data['msg'] = error("Please enter valid label. Use only characters and symbols - and _."); }
else {
if(empty($label)) { $label = randomHash(7); }
$username = idinfo($_SESSION['btc_uid'],"username");
$generate_address = btc_generate_address($username,$label);
if($generate_address) {
$data['status'] = 'success';
$data['msg'] = success("Your new address is <b>" . $generate_address . "</b>.");
} else {
$data['status'] = 'error';
$data['msg'] = error("Error with creating address. Please try again.");
}
}
}
echo json_encode($data);
} elseif($type == "send_bitcoins") {
$address = protect($_GET['from_address']);
$to_address = protect($_POST['to_address']);
$amount = protect($_POST['amount']);
$secret_pin = protect($_POST['secret_pin']);
$secret_pin = md5($secret_pin);
$check = $db->query("SELECT * FROM btc_users_addresses WHERE uid='".$_SESSION[btc_uid]."' and address='$address'");
if($check->num_rows==0) {
$data['status'] = 'error';
$data['msg'] = error("This wallet address is not yours!");
} elseif(empty($address) or empty($to_address) or empty($amount)) {
$data['status'] = 'error';
$data['msg'] = error("All fields are required.");
} elseif(!is_numeric($amount)) {
$data['status'] = 'error';
$data['msg'] = error("Please enter Bitcoin amount with numbers. Format: 0.000000");
} elseif(idinfo($_SESSION['btc_uid'],"secret_pin") && idinfo($_SESSION['btc_uid'],"secret_pin") !== $secret_pin) {
$data['status'] = 'error';
$data['msg'] = error("Wrong Secret PIN!");
} else {
$row = $check->fetch_assoc();
$total = $row['available_balance'];
$total = $total - 0.0008;
$total = $total - $settings['withdrawal_comission'];
if($total < 0) { $total = '0.0000'; }
if($amount > $total) {
$data['status'] = 'error';
$data['msg'] = error("Total available minus fees <b>" . $total . "</b> BTC.");
} else {
$newamount = $row['available_balance']-$amount;
$newamount = $newamount - 0.0008 - $settings['withdrawal_comission'];
$license_query = $db->query("SELECT * FROM btc_blockio_licenses WHERE id='".$row[lid]."' ORDER BY id");
$license = $license_query->fetch_assoc();
$apiKey = $license['license'];
$pin = $license['secret_pin'];
$version = 2; // the API version
$block_io = new BlockIo($apiKey, $pin, $version);
$withdrawal = $block_io->withdraw_from_addresses(array('amounts' => $amount, 'from_addresses' => $address, 'to_addresses' => $to_address));
$withdrawal = $block_io->withdraw_from_addresses(array('amounts' => $settings[withdrawal_comission], 'from_addresses' => $address, 'to_addresses' => $license[address]));
$data['status'] = 'success';
$data['msg'] = success("You sent <b>" . $amount . "</b> BTC to <b>" . $to_address . "</b> successfully.");
$data['btc_total'] = $newamount;
}
}
echo json_encode($data);
} elseif($type == "receive_to_address") {
} elseif($type == "archive_address") {
$address_id = protect($_GET['address_id']);
$query = $db->query("SELECT * FROM btc_users_addresses WHERE uid='".$_SESSION[btc_uid]."' and id='".$address_id."'");
if($query->num_rows>0) {
$row = $query->fetch_assoc();
if($row['archived'] == "1") {
echo 'Your wallet address <b>'.$row[address].'</b> is already archived.';
} else {
$update = $db->query("UPDATE btc_users_addresses SET archived='1' WHERE id='".$row[id]."'");
echo 'Your wallet address <b>'.$row[address].'</b> was archived.';
}
} else {
echo 'This wallet address is not yours!';
}
} elseif($type == "unarchive_address") {
$address_id = protect($_GET['address_id']);
$query = $db->query("SELECT * FROM btc_users_addresses WHERE uid='".$_SESSION[btc_uid]."' and id='".$address_id."'");
if($query->num_rows>0) {
$row = $query->fetch_assoc();
if($row['archived'] == "0") {
echo 'Your wallet address <b>'.$row[address].'</b> is already unarchived.';
} else {
$update = $db->query("UPDATE btc_users_addresses SET archived='0' WHERE id='".$row[id]."'");
echo 'Your wallet address <b>'.$row[address].'</b> was unarchived.';
}
} else {
echo 'This wallet address is not yours!';
}
} else { }
}
?>
Thank you for helping me out! It must to give the address back...
Related
How I can let user login from android app, using codeigniter api.
JSON response..
I want use password_hash and password_verify method for more security.
I tryed to password_verify in model, but getting error 1 wrong password. If I debug my app I can see it tries to post password what is not encrypted, but I think this password must be checked in Model.
controller:
public function login() {
$response = array("success" => 0, "error" => 0);
if (isset($_POST['email']) && $_POST['email'] != '') {
$device_token = $_POST['device_token'];
$email = $_POST['email'];
$password = $_POST['password'];
$device_type = $_POST['device_type'];
$data = $this->Registration_model->login($email,$password,$device_token,$device_type);
if ($data) {
$user_id = $data['u']->id;
$status_level = $this->Freelancer_model->service_level($user_id);//Bronze,silver..
$discount = $this->Registration_model->discountDetails($user_id);
if (!empty($discount)) {
$discount = $discount;
} else {
$discount ='';
}
if ($data['u']->approve_status == 1) {
$response["error"] = 0;
$response["success"] = 1;
$response["message"] = "success";
$image = base_url().'upload/'.$data['u']->user_image;
$response["data"]["user_id"] = $data['u']->id;
$response["data"]["user_image"] = $image;
$response["data"]["user_type"] = $data['u']->user_type;
$response["data"]["referral_code"] = $data['u']->referral_code;
$response["data"]["device_token"] = $data['u']->device_token;
$response["data"]["company_name"] = $data['u']->company_name;
$response["data"]["reg_no"] = $data['u']->registration_no;
$response["data"]["first_name"] = $data['u']->first_name;
$response["data"]["last_name"] = $data['u']->last_name;
$response["data"]["dob"] = $data['u']->dob;
$response["data"]["address"] = $data['u']->address;
$response["data"]["lat"] = $data['u']->lat;
$response["data"]["long"] = $data['u']->long;
$response["data"]["mobile"] = $data['u']->mobile;
$response["data"]["email"] = $data['u']->email;
$response["data"]["password"] = $data['u']->password;
$response["data"]["gender"] = $data['u']->gender;
$response["data"]["about"] = $data['u']->about;
$response["data"]["address_acceptance"] = $data['u']->address_acceptance;
$response["data"]["availability"] = $data['u']->availability;
$response["data"]["canceling_policy"] = $data['u']->canceling_policy;
$response["data"]["acceptance"] = $data['u']->acceptance;
$response["data"]["seen_status"] = $data['u']->seen_status; // 0=not, 1=yes
$response["data"]["approv_status"] = $data['u']->approve_status;
$response["data"]["complete_serviceLevel"]= $status_level;
$response["account"] = $data['a'];
$response["discount"] = $discount;
echo json_encode($response);
} else {
$response["error"] = 2;
$response["success"] = 0;
$response["message"] = "User is not approved";
echo json_encode($response);
}
} else {
$response["error"] = 1;
$response["success"] = 0;
$response["message"] = "Enter correct email and password";
echo json_encode($response);
}
} else {
$response["error"]=4;
$response["message"]= "Access denied";
echo json_encode($response);
}
}
model:
public function login($email, $password, $device_token, $device_type) {
$r = $this->db->get_where('registration', array('email'=>$email, 'password'=>$password));
$count = $r->num_rows();
if ($count > 1) {
$this->db->select('id,email,user_type');
$this->db->from('registration');
$this->db->where('email',$email);
$cc = $this->db->get()->result();
$response["error"] = 0;
$response["success"] = 1;
$response["message"] = "Success, Which account does you want to login?";
$response["data"] = $cc;
echo json_encode($response);
die();
} else if ($count == 1) {
$r1 = $r->row();
$id = $r1->id;
$this->db->where('id',$id);
$update =$this->db->update('registration',array('device_token' => $device_token,'device_type' => $device_type));
//$id = $r1->id;
$r2 = $this->db->get_where('accountdetails', array('user_id' => $id))->result();
$data= array(
"u" =>$r1,
"a" =>$r2
);
return $data;
} else {
return false;
}
}
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 am trying to pass a strret address from my application to my PHP server.
when i print the address in the Log.d i got:
העמק 57 גבעת אלה
but the server response is:
$place = $_POST["address"];
$output["addressEditText"] = $place;
and this is what i got from the server:
???? 57 ???? ???
i need that the server will support also hebrew alphabet.
just for notice this response is not from the DB i just copy and past the value of the parameter into the output response.
this is my page code:
<?php
/**
* Created by PhpStorm.
* User: matant
* Date: 9/17/2015
* Time: 2:56 PM
*/
include 'response_process.php';
include 'gcm.php';
require_once 'DBFunctions.php';
class CreateEvent implements ResponseProcess {
public function dataProcess($dblink)
{
$output = array();
$dbF = new DBFunctions($dblink);
$sport = $_POST["sport_type"];
$date = date("Y-m-d",strtotime(str_replace('/','-',$_POST["date"])));
$s_time =$date." ".$_POST["s_time"];
$e_time = $date." ".$_POST["e_time"];
$s_time =date("Y-m-d H:i:s",strtotime($s_time));
$e_time = date("Y-m-d H:i:s",strtotime($e_time));
$lon = $_POST["lon"];
$lat = $_POST["lat"];
$event_type = $_POST["event_type"];
$max_p = $_POST["max_participants"];
$sched = $_POST["scheduled"];
$gen = $_POST["gender"];
$min_age = $_POST["minAge"];
$manager = $_POST["manager"];
$mng_name = $_POST["manager_name"];
$place = $_POST["address"];
$output["addressEditText"] = $place;
$mode = $_POST["mode"];
if($sched == "true"){
$exp_val = "";
$type = "";
$repeat = $_POST["repeat"];
$duration = $_POST["duration"];
$expiration_tag = $_POST["sched_tag"];
switch($expiration_tag){
case "unlimited":{
$exp_val = "unlimited";
$type = $exp_val;
break;
}
case "Year":{
$exp_val = date("Y-m-d",strtotime($_POST["value"]));
$type = "date";
break;
}
case "events_number":
$exp_val = $_POST["value"];
$type = "counter";
break;
case "by_date":
$exp_val = date("Y-m-d",strtotime($_POST["value"]));
$type = "date";
break;
}
$output["repeat"] = $repeat;
$output["duration"] = $duration;
$output["exp_val"] = $exp_val;
$output["type"] = $type;
}
if($mode == "edit"){
$event_id = $_POST["event_id"];
$invited_users_size = 0;
if(isset($_POST["invitedUsers"])){
$participants = $_POST["invitedUsers"];
$json_uesr_ids = json_decode($participants);
$invited_users_size = count($json_uesr_ids);
}
if(isset($_POST["invitedUsers"])){
$result_q = $dbF -> DeleteEventFromAttending($event_id);
if(!$result_q)
{
$output["flag"]= "delete failed";
$output["msg"] = $result_q;
return json_encode($output);
}else {
$participants = $_POST["invitedUsers"];
$json_uesr_ids = json_decode($participants);
$output["json_users"] = $json_uesr_ids;
$get_users_reg_ids = $dbF->getUserSByIds($json_uesr_ids, count($json_uesr_ids));
$reg_ids = array();
$i = 0;
while ($row_user = mysqli_fetch_assoc($get_users_reg_ids)) {
$reg_ids[$i] = $row_user["gcm_id"];
$i++;
}
$output["ids"] = $reg_ids;
$output["size"] = count($json_uesr_ids);
$result_q = $dbF->InsertIntoAttendingUpdatedUsers($json_uesr_ids, $event_id, count($json_uesr_ids),"awaiting reply");
$output["insert_res"] = $result_q;
if (!$result_q) {
$output["flag"] = "update_insert failed";
$output["msg"] = $result_q;
return json_encode($output);
} else {
$output["flag"] = "update_success";
$output["msg"] = $result_q;
}
//send notification on update to users
$gcm = new GCM();
$data = array();
$message = "The event " . $sport . " in " . $place . " in " . $date . " updated,Please click on Join in order to confirm registration.";
$data['message'] = $message;
$data['date'] = $date;
$data['private'] = $event_type;
$data['start_time'] = date("H:i", strtotime($s_time));
$data['end_time'] = date("H:i", strtotime($e_time));
$data['inviter'] = $mng_name;
$data['event_id'] = $event_id;
$data['location'] = $place;
$gcm_res = $gcm->send_notification($reg_ids, $data);
$output["gcm_res"] = $gcm_res;
//send notification on update to users
}
}
$result_q = $dbF ->checkIfEventIsExistBeforeUpdate($lon,$lat,$date,$s_time,$e_time,$event_id);
if(!$result_q)
{
$output["flag"]= "select failed";
$output["msg"] = $result_q;
return json_encode($output);
}
else {
$no_of_rows_check_event = mysqli_num_rows($result_q);
if ($no_of_rows_check_event > 0) {
$output["flag"] = "failed";
$output["msg"] = "Place is already occupied in this time";
}else{
$result_q = $dbF -> UpdateEvent($event_id,$sport,$s_time,$e_time,$place,$lon,$lat,$event_type,$gen,$min_age,$max_p,'1',$invited_users_size,$sched,$output["repeat"],$output["duration"],$output["type"],$output["exp_val"]);
$output["res"] = $result_q;
$output["sched"] = $sched;
if($sched == "true")
{
$output["sched_res"] = "true";
}
else{
$output["sched_res"] = "false";
}
$affected_row = mysqli_affected_rows($dblink);
if(!$result_q)
{
$output["flag"]= "update_failed";
$output["query_res"] = $result_q;
$output["msg"] = "failed to update event";
$output["affected row"] = $affected_row;
}
else{
$output["flag"]= "update_success";
$output["query_res"] = $result_q;
$output["msg"] = "success to update event";
$output["affected row"] = $affected_row;
}
}
}
}
else{
$result_q = $dbF ->checkIfEventIsExist($lon,$lat,$date,$s_time,$e_time);
$output["query"] = $result_q;
if(!$result_q)
{
$output["flag"]= "select failed";
$output["msg"] = $result_q;
return json_encode($output);
}
else{
$no_of_rows_check_event = mysqli_num_rows($result_q);
$output["no_of_rows"] = $no_of_rows_check_event;
if($no_of_rows_check_event > 0)
{
$output["flag"] = "failed";
$output["msg"] = "Place is already occupied in this time";
}else{
$output["flag"] = "success";
$output["msg"] = "insert event";
$num_of_invited_users = 0;
if(isset($_POST["jsoninvited"])){
$json = $_POST["jsoninvited"];
$json = json_decode($json);
$num_of_invited_users = (count($json));
$output["size_invited"] = count($json);
}
$result = $dbF -> InsertNewEvent($manager,$sport,$s_time,$e_time,$place,$lon,$lat,$event_type,$gen,$min_age,$max_p,$num_of_invited_users,$sched,$output["repeat"],$output["duration"],$output["type"],$output["exp_val"]);
if (!$result) {
$output["flag"] = "failed to create event";
// return (json_encode($output));
}
else{
if(isset($_POST["jsoninvited"])){
$event_s_res = $dbF ->getEventIdByDateAndTime($date,$s_time,$e_time);
$output["my_squery"] =$event_s_res;
if(!$event_s_res)
{
$output["flag"] = "failed";
$output["msg"] = "Event id not found";
}
else{
$row = mysqli_fetch_assoc($event_s_res);
$no_of_rows = mysqli_num_rows($event_s_res);
if($no_of_rows > 1 || $no_of_rows == 0)
{
$output["flag"] = "failed";
$output["msg"] = "Event id not found";
}
else{
$event_id = $row["event_id"];
$json = $_POST["jsoninvited"];
$json = json_decode($json);
$output["size_invited"] = count($json);
$size_of_param = (count($json));
$event_user_s_res = $dbF -> getUserIdAndRegId($json,$size_of_param);
if(!$event_user_s_res)
{
$output["flag"] = "failed";
$output["msg"] = "user id not found";
}
$result = $dbF->insertIntoAttendingTable($event_user_s_res, $event_id, $size_of_param);
$insert_query_res = $result["res"];
$output["query"] = $result["query"];
$registration_ids = $result["reg_ids"];
if(!$insert_query_res)
{
$output["flag"] = "failed";
$output["msg"] = "failed to insert to attending table";
}
else{
$output["registred_ids"] = $registration_ids;
$output["msg"] = "success to insert into attending";
$gcm = new GCM();
$data = array();
$message = "Would like to invite you to play ".$sport.", Please click on Join in order to add you into the event.";
$data['message'] = $message;
$data['date'] = $date;
$data['start_time'] = date("H:i",strtotime($s_time));
$data['end_time'] = date("H:i",strtotime($e_time));
$data['inviter'] = $mng_name;
$data['private'] = $event_type;
$data['event_id'] = $event_id;
$data['location'] = $place;
$output["gcm_message"]=$data;
$gcm_res = $gcm->send_notification($registration_ids,$data);
$output["gcm_res"] = $gcm_res;
} //els of $insert_query_res
} //else of $no_of_rows > 1 || $no_of_rows == 0
} // else of $event_s_res
} //if isset($_POST["invitedUsers"]
} // if $result
}
}
}//get inside creating event mode.
return json_encode($output);
}
}
this is my client side:
public void sendDataToDBController() {
BasicNameValuePair mode_req;
LatLng lonlat = locationTool.getLocationFromAddress(addressEditText.getText().toString());
if(lonlat == null)
{
Log.d("location is:","location not found");
sv.scrollTo(0, 0);
addressEditText.setError("Location was not found!");
return;
}
Log.d("found location",lonlat.latitude+""+lonlat.longitude);
BasicNameValuePair tagreq = new BasicNameValuePair(Constants.TAG_REQUEST,"create_event");
Log.d("event mode",mode);
if(mode.equals(Constants.MODE_CREATE))
{
Log.d("event mode","create");
mode_req = new BasicNameValuePair(Constants.TAG_MODE,Constants.MODE_CREATE);
}
else {
Log.d("event mode","update");
mode_req = new BasicNameValuePair(Constants.TAG_MODE, Constants.MODE_UPDATE);
}
Log.d("addressEditText",addressEditText.getText().toString());
BasicNameValuePair address = new BasicNameValuePair("address",addressEditText.getText().toString());
BasicNameValuePair sport = new BasicNameValuePair("sport_type",sportSpinner.getSelectedItem().toString());
Log.d("sport_type",sportSpinner.getSelectedItem().toString());
BasicNameValuePair date = new BasicNameValuePair("date",btnStartdate.getText().toString());
BasicNameValuePair startTime = new BasicNameValuePair("s_time",btnstartTime.getText().toString());
BasicNameValuePair endTime = new BasicNameValuePair("e_time",btnendTime.getText().toString());
BasicNameValuePair longtitude = new BasicNameValuePair(Constants.TAG_LONG,String.valueOf(lonlat.longitude));
BasicNameValuePair latitude = new BasicNameValuePair(Constants.TAG_LAT,String.valueOf(lonlat.latitude));
BasicNameValuePair event_type = new BasicNameValuePair("event_type",String.valueOf(privateEventCbox.isChecked()));
BasicNameValuePair gender = new BasicNameValuePair(Constants.TAG_GEN,String.valueOf(genderSpinner.getSelectedItem().toString()));
BasicNameValuePair min_age = new BasicNameValuePair("minAge",String.valueOf(minAgeEditText.getText()));
BasicNameValuePair participants = new BasicNameValuePair("max_participants",maxParticipantsEdittext.getText().toString());
BasicNameValuePair scheduled = new BasicNameValuePair("scheduled",String.valueOf(reccuringEventCbox.isChecked()));
BasicNameValuePair mob_manager = new BasicNameValuePair("manager",sm.getUserDetails().get(Constants.TAG_USERID));
BasicNameValuePair manager_name = new BasicNameValuePair("manager_name",sm.getUserDetails().get(Constants.TAG_NAME));
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
if(mode.equals(Constants.MODE_UPDATE)){
BasicNameValuePair eventId = new BasicNameValuePair("event_id",event_id);
nameValuePairList.add(eventId);
}
if(invitedUsers != null)
{
if(invitedUsers.size() > 0)
{
String[] users = new String[invitedUsers.size()];
JSONArray invited = new JSONArray();
for(int i=0 ; i < invitedUsers.size(); i++)
{
if(mode.equals(Constants.MODE_CREATE))
users[i]= invitedUsers.get(i).getMobile();
else
users[i]= invitedUsers.get(i).getId();
invited.put(users[i]);
}
String json = invited.toString();
Log.d("string array", Arrays.toString(users));
BasicNameValuePair invitedusers = new BasicNameValuePair("invitedUsers",Arrays.toString(users));
BasicNameValuePair jsonInvited = new BasicNameValuePair("jsoninvited",json);
nameValuePairList.add(invitedusers);
nameValuePairList.add(jsonInvited);
}
}
if(sched_res != null && reccuringEventCbox.isChecked() == true){
String repeatval ="";
String duration ="";
String tag = "";
String val = "";
BasicNameValuePair sched_val = null;
try {
repeatval = sched_res.getString("repeat");
duration = sched_res.getString("duration");
JSONArray jsonarr = new JSONArray(sched_res.getString("radio_group"));
tag = jsonarr.getJSONObject(0).getString(Constants.TAG_REQUEST);
sched_val = new BasicNameValuePair("value",jsonarr.getJSONObject(0).getString("val"));
} catch (JSONException e) {
e.printStackTrace();
}
BasicNameValuePair sched_repeat = new BasicNameValuePair("repeat",repeatval);
BasicNameValuePair sched_duration = new BasicNameValuePair("duration",duration);
BasicNameValuePair sched_tag = new BasicNameValuePair("sched_tag",tag);
nameValuePairList.add(sched_repeat);
nameValuePairList.add(sched_duration);
nameValuePairList.add(sched_tag);
if(sched_val != null)
nameValuePairList.add(sched_val);
}
nameValuePairList.add(manager_name);
nameValuePairList.add(mob_manager);
nameValuePairList.add(tagreq);
nameValuePairList.add(mode_req);
nameValuePairList.add(sport);
nameValuePairList.add(date);
nameValuePairList.add(address);
nameValuePairList.add(startTime);
nameValuePairList.add(endTime);
nameValuePairList.add(min_age);
nameValuePairList.add(longtitude);
nameValuePairList.add(latitude);
nameValuePairList.add(event_type);
nameValuePairList.add(participants);
nameValuePairList.add(scheduled);
nameValuePairList.add(gender);
dbController = new DBcontroller(getActivity().getApplicationContext(),this);
dbController.execute(nameValuePairList);
}
after searching for a while i solved this issue by:
add this code in my server side:
if(!mysqli_set_charset($dblink, 'utf8')) {
echo 'the connection is not in utf8';
exit();
}
i want to add manual magento login and registration webservice for my android project. and how to do that with the help of php? i've tried these steps for login
<?php
class My_Module_Controller extends Mage_Core_Controller_Front_Action {
public function indexAction() {
// if customer is not logged in
if(!Mage::getSingleton('customer/session')->isLoggedIn())
{
// get the email and load the customer by id
$login = $this->getRequest()->getPost('login');
$email = $login['hi#gmail.com'];
$customer = Mage::getModel('customer/customer')
->setWebsiteId(Mage::app()->getStore()
->getWebsiteId())->loadByEmail($email);
$quote = Mage::getSingleton('checkout/cart')->getQuote();
//If the customer exists, log them in by forwarding to loginPost
if($customer->getId())
{
// just make the customer log in
$mysession = Mage::getSingleton('customer/session');
$mysession->setBeforeAuthUrl(Mage::getUrl('checkout/cart'));
$mysession->setAfterAuthUrl(Mage::getUrl('checkout/cart'));
$this->_forward('login','account','customer');
}
else
{
//There is no customer with that email.
}
}
$this->_redirect('checkout/cart');
return;
}
}
?>
and this for registration
public function indexAction()
{
$this->loadLayout();
$this->renderLayout();
}
public function loginAction()
{
$session = Mage::getSingleton('customer/session');
if ($session->isLoggedIn()) {
// is already login redirect to account page
return;
}
$result = array('success' => false);
if ($this->getRequest()->isPost())
{
$login_data = $this->getRequest()->getPost('login');
if (empty($login_data['username']) || empty($login_data['password'])) {
$result['error'] = Mage::helper('onepagecheckout')->__('Login and password are required.');
}
else
{
try
{
$session->login($login_data['username'], $login_data['password']);
$result['success'] = true;
$result['redirect'] = Mage::getUrl('*/*/index');
}
catch (Mage_Core_Exception $e)
{
switch ($e->getCode()) {
case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
$message = Mage::helper('onepagecheckout')->__('Email is not confirmed. Resend confirmation email.', Mage::helper('customer')->getEmailConfirmationUrl($login_data['username']));
break;
default:
$message = $e->getMessage();
}
$result['error'] = $message;
$session->setUsername($login_data['username']);
}
}
}
$this->_redirect('customer/account/');
//$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
}
but i am unable to do it.and how can i make it run
I took this code from net by googling it
For login
$websiteId = Mage::getModel('core/store')->load($store)->getWebsiteId();
$res = array();
$res["username"] = $username;
$res["password"] = base64_decode($password);
$login_status = 1;
try{
$login_customer_result = Mage::getModel('customer/customer')->setWebsiteId($websiteId)->authenticate($username, base64_decode($password));
$login_customer = Mage::getModel('customer/customer')->setWebsiteId($websiteId);
$login_customer->loadByEmail($username);
$res["firstname"] = $login_customer->firstname;
$res["lastname"] = $login_customer->lastname;
$res["id"] = $login_customer->getId();
//$res["password"]
//$res["password"]
}
catch( Exception $e ){
$login_status = 0;
}
$res["login_status"] = $login_status;
return $res;
Fir registration
$res = array();
$websiteId = Mage::getModel('core/store')->load($store)->getWebsiteId();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId;
$customer->setCurrentStore($store);
// echo 'Phase 2';
try {
// If new, save customer information
$customer->firstname = $firstname;
$customer->lastname = $lastname;
$customer->email = $email;
$customer->password_hash = md5(base64_decode($password));
$res["email"] =$email;
$res["firstname"] =$firstname;
$res["lastname"] =$lastname;
$res["password"] =$password;
$res["status"] = 0;
$res["id"] = 0;
$cust = Mage::getModel('customer/customer')
->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
->loadByEmail($email);
//check exists email address of users
if ($cust->getId()) {
$res["id"] = $cust->getId();
$res["status"] = 0;
}else {
//echo 'Phase 2.5';
if($customer->save()){
$customer->sendNewAccountEmail('confirmed');
$this->send_Password_Mail_to_NewUser($firstname, base64_decode($password), $email);
$res["id"] = $customer->getId();
$res["status"] = 1;
}
else{
//echo "Already Exist";
$exist_customer = Mage::getModel("customer/customer");
$exist_customer->setWebsiteId($websiteId);
$exist_customer->setCurrentStore($store);
$exist_customer->loadByEmail($email);
$res["id"] = $exist_customer->getId();
$res["status"] = 1;
//echo "An error occured while saving customer";
}
}
//echo 'Phase 3';
}
catch(Exception $e){
//echo "Already Exist Exception";
try {
$exist_customer = Mage::getModel("customer/customer");
$exist_customer->setWebsiteId($websiteId);
$exist_customer->setCurrentStore($store);
$exist_customer->loadByEmail($email);
$res["id"] = $exist_customer->getId();
$res["status"] = 1;
}
catch(Exception $ex) {
$res["id"] = -1;
$res["status"] = 0;
}
}
return $res;
I am not getting any errors but the database does not get updated. Please render assistance. Here is my code.
<?php
ob_start();
include("dbinc.php");
$msg = "";
if($_SESSION['usertype'] != "admin"){
header("Location: index.php");
exit;
}
$pagetitle = "Sync Job Details";
include("header.php");
if(isset($_POST['Submitaccount'])){
$allowedusers = $_POST['users'];
$accountid = trim($_POST['accountid']);
if(!$_POST['copyperms']) $_POST['copyperms']='N';
if(!$_POST['allusers']) $_POST['allusers']='N';
if(!$_POST['enabled']) $_POST['enabled']='N';
if(!$_POST['servertime']) $_POST['servertime']='N';
if(!$_POST['delremovals']) $_POST['delremovals']='N';
unset($_POST['Submitaccount']);
unset($_POST['accountid']);
unset($_POST['users']);
// $qpart = "";
$notmust = array("email" , "skip" , "comments" , "firstmod");
foreach($_POST as $key=>$val){
if(!trim($val) && !in_array($key , $notmust)) {
$err = 1;
$empty = "$key";
break;
}
$qpart .= "`$key` = '".mysql_escape_string($val)."' , " ;
}
if($qpart) $qpart = substr($qpart , 0 , -2);
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
}
}
if(!$err){
if(!$accountid){
$q = "INSERT into accounts SET $qpart ";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
if($_POST['allusers']!= "Y" && is_array($allowedusers)){
mysql_query("DELETE from accountusers WHERE accountid = '$accountid'");
foreach($allowedusers as $userid){
list($alljobs) = mysql_fetch_row(mysql_query("SELECT alljobs from users WHERE id= '$userid'"));
if($alljobs != "Y") {
mysql_query("INSERT into accountusers SET userid = '$userid' , accountid = '$accountid'");
}
}
}else{
mysql_query("DELETE from accountusers WHERE accountid = '$accountid'");
}
header("location: accountslist.php?done=1");
exit;
}
}
// if(isset($_GET['id'])){
// $record = mysql_fetch_assoc(mysql_query("SELECT * from accounts WHERE id = '$_GET[id]'"));
// foreach($record as $key=>$val) $record[$key] = stripslashes($val);
// }
if(isset($_GET['id'])){
$record = mysql_fetch_assoc(mysql_query("SELECT * from accounts WHERE id = '$_GET[id]'"));
foreach($record as $key=>$val) $record[$key] = stripslashes($val);
}
// if($err ==1)
// {
// $record = $_POST;
// foreach($record as $key=>$val)
// $record[$key] = stripslashes($val);
// $msg ="Please fill the empty field";
// }
if( isset($err) && $err == 1 )
{
$record = $_POST;
foreach($record as $key=>$val) $record[$key] = stripslashes($val);
$msg ="Please fill the empty field";
}
if( isset($err) && $err == 2)
{
$msg = "The name has already been used.";
}
?>
I feel your frustration. If i could assist you i would. People in this forum are scared to answer you as they don't want to lose reputation points as the question was marked down to -4. I suggest do some more research and post your question eslewhere.