PHP search with multiple fields - php

I want to search data using ajax method with multiple fields search option (e.g. name, college, department, year, nationality e.t.c ). I have insert name for searching and rest of fields are empty than it went to foreach loop but this if (isset($_GET[$field]) && !empty($_GET['$field'])) condition not successful and went to else loop
$fields = array(
'name' => TRUE,
'gender' => TRUE,
'colf' => TRUE,
'deptf' => TRUE,
'natf' => TRUE,
'fstatusf' => TRUE,
'fyearf' => TRUE
);
foreach ($fields as $field => $like) {
if (isset($_GET[$field]) && !empty($_GET['$field'])) {
$value = $_GET[$field];
$search[] = $field . ( $like ? ('LIKE "%' . $value . '%"') : ('="' . $value . '"') );
}
}
if ($search) {
$sql = 'SELECT * FROM fmaf WHERE ' . implode(' or ' . $search);
}
else{
$sql="SELECT * FROM fmaf";
}

At last i have found the solution and thanks to cFreed and other who help me. My main concern is that if user want to search with one field only or more than 1 field in that case below answer is helpful for me and may be also for someone:
if (empty($_GET['name']) && empty($_GET['gender']) && empty($_GET['colf']) && empty($_GET['deptf']) && empty($_GET['natf']) && empty($_GET['fstatusf']) && empty($_GET['fyearf']))
{
$sql="select * from fmaf ";
}
else
{
$wheres = array();
$sql = "select * from fmaf where ";
if (isset($_GET['name']) and !empty($_GET['name']))
{
$wheres[] = "name like '%{$_GET['name']}%' ";
}
if (isset($_GET['gender']) and !empty($_GET['gender']))
{
$wheres[] = "gender = '{$_GET['gender']}'";
}
if (isset($_GET['colf']) and !empty($_GET['colf']))
{
$wheres[] = "college = '{$_GET['colf']}' ";
}
if (isset($_GET['deptf']) and !empty($_GET['deptf']))
{
$wheres[] = "department = '{$_GET['deptf']}' ";
}
if (isset($_GET['natf']) and !empty($_GET['natf']))
{
$wheres[] = "nationality = '{$_GET['natf']}' ";
}
if (isset($_GET['fstatusf']) and !empty($_GET['fstatusf']))
{
$wheres[] = "finalstatus = '{$_GET['fstatusf']}' ";
}
if (isset($_GET['fyearf']) and !empty($_GET['fyearf']))
{
$wheres[] = "fyear = '{$_GET['fyearf']}' ";
}
foreach ( $wheres as $where )
{
$sql .= $where . ' AND '; // you may want to make this an OR
}
$sql=rtrim($sql, "AND ");
}

You need to build the query depending on the request.
A toy example is this:
$sql = "select * from student where 1 = 1".(isset($name)?" AND name like '%$name%":"").(isset($country)?" AND country = '$country'":"").";";

You may use a simple way, being able to face any case, like this:
// define searchable fields, with option for LIKE|EQUAL (TRUE|FALSE)
$fields = [
'name' => TRUE,
'country' => TRUE,
'address' => TRUE,
'gender' => FALSE,
'state' => FALSE
];
foreach ($fields as $field => $like) {
if (isset($_GET[$field]) AND !empty($_GET['$field'])) {
$value = $_GET[$field];
// prepare WHERE condition item, depending on LIKE option
$search[] = $field . (
$like ? ('LIKE "%' . $value . '%"') : ('="' . $value . '"')
);
}
}
if ($search) {
$sql = 'SELECT * FROM student WHERE ' . implode(' AND ' . $search);
}

Related

Writing two conditions in WHERE clause gives incorrect output in PDO query

