call php file on incoming call (asterisk) - php

im new in asterisk i searched like 10hour for example how trigger a php file on incoming call to get caller ID and show to user who is calling
and i found some result and tested them
codes below are Working(copy pasted from someone example) But problem is its work(trigger php file) only when i call someone from voip and NOT when someone from outside call me and that is what i need
so can you dear programmers help me what is my mistake and gimme a working example? i know the codes in extensions_custom.conf need to be change but well im not very good at voip programming and i have no clue how to fix it
extensions_custom.conf codes:
[macro-dialout-trunk-predial-hook]
exten => s,1,Verbose(Incoming call from Sip line CallerID=${CALLERID(all)})
exten => s,2,AGI(testest.php,${CALLERID(all)})
and my test php file
#!/usr/bin/php -q
<?php
$query = $argv[1];
file_get_contents('http://192.168.1.6/crm/test.php?s=test');
$fh = fopen('test.txt','w+');
fwrite($fh,$query);
fclose($fh);
?>

Check macro-dial-one (need change it in extensions_ovveride_freepbx.conf) or create custom context on incoming (extensions_custom.conf) and change to that context all your trunks.

i FOund answer i put it in here So everyone can use because there is like no example of this simple code anywhere
<?php
$socket = fsockopen("192.168.1.100","5038", $errno, $errstr,10);
if (!$socket){
echo "$errstr ($errno)\n";
}else{
//include('config.php');
//$db = db();
fputs($socket, "Action: Login\r\n");
fputs($socket, "UserName: admin\r\n");
fputs($socket, "Secret: *********\r\n\r\n");
//fputs($socket, "Action: WaitEvent\r\n");
//fputs($socket, "Action: Logoff\r\n\r\n");
$event = "";
while($ret = fgets($socket)){
if(substr($ret,0,6) == "Event:"){
$e = explode(':', $ret);
$event = trim($e[1]);
}
if($event == "DeviceStateChange"){
$data = explode(':', $ret);
if($data[0] == "Timestamp"){
$ts = floor(trim($data[1]));
}
if($data[0] == "Device" && substr(trim($data[1]),0,3) == 'SIP'){
$d = explode('/', trim($data[1]));
$dev = trim($d[1]);
$device = "";
if(is_numeric($dev)){
$device = $dev;
}
}
if($data[0] == "State" && $device != ""){
$state = trim($data[1]);
if($state == "NOT_INUSE"){
//Clear CID fields and update presence state
echo 'NOT_inuse: state:'.$state.'-device: '.$device;//YOUR CODE
// $sql = "update asterisk.web_presence set state='$state',cidnum = NULL, cidname = NULL, inorout = NULL, callstart = NULL where ext='$device'";
// mysql_query($sql);
}else{
//Update presence state
echo 'else NOT_inuse: state:'.$state.'-device: '.$device;//YOUR CODE
$sql = "update asterisk.web_presence set state='$state' where ext='$device'";
// mysql_query($sql);
}
$event = "";
$device = "";
}
}
if($event == "DialBegin"){
$data = explode(':', $ret);
if($data[0] == "Timestamp"){
$ts = floor(trim($data[1]));
}
if($data[0] == "Channel"){
$c = explode('/',trim($data[1]));
$c2 = explode('-', trim($c[1]));
$channel = trim($c2[0]);
}
if($data[0] == "CallerIDNum"){
$cidnum = trim($data[1]);
}
if($data[0] == "CallerIDName"){
$cidname = trim($data[1]);
}
if($data[0] == "DialString"){
if(substr(trim($data[1]),0,3) == 'SIP' || is_numeric(trim($data[1]))){
if(is_numeric(trim($data[1]))){
$exten = trim($data[1]);
}else{
$e = explode('/', trim($data[1]));
$exten = trim($e[1]);
}
$time = time();
//query("insert into callq(mobile,exten,time_stamp) values('$cidnum','$exten',$time)",$db);//YOUR CODE
echo 'dialstring-cidnum:'.$cidnum.'-cidname:'.$cidname.'-ts:'.$ts.'-ext:'.$exten;
//Update inbound presence call
/// $sql = "update asterisk.web_presence set cidnum = '$cidnum', cidname = '$cidname', inorout='I', callstart='$ts' where ext='$exten' and cidnum is null";//YOUR CODE
// mysql_query($sql);
// $sql = "update asterisk.web_presence set cidnum = '$exten', inorout='O', callstart='$ts' where ext='$channel' and cidnum is null";//YOUR CODE
// mysql_query($sql);
}else{
$e = explode('#', trim($data[1]));
$dialed = trim($e[0]);
if($channel != 'gateway'){
//Update outbound presence call
// $sql = "update asterisk.web_presence set cidnum = '$dialed', inorout='O', callstart='$ts' where ext='$channel'";
// mysql_query($sql);
}
}
$event = "";
$exten = "";
}
}
if($event == "UnParkedCall"){
$data = explode(':', $ret);
if($data[0] == "Timestamp"){
$ts = floor(trim($data[1]));
}
if($data[0] == "RetrieverChannel"){
$c = explode('/',trim($data[1]));
$c2 = explode('-', trim($c[1]));
$channel = trim($c2[0]);
}
if($data[0] == "ParkeeCallerIDNum"){
$cidnum = trim($data[1]);
}
if($data[0] == "ParkeeCallerIDName"){
$cidname = trim($data[1]);
}
if($data[0] == "ParkingSpace"){
$dialed = trim($data[1]);
$pickup = "$cidnum ($dialed)";
echo 'parked';
//Update outbound presence call
// $sql = "update asterisk.web_presence set cidnum = '$pickup', cidname='$cidname', inorout='O', state='INUSE', callstart='$ts' where ext='$channel'";
//mysql_query($sql);
$event = "";
$channel = "";
}
}
}
}
sleep(5);
exit;
fclose($socket); ?>

