Using URL to send data to a server - html

I am looking for a way to interpret data in a URL, server side.
Client side, I can control what the URL is, and I can programmatically produce Data for the URL, but I do not have direct access to the source code.
So ultimately, I am trying to build an online High Score system, for an offline game.
I have access to Azure and my dedicated LAMP server. I would like for my server to wait for a connections that use a URL something like "http://www.myappserver19002393859.com/HighScores?UserID=2fb44e3888?Score=25250"
I want to get the UserID & Score from the URL and then redirect to another page with the High Score Table...
Any suggestions?
(Edit: I can do anything server side, it is only client side where I have limitations.)

Use PHP's $_GET collection. It contains the key/value pairs of a URI's querystring.
In the example you've given, it would look like this:
HighScoresHandler.php
<?php
$userId = $_GET['UserID'];
$score = $_GET['Score'];
// Validation
if( empty( $userId ) || empty( $score ) ) {
echo "No UserID or Score provided.";
exit();
}
$score = intval( $score );
if( $score === 0 ) {
echo "Invalid score specified.";
exit();
}
// Verification
// TODO: Query your database to ensure the user specified by $userID exists.
// Make sure you do this safely as not to be subject to SQL injection.
$sql = "SELECT COUNT(*) FROM Users WHERE UserID = #userId";
// Action
$sql = "INSERT INTO HighScores ( UserID, Score ) VALUES ( #userId, #score )";
?>
Note that you would be advised to implement some form of MAC (Message Authentication Code) or some other system to verify that a score is real, otherwise there is nothing stopping anyone from submitting bogus scores using forged HTTP requests (this is why you sometimes see insanely high scores posted to online scoreboards).

Related

Data is not constantly loading from custom wordpress table

global $wpdb;
$tablename_temp = $wpdb->prefix . 'faculty_temp';
$toke = $_GET['token'];
$user = $wpdb->get_results("SELECT * FROM $tablename_temp where token='$toke'");
This is to fetch data from custom wordpress table, the loads fine sometimes. On some times data isn't fetched. Like I refresh 10 times, data doesn't appear in 1 out of 10 times. Seems to be server issue, while updating files in Advanced File Manager & while getting data in WP data access plugin also has same issue
First of all your code is unsafe. Need to add the sanitize functions and the escaping query to the database
global $wpdb;
$tablename_temp = $wpdb->prefix . 'faculty_temp';
$toke = isset( $_GET['token'] ) ? sanitize_text_field( wp_unslash( $_GET['token'] ) ) : '';
$user = $wpdb->get_results("SELECT * FROM $tablename_temp where token='".$wpdb->esc_like($toke)."'");
The code is valid. Perhaps the problem is that you are simultaneously writing and deleting to the temporary table "faculty_temp" and the fetch request is sent when data is deleted or modified.
Need to change your method for working with temp data

How to edit moodle sql to time access

I'm trying to change my Moodle in 2.6 version.
I want to do something like this: When user is logged in ,He have permission to watch all materials but only when his account is active.
I want to edit sql database to add 1 field 'is_active' and set there datetime stamp.
For Example I have user John Doe , i put in database in field 'is_active' date 25.02.2014 and he can watch all lessons ans stuff till 25.02.2014 after that his account goes unactivate and when he tries to log in he will have information that his account is not active and he has to contact with administrator.
Can you tell me witch Database query change to check that permission when user is trying to log in ? I think that resolution will be to get current date from server and check it with date in database. If system date is lower that database user have access , if date is higher user doesn't have access and he gets info.
If somebody doesn't understand sorry for my english write in comments i will try to describe more.
I would create a user profile field 'is_active', choose datetime and set it to 'Not visible'
site admin -> users -> accounts -> user profile fields
http://docs.moodle.org/26/en/User_profile_fields
Then create a local plugin that uses cron to check the date and sets the user to suspended
In /local/is_active/version.php - http://docs.moodle.org/dev/version.php
defined('MOODLE_INTERNAL') || die();
$plugin->version = 201402301; // Plugin version
$plugin->requires = 2013051402; // Moodle version.
$plugin->component = 'local_is_active'; // Component name
$plugin->cron = 1; // In seconds - how often should this be run?
In /local/is_active/lang/en/local_is_active.php
$string['pluginname'] = 'Is active';
In /local/is_active/lib.php have a cron function local_xxx_cron() that updates the user table to suspended. I haven't tested the SQL but something like this
defined('MOODLE_INTERNAL') || die();
function local_is_active_cron() {
$sql = "UPDATE {user}
SET suspended = :suspended
WHERE EXISTS (SELECT userid
FROM {user_info_field} f
JOIN {user_info_data} d ON d.fieldid = f.id
AND d.data < :now
AND d.userid = mdl_user
WHERE f.shortname = :shortname)";
$params = array('suspended' => 1,
'now' => time(),
'shortname' => 'is_active');
$DB->execute($sql, $params);
}
EDIT : Forgot to add that you will need to go to notifications to install the plugin - site admin -> notifications - then Moodle will automatically call the cron function when cron is run.
You can run cron manually by going to /admin/cron.php
As a site admin you can edit the date via the users profile - go to site admin -> users -> accounts -> browse list of users -> then click the pencil next to a user profile
Or update the date using something like this - the data field needs to be a unix timestamp rather than a string type date
$activedate = strtotime('2014-02-23'); // Timestamp
$fieldid = $DB->get_field('user_info_field', 'id', array('shortname' => 'is_active'));
$params = array('fieldid' => $fieldid, 'userid' => $userid);
if ($DB->record_exists('user_info_data', $params)) {
$DB->set_field('user_info_data', 'data', $activedate, $params);
} else {
$data = new stdClass();
$data->fieldid = $fieldid;
$data->userid = $userid;
$data->data = $activedate;
$data->dataformat = 0;
$DB->insert_record('user_info_data', $data);
}