I have a function in one of my PDO class and when I write two conditions in WHERE clause it execute the incorrect query.
I have tried writing WHERE in array but it gives me an unknown column error so I have written the conditions in string format. The query works perfectly if I write a single condition but generate issue if I write multiple conditions.
I have the following code in my function:
public function getNewsByDate($date, $lastdate){
$args = array(
'fields' => array(
'news.id',
'news.title',
'news.summary',
'news.story',
'news.image',
'news.added_by',
'news.status',
'news.added_date',
'news.news_category',
'(SELECT users.full_name FROM users WHERE id = news.added_by) as author',
),
'where' => (' date BETWEEN "'.$date.'" AND "'.$lastdate.'"') AND (' archieveCategory = "magazine" '),
);
return $this->select($args, true);
}
And when I debug my above code I get the sql which looks like this:
SELECT news.id, news.title, news.summary, news.story, news.image,
news.added_by, news.status, news.added_date, news.news_category,
(SELECT users.full_name FROM users WHERE id = news.added_by) as author
FROM news
WHERE 1
ORDER BY news.id DESC
And, I have the following code in my select query:
final protected function select($args = array(), $is_die = false){
try {
$this->sql = "SELECT ";
if (isset($args['fields'])) {
if (is_array($args['fields'])) {
$this->sql .= implode(', ', $args['fields']);
} else {
$this->sql .= $args['fields'];
}
} else {
$this->sql .= " * ";
}
$this->sql .= " FROM ";
if (!isset($this->table) || empty($this->table)) {
throw new Exception("Table not set");
}
$this->sql .= $this->table;
/*Join Query*/
if (isset($args['join']) && !empty($args['join'])) {
$this->sql .= " ".$args['join'];
}
/*Join Query*/
if (isset($args['where']) && !empty($args['where'])) {
if (is_array($args['where'])) {
$temp = array();
foreach ($args['where'] as $column_name => $data) {
if (!is_array($data)) {
$data = array(
'value' => $data,
'operator' => '=',
);
}
$str = $column_name.' '.$data['operator'].' :'.str_replace('.', '_', $column_name);
$temp[] = $str;
}
$this->sql .= " WHERE ".implode(' AND ', $temp);
} else {
$this->sql .= " WHERE ".$args['where'];
}
}
/*Group*/
if (isset($args['group_by']) && !empty($args['group_by'])) {
$this->sql .= " GROUP BY ".$args['group_by'];
}
/*Group*/
/*Order*/
if (isset($args['order_by']) && !empty($args['order_by'])) {
$this->sql .= " ORDER BY ".$args['order_by'];
} else {
$this->sql .= " ORDER BY ".$this->table.".id DESC";
}
/*Order*/
/*Limit*/
if (isset($args['limit']) && !empty($args['limit'])) {
if (is_array($args['limit'])) {
$this->sql .= " LIMIT ".$args['limit'][0].",".$args['limit'][1];
} else {
$this->sql .= " LIMIT ".$args['limit'];
}
}
/*Limit*/
$this->stmt = $this->conn->prepare($this->sql);
if (is_array($args['where']) || is_object($args['where'])){
foreach ($args['where'] as $column_name => $data) {
$value = is_array($data) ? $data['value'] : $data; //check if passed where statement was an array, fetch value if so
if (is_int($value)) {
$param = PDO::PARAM_INT;
}elseif (is_bool($value)) {
$param = PDO::PARAM_BOOL;
}elseif (is_null($value)) {
$param = PDO::PARAM_NULL;
}else {
$param = PDO::PARAM_STR;
}
if ($param) {
$this->stmt->bindValue(":".str_replace('.', '_', $column_name), $value, $param);
}
}
}
if ($is_die) {
echo $this->sql;
}
$this->stmt->execute();
$data = $this->stmt->fetchAll(PDO::FETCH_OBJ);
return $data;
} catch (PDOException $e) {
error_log(
date('Y-m-d h:i:s A').", Select Query: ".$e->getMessage()."\r\n"
, 3, ERROR_PATH.'/error.log');
return false;
} catch (Exception $e) {
error_log(
date('Y-m-d h:i:s A').", General: ".$e->getMessage()."\r\n"
, 3, ERROR_PATH.'/error.log');
return false;
}
}
My expected result would be like this:
SELECT news.id, news.title, news.summary, news.story, news.image,
news.added_by, news.status, news.added_date, news.news_category,
(SELECT users.full_name FROM users WHERE id = news.added_by) as author
FROM news WHERE date BETWEEN "2019-03-01" AND "2019-03-31" AND archeiveCategory = "magazine"
ORDER BY news.id DESC
In the where element of the array, the quotes should be...
'where' => '( date BETWEEN "'.$date.'" AND "'.$lastdate.'") AND ( archieveCategory = "magazine" )',
in your version
'where' => (' date BETWEEN "'.$date.'" AND "'.$lastdate.'"') AND (' archieveCategory = "magazine" '),
you can see that the quotes start after the opening ( and before the close ), this meant (I think) you ended up with a logical equivalent of
'where' => ('some string') AND ('another string'),
which is where the 1 comes from in the output.