Related

Fatal error: Call to a member function get() on null in C:\appserv\www\Cocolani\php\req\register.php on line 4

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&reg='.$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();

Profile url unable to get result

So I am wanting to allow my members to view a profile via a url such as: mywebsite.com/account/Username
however, at the moment my members can view via the url: mywebsite.com/account?username=username.
This doesn't look profesional and I've tried nearly everything to get it to the url I'm looking to get.
(Please be aware; I'm very new to this website and cannot use it properly, If I have done anything wrong, please notify me and I will justify it.)
The code:
//get config
$config = $base->loadConfig();
full code:
https://pastebin.com/UmAmF9Rt
<?php
require('../includes/config.php');
require('../structure/base.php');
require('../structure/forum.php');
require('../structure/forum.index.php');
require('../structure/forum.thread.php');
require('../structure/forum.post.php');
require('../structure/database.php');
require('../structure/user.php');
$database = new database($db_host, $db_name, $db_user, $db_password);
$base = new base($database);
$user = new user($database);
$forum = new forum($database);
$forum_index = new forum_index($database);
$thread = new thread($database);
$post = new post($database);
$user->updateLastActive();
//get config
$config = $base->loadConfig();
//set some variables that are used a lot throughout the page
if (!empty($_GET['username'])) {
$profile_name = htmlspecialchars($_GET["username"]);
}
else{
$profile_name = $user->getUsername($_COOKIE['user'], 2);
}
$username = $user->getUsername($_COOKIE['user'], 2);
$rank = $user->getRank($username);
$f = $_GET['forum'];
$i = $_GET['id'];
//assign data to details[] array
$details['lock'] = $detail_query[0]['lock'];
$details['sticky'] = $detail_query[0]['sticky'];
$details['title'] = stripslashes(htmlentities($detail_query[0]['title']));
$details['username'] = $detail_query[0]['username'];
$details['status'] = $detail_query[0]['status'];
$details['content'] = $detail_query[0]['content'];
$details['date'] = $detail_query[0]['date'];
$details['lastedit'] = $detail_query[0]['lastedit'];
$details['qfc'] = $detail_query[0]['qfc'];
$details['moved'] = $detail_query[0]['moved'];
$details['hidden'] = $detail_query[0]['hidden'];
$details['autohiding'] = $detail_query[0]['autohiding'];
//get forum details
$forum_details = $database->processQuery("SELECT `title` FROM `forums` WHERE `id` = ?", array($f), true);
if(isset($_GET['username'])){
if($user->doesExist($_GET['username'])){;
}
}else{
if(!$user->isLoggedIn()){
$base->redirect('../login.php');
}else{
$user_s = $username;
}
}
$messages = array();
$avatar = $user->getAvatar($profile_user);
$usr = $user->getUsername($profile_user);
if($username == $profile_user && $user->isLoggedIn() && isset($_REQUEST['cust_title'])) {
$user->setTitle($username, htmlentities($_REQUEST['cust_title']));
}
if($user_s == $username && $user->isLoggedIn() && isset($_FILES['uploaded'])) {
if(isset($_REQUEST['delete'])) {
$user->setAvatar($username, '');
$messages[] = "Your avatar has been removed.";
} else {
$ok = false;
$info = getimagesize($_FILES['uploaded']['tmp_name']);
if ($_FILES['uploaded']['error'] !== UPLOAD_ERR_OK) {
$messages[] = ("Upload failed with error code " . $_FILES['uploaded']['error']);
} else if($info === FALSE) {
$messages[] = ("Unable to determine image type of uploaded file");
} else if(($info[2] !== IMAGETYPE_GIF) && ($info[2] !== IMAGETYPE_JPEG) && ($info[2] !== IMAGETYPE_PNG)) {
$messages[] = ("Not a gif/jpeg/png");
} else if($_FILES['uploaded']['size'] > 350000) {
$messages[] = "Your file is too large.";
} else if($_FILES['uploaded']['type'] == "text/php") {
$messages[] = "No PHP files";
} else {
$ok = true;
}
$target = md5(strtolower(trim($username))) .'.'. pathinfo($_FILES['uploaded']['name'])['extension'];
if($ok) {
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], "../images/avatar/" . $target)){
$messages[] = "Your avatar has been uploaded. Please allow atleast 10 minutes for it to update.";
$user->setAvatar($username, $target);
} else {
$messages[] = "Sorry, there was a problem uploading your file.";
}
}
}
}
//retrieve posts/threads
$posts = $database->processQuery("SELECT `id`,`thread`,`username`,`timestamp`,`content` FROM `posts` WHERE `username` = ? AND ". time() ." - `timestamp` < 1209600 ORDER BY `id` DESC", array($user_s), true);
$threads = $database->processQuery("SELECT `id`,`parent`,`title`,`username`,`timestamp`,`content` FROM `threads` WHERE `username` = ? AND ". time() ." - `timestamp` < 1209600 ORDER BY `id` DESC", array($user_s), true);
//type:id:forum:timestamp:(if post)thread
$list = array();
foreach($posts as $post){
//get the thread's forum/parent
$t = $database->processQuery("SELECT `parent` FROM `threads` WHERE `id` = ? LIMIT 1", array($post['thread']), true);
$list[$post['timestamp']] = 'p:'.$post['id'].':'. $t[0]['parent'] .':'.$post['timestamp'].':'.$post['thread'].':'.$post['content'];
}
//add threads
foreach($threads as $thread){
$list[$thread['timestamp']] = 't:'.$thread['id'].':'.$thread['parent'].':'.$thread['timestamp'].':'.$thread['content'];
}
//now sort them
krsort($list, SORT_NUMERIC);
$r = $database->processQuery("SELECT * FROM `users` WHERE `username` = ?", array($profile_name), true);
?>
Your best bet is to use:
.htaccess route with mod_rewrite
Try Adding a file called .htaccess in your root folder, and add something like this:
RewriteEngine on
RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /account.php?username=$username
This will tell Apache to enable mod_rewrite for this folder, and if it gets asked a URL matching the regular expression it rewrites it internally to what you want:
Refer to this answer by Niels Keurentjes: https://stackoverflow.com/a/16389034/3367509
If you are new to .htaccess look up this question: What is .htaccess file?