Login with url paramaters

I'm creating a login system of sorts that uses parameters from the URL.
The parameters are set no problem. I dont know what the issue is.
Here's my code:
<?php
require_once("db_const.php");
$mysqli = new mysqli("dont", "try", "to login to", "my database");
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$username = filter_input(INPUT_GET,"username",FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_GET,"password",FILTER_SANITIZE_STRING);
$sql = "SELECT * from users WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
$result = $mysqli->query($sql);
if (!$result->num_rows == 1) {
echo "failed";
} else {
echo "success";
}
?>
There are a few problems with your code.
The problem is the use of the LIKE function. Your usage is
SELECT * from users WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1
Like requires additional specification to find match positions and such, for example :
SELECT ... WHERE username LIKE '%{$username}%'
In the form you used, the WHERE clause if equivalent to
SELECT ... WHERE username = '{$username}'
In addition, LIKE is not recommended even (especially) with the wildcards, as 'tom' will match users 'tom' and 'tommy', and the count will certainly not be == 1.
I'll also urge you to test the query for errors
if (!$result) {
echo 'An error occurred : $mysqli->error;
}
Others have already mentioned the risk in passwing username and passwords on the URL, Please take note of their comments.
In addition, storing the password in plain form the database is not recommended for security reasons. There are plenty of resources explaining how to encrypt passwords and authenticate using the encrypted values.
Try:
$sql = "SELECT * from users WHERE username='$username' AND password='$password'";
CAUTION
Even if the above code solves your problem, It's still very dangerous as it's vulnerable for SQL injection on both username and password parameters and it can be exploited in a manner that a malicious user can bypass the login check by breaking out of the quotes and adding a condition that evaluates to true.
You can use a mysqli::prepare to get over that.
$stmt = mysqli->prepare("SELECT * from users WHERE username=? AND password=?");
$stmt->bind_param("ss", $username,$password);
$stmt->execute();

codeigniter mysql transactions

I'm new to database transactions and what i've found is extremely confusing. I have a queue table that contains email address, send datetime, and sent datetime. My cron job is constantly firing and selecting rows with the 'send datetime' passed now. It sends an email to the address and updates the 'sent datetime' column.
If this cron job fired at the exact same time, there is potential for the them to grab the same rows, thus sending the email twice.
From what i understand, transactions all depend on the success or failure or queries. How do i check that in this scenario?
$this->db->trans_begin();
$query = $this->db->query('SELECT * FROM Queue_table where send >= now LIMIT 100');
foreach ($query->result() as $row)
{
//code to send email to $row->email;
$this->db->query('UPDATE Queue_table SET sent = now WHERE id = '$row->id'');
}
//the following doesn't make much sense to me. What would cause
// this to be false in this scenario?
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
}
else
{
$this->db->trans_commit();
}
Am i going about doing this completely wrong?

php/mysql:what's the idea to active/inactive a code from being executed

i have a php code to show online users,my question is that how to make an option(yes,no) in the admin panel to control the appearance of enabling or disabling the code
just i want to know the idea for making something like that?what are the fields required?what are the queries to do that?
or an article discuss the process of activate or in activate some code from being executed according the state of selected option(y,n)
and a practical snippet for that.......
session_start();
$session=session_id();
$time=time();
$time_check=$time-600; //SET TIME 10 Minute
$host="localhost"; // Host name
$username="advphp_advphp"; // Mysql username
$password="112233"; // Mysql password
$db_name="advphp_download"; // Database name
$tbl_name="user_online"; // Table name
// Connect to server and select databse
mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name WHERE session='$session'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count=="0"){
$sql1="INSERT INTO $tbl_name(session, time)VALUES('$session', '$time')";
$result1=mysql_query($sql1);
}
else {
"$sql2=UPDATE $tbl_name SET time='$time' WHERE session = '$session'";
$result2=mysql_query($sql2);
}
$sql3="SELECT * FROM $tbl_name";
$result3=mysql_query($sql3);
$count_user_online=mysql_num_rows($result3);
echo "المتواجدون الان : "; echo $count_user_online + 30;
// if over 10 minute, delete session
$sql4="DELETE FROM $tbl_name WHERE time<$time_check";
$result4=mysql_query($sql4);
mysql_close();
You can think of the list of online users as a module that you can configure from a back end.
Keep a XML file with the list of all the modules and their statuses (enabled/disabled) and allow the user to disable/enable the module from the back end by setting the right value for the module name in the XML file.
When you need to check the module you can either load the XML file and check the status or just keep a session variable with the statuses of the modules and decide according to that variable weather to show it or not.
For each user add an extra field called privilege which stores if user has admin, special privilege
Write a php page like admin.php
if the logged in user has admin privilege then include the admin.php page in their homepage or else do not include the admin.php
admin,php will contain the additional features for an admin user
query
select username, status from tableName
where loginName='$user' and password='$password';
then in code
if(row['status'] == 'admin')
{
include_once('admin.php');
}