update existing array record if already exists in database else insert into database using array

I am getting error while updating my sales order using for each.
foreach( $_POST['productId'] as $key => $val){
$invoice_arrs = array(
"product_name" => $_POST['productname'][$key],
"purchaseQty" => $_POST['purchaseQty'][$key],
"sellingPrice" => $_POST['sellingPrice'][$key],
"discount" => $_POST['discount'][$key],
"dis_type" => $_POST['discounttype'][$key],
"total" => $_POST['total'][$key],
"net_price" => $_POST['net_price'][$key]
);
$temp=UpdateRecords("sales_order","sales_order_id=$id",$invoice_arrs,1);
//here is my update record function
function UpdateRecords($table, $condition, $updata, $debug = "") {
global $conn;
foreach ( $updata as $key => $value ) {
if ($value != "now()") {
$fv [] = "$key = \"" . "$value" . "\"";
} else {
$fv [] = "$key = " . "$value" . "";
}
}
$fv_list = trim ( implode ( ", ", $fv ) );
$query = "UPDATE $table SET " . "$fv_list" . " WHERE $condition";
if ($debug == 1) {
echo $query;
}
$result = executeQuery( $query );
if (! mysqli_affected_rows ( $conn )) {
global $errormessage;
$errormessage = mysqli_error ( $conn );
if (! empty ( $errormessage ))
return 0;
}
return 1;
}
You can try below query -
INSERT INTO $table (product_name,
purchaseQty,
sellingPrice,
discount,
dis_type,
total,
net_price)
VALUES($_POST['productname'][$key],
$_POST['purchaseQty'][$key],
$_POST['sellingPrice'][$key],
$_POST['discount'][$key],
$_POST['discounttype'][$key],
$_POST['total'][$key],
$_POST['net_price'][$key])
ON DUPLICATE KEY UPDATE product_name = VALUES($_POST['productname'][$key]),
purchaseQty = VALUES($_POST['purchaseQty'][$key]),
sellingPrice = VALUES($_POST['sellingPrice'][$key]),
discount = VALUES($_POST['discount'][$key]),
dis_type = VALUES($_POST['discounttype'][$key]),
total = VALUES($_POST['total'][$key]),
net_price = VALUES($_POST['net_price'][$key]);

Datatables serverside processing using mysqli json

I am using datatables without a problem, but some pages crash due to the large amount of data that it's fetching from the database. So I tried to implement server side processing. I followed the examples on the site, but I just don't seem to receive the json data sent from the php file. Can someone please tell me what's wrong?
What I get on console is: jquery.min.js:5 POST http://example.com//datatables-script.php net::ERR_EMPTY_RESPONSE.
Response at Network tab says: Failed to load response data
This is my ajax call:
$(document).ready(function(){
$('#sort').dataTable({
"ajax": {
url: "datatables-script.php",
type: "POST",
data: {storeid:'<?php echo $stid; ?>'},
//dataType: 'json',
success: function(gotback) {
//var JSONArray = JSON.stringify(data);
//console.log(JSONArray);
console.log(gotback);
}
},
"processing": true,
"serverSide": true,
"bServerSide": true,
});
This is my script: Sorry for the long post.
<?php
mb_internal_encoding('UTF-8');
$aColumns = array( 'Rec_Id', 'Br_Id', 'C_Id', 'SubcId', 'ProdId', 'Prodme', 'URL', 'Im0', 'Price' );
$sIndexColumn = 'Rec_Id';
$sTable = 'tb';
$gaSql['user'] = 'ss';
$gaSql['password'] = 'sss';
$gaSql['db'] = 's';
$gaSql['server'] = 's';
$gaSql['port'] = 3306; // 3306 is the default MySQL port
// Input method (use $_GET, $_POST or $_REQUEST)
$input =& $_POST;
$gaSql['charset'] = 'utf8';
//get store id
$storeid = $_POST['storeid'];
$db = new mysqli($gaSql['server'], $gaSql['user'], $gaSql['password'], $gaSql['db'], $gaSql['port']);
if (mysqli_connect_error()) {
die( 'Error connecting to MySQL server (' . mysqli_connect_errno() .') '. mysqli_connect_error() );
}
if (!$db->set_charset($gaSql['charset'])) {
die( 'Error loading character set "'.$gaSql['charset'].'": '.$db->error );
}
$sLimit = "";
if ( isset( $input['iDisplayStart'] ) && $input['iDisplayLength'] != '-1' ) {
$sLimit = " LIMIT ".intval( $input['iDisplayStart'] ).", ".intval( $input['iDisplayLength'] );
}
$aOrderingRules = array();
if ( isset( $input['iSortCol_0'] ) ) {
$iSortingCols = intval( $input['iSortingCols'] );
for ( $i=0 ; $i<$iSortingCols ; $i++ ) {
if ( $input[ 'bSortable_'.intval($input['iSortCol_'.$i]) ] == 'true' ) {
$aOrderingRules[] =
"".$aColumns[ intval( $input['iSortCol_'.$i] ) ]." "
.($input['sSortDir_'.$i]==='asc' ? 'asc' : 'desc');
}
}
}
if (!empty($aOrderingRules)) {
$sOrder = " ORDER BY ".implode(", ", $aOrderingRules);
} else {
$sOrder = "";
}
$iColumnCount = count($aColumns);
if ( isset($input['sSearch']) && $input['sSearch'] != "" ) {
$aFilteringRules = array();
for ( $i=0 ; $i<$iColumnCount ; $i++ ) {
if ( isset($input['bSearchable_'.$i]) && $input['bSearchable_'.$i] == 'true' ) {
$aFilteringRules[] = "".$aColumns[$i]." LIKE '%".$db->real_escape_string( $input['sSearch'] )."%'";
}
}
if (!empty($aFilteringRules)) {
$aFilteringRules = array('('.implode(" OR ", $aFilteringRules).')');
}
}
// Individual column filtering
for ( $i=0 ; $i<$iColumnCount ; $i++ ) {
if ( isset($input['bSearchable_'.$i]) && $input['bSearchable_'.$i] == 'true' && $input['sSearch_'.$i] != '' ) {
$aFilteringRules[] = "".$aColumns[$i]." LIKE '%".$db->real_escape_string($input['sSearch_'.$i])."%'";
}
}
if (!empty($aFilteringRules)) {
$sWhere = " WHERE sid=$storeid ".implode(" AND ", $aFilteringRules);
} else {
$sWhere = "";
$aQueryColumns = array();
foreach ($aColumns as $col) {
if ($col != ' ') {
$aQueryColumns[] = $col;
}
}
$sQuery = "
SELECT SQL_CALC_FOUND_ROWS ".implode(", ", $aQueryColumns)."
FROM ".$sTable."".$sWhere.$sOrder.$sLimit;
//echo $sQuery;
$rResult = $db->query( $sQuery ) or die($db->error);
// Data set length after filtering
$sQuery = "SELECT FOUND_ROWS()";
$rResultFilterTotal = $db->query( $sQuery ) or die($db->error);
list($iFilteredTotal) = $rResultFilterTotal->fetch_row();
// Total data set length
$sQuery = "SELECT COUNT(".$sIndexColumn.") FROM ".$sTable."";
$rResultTotal = $db->query( $sQuery ) or die($db->error);
list($iTotal) = $rResultTotal->fetch_row();
$output = array(
"sEcho" => intval($input['sEcho']),
"iTotalRecords" => $iTotal,
"iTotalDisplayRecords" => $iFilteredTotal,
"aaData" => array(),
);
while ( $aRow = $rResult->fetch_assoc() ) {
$row = array();
for ( $i=0 ; $i<$iColumnCount ; $i++ ) {
if ( $aColumns[$i] == 'version' ) {
// Special output formatting for 'version' column
$row[] = ($aRow[ $aColumns[$i] ]=='0') ? '-' : $aRow[ $aColumns[$i] ];
} elseif ( $aColumns[$i] != ' ' ) {
// General output
$row[] = $aRow[ $aColumns[$i] ];
}
}
$output['aaData'][] = $row;
}
echo json_encode( $output );
Check this example, I am using the same in my project:
JS:
$('#datatable_location_details').dataTable({
"sServerMethod": "GET",
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "getdetails.php,
// "aoColumns": [null, null, null, null, { "bSortable": true, "sClass": "align_center" }, { "bSortable": true, "sClass": "align_center" }, { "bSortable": false, "sClass": "align_center" }]
});
Php:
$start = $_REQUEST['iDisplayStart'];
$length = $_REQUEST['iDisplayLength'];
$col = $_REQUEST['iSortCol_0'];
$arr = array(0 => 'state', 1 => 'city', 2 => 'institute_name', 3 => 'address', 4 => 'student_count', 5 => 'ranking');
$sort_by = $arr[$col];
$sort_type = $_REQUEST['sSortDir_0'];
$qry = "select id, institute_name, address, state, city, student_count, ranking, latitude, longitude from location_details where (state LIKE '%".$state."%' and city LIKE '%".$city."%' and institute_name LIKE '%".$name."%' and address LIKE '%".$address."%') and (address != '' and state != '' and city != '') ORDER BY ".$sort_by." ".$sort_type." LIMIT ".$start.", ".$length;
$res = mysqli_query($con, $qry);
while($row = mysqli_fetch_assoc($res))
{
$data[] = $row;
}
$qry = "select count(id) as count from location_details";
$res = mysqli_query($con, $qry);
while($row = mysqli_fetch_assoc($res))
{
$iTotal = $row['count'];
}
$rec = array(
'iTotalRecords' => $iTotal,
'iTotalDisplayRecords' => $iTotal,
'aaData' => array()
);
$k=0;
if (isset($data) && is_array($data))
{
foreach ($data as $item)
{
$action = 'Show Map';
$tooltip= 'Show Map';
$class = 'show_details';
if($item['latitude'] == '' && $item['longitude'] == '')
{
$action = 'Modify Address';
$tooltip= 'Latitude & Longitude are not available for this address';
$class = 'modify_address';
}
$rec['aaData'][$k] = array(
0 => $item['state'],
1 => $item['city'],
2 => htmlspecialchars($item['institute_name'], ENT_QUOTES),
3 => htmlspecialchars($item['address'], ENT_QUOTES),
4 => $item['student_count'],
5 => $item['ranking'],
6 => ''.$action.'',
);
$k++;
}
}
echo json_encode($rec);
For more info check this Github Project

How can I email myself the RAW SQL query that this php function is producing?

I want to run explain on a query that is slow but I don't know how to view the raw sql so I can run it in phpmyadmin and debug it. Here is the function.
private function getAttImages($limit, $forumIds = 0, $fidsReverse = false, $topicIds = 0, $membersIds = 0, $order = 'attach_date', $sort = 'desc', $group = null)
{
$fids = '';
if ($forumIds)
{
$r = '';
if ($fidsReverse)
{
$r = ' NOT ';
}
if (is_array($forumIds))
{
$forumIds = implode(',', $forumIds);
}
$fids = ' AND forums_topics.forum_id ' . $r . ' IN (' . $forumIds . ')';
}
$tids = '';
if ($topicIds)
{
$tids = ' AND forums_topics.tid IN (' . $topicIds . ')';
}
$mids = '';
if ($membersIds)
{
$mids = ' AND core_attachments.attach_member_id IN (' . $membersIds . ')';
}
$whereT = array();
$joinsT = array();
$findInPosts = ' AND ' . \IPS\Db::i()->findInSet('queued', array('0'));
$joinsT[] = array(
'select' => 'forums_posts.*',
'from' => 'forums_posts',
'where' => array("forums_posts.pid=core_attachments_map.id2" . $findInPosts),
);
$findInTopics = ' AND ' . \IPS\Db::i()->findInSet('approved', array('1'));
$joinsT[] = array(
'select' => 'forums_topics.*',
'from' => 'forums_topics',
'where' => array("forums_topics.tid=forums_posts.topic_id" . $findInTopics . $fids . $tids),
);
$select = 'core_attachments.attach_id AS custom_data, core_attachments.*';
if ($group)
{
$select = 'core_attachments.attach_id AS custom_data, COUNT(attach_is_image) as cnt_images, SUM(attach_hits) as summ_attach_hits, core_attachments.*';
}
$joinsT[] = array(
'select' => $select,
'from' => 'core_attachments',
'where' => array('core_attachments.attach_is_image=1 AND core_attachments.attach_is_archived=0 AND core_attachments.attach_id=core_attachments_map.attachment_id' . $mids),
);
$joinsT[] = array( 'select' => 'core_members.member_id, core_members.member_group_id, core_members.mgroup_others, core_members.name, core_members.members_seo_name',
'from' => 'core_members',
'where' => array('core_attachments.attach_member_id=core_members.member_id' . $mids),
);
$joinsT[] = array( 'select' => 'core_permission_index.perm_id',
'from' => 'core_permission_index',
'where' => array("core_permission_index.app='forums' AND core_permission_index.perm_type='forum' AND core_permission_index.perm_type_id=forums_topics.forum_id"),
);
$groupT = $group;
$whereT[] = array(
"core_attachments_map.location_key='forums_Forums' AND " .
\IPS\Db::i()->findInSet('perm_view', array_merge(array(\IPS\Member::loggedIn()->member_group_id), array_filter(explode(',', \IPS\Member::loggedIn()->mgroup_others)))) . " OR perm_view='*'" .
$fids . $tids . $mids
);
$table = new \IPS\Helpers\Table\Db(
'core_attachments_map',
\IPS\Http\Url::internal('app=core&module=system&controller=nbattachpictures', 'front', 'nbattachpictures'),
$whereT,
$groupT
);
$table->joins = $joinsT;
$table->sortBy = $order;
$table->sortDirection = $sort;
$table->limit = $limit;
$table->rowsTemplate = array(\IPS\Theme::i()->getTemplate('plugins', 'core', 'global'), 'nbAttachmentsBlocksRows');
$table->parsers = array(
'custom_data' => function( $val, $row )
{
return array(
'topic_data' => \IPS\Http\Url::internal("app=forums&module=forums&controller=topic&id={$row['tid']}", 'front', 'forums_topic', array($row['title_seo'])),
'summ_attach_hits' => $row['summ_attach_hits'],
'jewel' => $this->attachJewel($row['summ_attach_hits']),
);
},
);
return $table;
}
Anybody know how I can see the SQL query only that is produced by this function? email is better than echo as I want to grab query from live site.
You could var_dump($table) and write the result in an email using the native php mail function or write it in a log file (this option is better).
Is that framework open-source? Because I couldn't find any documentation about the class \IPS\Helpers\Table\Db. Probably there's a method in it to build the query, you could look for it at that class source code and put the result of that method into the email message or log file instead of var_dump the table.

How could I fix this Auto Increment?

So, here is my problem on login through steam id it creates an account on my website but it also decides on next login to skip an Auto Increment causing the next registered member to gain a ton of Auto Incremented member id's
<?php
require ("common.php");
class SteamSignIn
{
const STEAM_LOGIN = 'https://steamcommunity.com/openid/login';
public static function genUrl($returnTo = false, $useAmp = true)
{
$returnTo = (!$returnTo) ? (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] : $returnTo;
$params = array(
'openid.ns' => 'http://specs.openid.net/auth/2.0',
'openid.mode' => 'checkid_setup',
'openid.return_to' => $returnTo,
'openid.realm' => (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'],
'openid.identity' => 'http://specs.openid.net/auth/2.0/identifier_select',
'openid.claimed_id' => 'http://specs.openid.net/auth/2.0/identifier_select',
);
$sep = ($useAmp) ? '&' : '&';
return self::STEAM_LOGIN . '?' . http_build_query($params, '', $sep);
}
public static function validate()
{
$params = array(
'openid.assoc_handle' => $_GET['openid_assoc_handle'],
'openid.signed' => $_GET['openid_signed'],
'openid.sig' => $_GET['openid_sig'],
'openid.ns' => 'http://specs.openid.net/auth/2.0',
);
$signed = explode(',', $_GET['openid_signed']);
foreach($signed as $item)
{
$val = $_GET['openid_' . str_replace('.', '_', $item)];
$params['openid.' . $item] = get_magic_quotes_gpc() ? stripslashes($val) : $val;
}
$params['openid.mode'] = 'check_authentication';
$data = http_build_query($params);
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' =>
"Accept-language: en\r\n".
"Content-type: application/x-www-form-urlencoded\r\n" .
"Content-Length: " . strlen($data) . "\r\n",
'content' => $data,
),
));
$result = file_get_contents(self::STEAM_LOGIN, false, $context);
preg_match("#^http://steamcommunity.com/openid/id/([0-9]{17,25})#", $_GET['openid_claimed_id'], $matches);
$steamID64 = is_numeric($matches[1]) ? $matches[1] : 0;
return preg_match("#is_valid\s*:\s*true#i", $result) == 1 ? $steamID64 : '';
}
}
$steam_login_verify = SteamSignIn::validate();
if(!empty($steam_login_verify))
{
// Grab Data From Steam API
$json = file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' . $sapik . '&steamids='. $steam_login_verify .'&format=json');
//Decode Data From Steam API
$data = json_decode($json);
foreach($data->response->players as $player)
{
$query = "INSERT INTO steam (steamid, personaname, profileurl, avatar, avatarmedium, avatarfull ) VALUES ( :steamid, :personaname, :profileurl, :avatar, :avatarmedium, :avatarfull) ";
$query_params = array(
':steamid' => $player->steamid,
':personaname' => $player->personaname,
':profileurl' => $player->profileurl,
':avatar' => $player->avatar,
':avatarmedium' => $player->avatarmedium,
':avatarfull' => $player->avatarfull,
);
}
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
switch( $ex->errorInfo[1] )
{
case 1062:
$ps = $db->prepare("SELECT * FROM `steam` WHERE steamid = :sid");
$ps->bindParam(':sid', $steam_login_verify);
$ps->execute();
$ps->setFetchMode(PDO::FETCH_ASSOC);
foreach ($ps as $row)
{
$_SESSION['sid'] = $row['steamid'];
}
header('Location:'.$basedir);
die('redirecting to'.$basedir);
;
}
}
$ps = $db->prepare("SELECT * FROM `steam` WHERE steamid = :sid");
$ps->bindParam(':sid', $steam_login_verify);
$ps->execute();
$ps->setFetchMode(PDO::FETCH_ASSOC);
foreach ($ps as $row)
{
$_SESSION['sid'] = $row['steamid'];
}
header('Location:'.$basedir);
die('redirecting to'.$basedir);
} else {
$steam_sign_in_url = SteamSignIn::genUrl();
}

Categories