How do i verify query from mysql database before outputing record

In my code am trying to verify if query is true before outputing result i have tried:
require("init.php");
if(empty($_GET["book"]) && empty($_GET["url"])) {
$_SESSION["msg"] = 'Request not valid';
header("location:obinnaa.php");
}
if(isset($_GET["book"]) && isset($_GET["url"])) {
$book = $_GET['book'];
$url = $_GET['url'];
$drs = urldecode("$url");
$txt = encrypt_decrypt('decrypt', $book);
if(!preg_match('/(proc)/i', $url)) {
$_SESSION["msg"] = 'ticket printer has faild';
header("location:obinnaa.php");
exit();
} else {
$ql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
if($count < 1) {
$_SESSION["msg"] = 'Transation has oready been made by a customer please check and try again';
header("location:obinnaa.php");
exit();
}
while($riow = mysqli_fetch_assoc($ql)) {
$id = $riow["id"];
$tqty = $riow["quantity"];
for($b = 0; $b < $tqty; $b++) {
$run = rand_string(5);
$dua .= $run;
}
}
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$split = $dua;
$show_plit = str_split($split, 5);
$b = 0;
while($row = mysqli_fetch_assoc($sql)) {
$id = $row["id"];
$qty = $row["quantity"];
$oldB = $b;
$am = " ";
for(; $b < $oldB + $qty; $b++) {
$am .= "$show_plit[$b]";
$lek = mysqli_query($conn, "UPDATE books SET ticket='$am' WHERE id=$id");
}
if($lek) {
$adr = urlencode($adr = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$ty = encrypt_decrypt("encrypt", $txt);
$vars = array(
"book" => $ty,
"url" => $adr
);
$querystring = http_build_query($vars);
$adr = "viewbuy.php?" . $querystring;
header("location: $adr");
} else {
$_SESSION["msg"] = 'Transation failed unknow error';
header("location:obinnaa.php");
}
}
}
}
but i get to
$_SESSION["msg"]='Transation has oready been made by a customer please check and try again
even when the query is right what are mine doing wrong.
Check your return variable name from the query. You have $ql when it should be $sql.
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
A good IDE would flag this. NetBeans is a good free one.
Public Service Announcement:
NEVER build SQL queries straight from a URL parameter. Always sanitize your inputs and (better yet) use parameterized queries for your SQL calls. You can Google these topics for more info.

PHP SQL to VB.Net conversion

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.

how to merge two server codes written in php

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.

Categories