I have spent nearly two days going in circles on this one.
I seem to have difficulty using $_SESSION or $_POST as strings in any query or converting them to strings to use.
I am using a simple hash approach to login to a site.
Extract from script is
<?php
session_start();
echo "******Running Authenticate<br>";
echo "data submitted<br>".$_POST['site_login']."<br>".$_POST['site_password']."<br><br>";
$SiteLogin = $_POST['site_login']
$_SESSION['site_login'] = $_POST['site_login'];
$_SESSION['site_password'] = $_POST['site_password'];
$_SESSION['session_id'] = session_id();
$_SESSION['Now_val'] = date('Y-m-d H:i:s');
//include 'showallvars.php';
include 'dbconfig.php';
// Prepare our SQL
if ($stmt = $con->prepare('SELECT site_index, site_password FROM web_sites WHERE site_login = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
$stmt->bind_param('s', $_POST['site_login']);
$stmt->execute();
$stmt->store_result();
// Store the result so we can check if the account exists in the database.
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $password);
$stmt->fetch();
echo "account exists";
}
else
{
header('Location: badindex.php');
}
if (password_verify($_POST['site_password'], $password)) {
// Verification success! User has loggedin!
echo "password good";
}
else
{
header('Location: badindex.php');
}
}
$_SESSION['loggedin'] = TRUE;
?>
that works fine
BUT there is another field ( 'site_name') in the record which i want to carry forward.
This should be easy !!
and there is a dozen ways of doing it
for example the "standard" example is something like
$name = $mysqli->query("SELECT site_name FROM web_sites WHERE site_login = 'fred'")->fetch_object()->site_name;
That works fine
but no matter how i try - concatenating or or ... I cannot get $_SESSION['site_login'] or $_POST['site_login'] to replace 'fred'.
There seems to be white space added in.
Assistance or guidance ?
It should be possible to as easy as doing the following:
So:
if ($stmt = $con->prepare('SELECT site_index, site_password
FROM web_sites WHERE site_login = ?')) {
becomes:
if ($stmt = $con->prepare('SELECT site_index, site_password, site_login
FROM web_sites WHERE site_login = ' . $SiteLogin)) {
Do note, it is bad practice to do directly parse $SiteLogin to a query, because now someone can SQL Inject this and hack your website. All they need to do is use your form and figure out that which field is responsible for $SiteLogin. You would need to escape your $SiteLogin. Assuming Mysqli, it would become:
if ($stmt = $con->prepare('SELECT site_index, site_password, site_login
FROM web_sites WHERE site_login = ' . $con->real_escape_string($SiteLogin))) {
Thank you for that BUT the instant I saw the curly brackets in your answer - it all came flooding back to me. I had forgotten that PHP has problems with the square brackets
$sql = ("SELECT site_name FROM web_sites WHERE site_login = '". $_SESSION{'site_login'} ."' LIMIT 1");
I KNEW it was easy !
Your comments on injection are of course correct but this was an edited code excerpt and $SiteLogin was just added in as a "temporary working variable if needed"
Related
I have javascript function that populates datatable using Ajax. My javascript code looks like :
$('#results').dataTable({
// Ajax load data
"ajax": {
"url": "get_intl_tickets",
"type": "POST",
"data": {
"user_id": 451,
"csrfmiddlewaretoken" : csrftoken,
}
}
})
My server side script in django has a function that loads around 500 data rows. Now the problem is that I don't want to load whole data at a time. Instead I want to have first 10 data rows. Then with pagination, another 10 rows like that.
I read the page server side processing documentation of datatables. I tried with "serverSide": true option as well. I am not understanding server side script. There is given an example of PHP. It seems that they are not using any parameters like draw, recordsFiltered, recordsTotal there. There they have used php SSP class. And it is unknown what does it do. I am trying to implement it in django.
But I am not finding proper good documentation to implement. Any help will be appreciated.
Old question but one I also had a surprisingly difficult time finding an answer to, so in case anyone else ends up here... :P
I found this 2020 article very helpful, specifically part 6 showing the "complete code" that includes getting the correct variables, building the SQL query, and how to build/structure the data object that it responds with:
https://makitweb.com/datatables-ajax-pagination-with-search-and-sort-php/
Their example posted below:
<?php
## Database configuration
include 'config.php';
## Read value
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = mysqli_real_escape_string($con,$_POST['search']['value']); // Search value
## Search
$searchQuery = " ";
if($searchValue != ''){
$searchQuery = " and (emp_name like '%".$searchValue."%' or
email like '%".$searchValue."%' or
city like'%".$searchValue."%' ) ";
}
## Total number of records without filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee");
$records = mysqli_fetch_assoc($sel);
$totalRecords = $records['allcount'];
## Total number of record with filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee WHERE 1 ".$searchQuery);
$records = mysqli_fetch_assoc($sel);
$totalRecordwithFilter = $records['allcount'];
## Fetch records
$empQuery = "select * from employee WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
$empRecords = mysqli_query($con, $empQuery);
$data = array();
while ($row = mysqli_fetch_assoc($empRecords)) {
$data[] = array(
"emp_name"=>$row['emp_name'],
"email"=>$row['email'],
"gender"=>$row['gender'],
"salary"=>$row['salary'],
"city"=>$row['city']
);
}
## Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data
);
echo json_encode($response);
Nice exemple:
https://datatables.net/examples/server_side/defer_loading.html
But you need edit server side.
Response demo
{
draw:2,
recordsFiltered:57,
recordsTotal:57
}
I used the script from here to do the verification.
The $result === FALSE condition was being bypassed regardless of me clicking on the re-captcha validation on my form.
So I decided to manually parse it like so:
The return looks like this if a failure:
{
"success":false,
"error-codes":[
"missing-input-response"
]
}
And if it's success it looks similar but some additional things are attached, but the main thing I targeted was the string "success":true,
With this part of the script directly below the $result variable:
$result_copy = $result;
// remove white spaces everywhere
$mod_res_copy = preg_replace('/\s+/', '', $result_copy);
$success_string = '"success":true';
if(strpos($mod_res_copy, $success_string) !== false) {
$status = "ok";
}else {
$status = "not-ok";
}
if ($status == "not-ok") {
echo "Please complete the captcha to prevent spam.";
exit;
}else {
// trigger database insert of comment or whatever
}
What I want to know is, is this wrong? Can this be spoofed? I'm using PHP as my server-side scripting language.
You are doing way more work than you need, to parse $result.
It is in JSON format, so this is all you need:
$status = json_decode($result)->success ? 'ok' : 'not-ok';
Could you tell me why this is not working? I just want to check whether the userid is really exists. if it does exist, means the registered users are able to do anything on the website. However, my coding doesnt work for that. One for registered users and another one for admin. My coding is something like this. Any idea?
session_start();
$sql = "SELECT *
FROM tablename
WHERE userid = '".$_SESSION["userid"]."' ";
$check = mysqli_query($link,$sql);
if (mysqli_num_rows($check) == 1 && $_SESSION['username'] == 'admin') {
echo "<p> HELLO </p> ";
}
Any ideas?
I faked it and it worked for me. Make sure there is a value in session and if your database connection is ok. The mysqli_error will show possible failures (always thrown errors in your code).
$sql = "SELECT *
FROM tablename
WHERE userid = '".$_SESSION["userid"]."' ";
$check = mysqli_query($link,$sql) or die(mysqli_error($link));
if (mysqli_num_rows($check) == 1 && $_SESSION['username'] == 'admin') {
echo "<p> HELLO </p> ";
}
session_start();
$sel="select * from register where userid='$userid' and password='$pass'";
$res= mysql_query($sel);
$co= mysql_num_rows($res);
echo $co;
if($co>0) {
$row=mysql_fetch_array($res);
$_SESSION['id']=$row['userid'];
header("echo 'helloooooooo'");
} else {
echo "Invalid userid....";
}
header("location:login.php");
}
To be more clear, none of these lines in default language's general_lang.php work:
$lang['general_welcome_message'] = 'Welcome, %s ( %s )';
or
$lang['general_welcome_message'] = 'Welcome, %1 ( %2 )';
I expect an output like Welcome, FirstName ( user_name ).
I followed the second (not accepted) answer at https://stackoverflow.com/a/10973668/315550.
The code I write in the view is:
<div id="welcome-box">
<?php echo lang('general_welcome_message',
$this->session->userdata('user_firstname'),
$this->session->userdata('username')
);
?>
</div>
I use codeigniter 2.
You will need to use php's sprintf function (http://php.net/manual/en/function.sprintf.php)
Example from http://ellislab.com/forums/viewthread/145634/#749634:
//in english
$lang['unread_messages'] = "You have %1$s unread messages, %2$s";
//in another language
$lang['unread_messages'] = "Hi %2$s, You have %1$s unread messages";
$message = sprintf($this->lang->line(‘unread_messages’), $number, $name);
I extended Code CI_Lang class like this..
class MY_Lang extends CI_Lang {
function line($line = '', $swap = null) {
$loaded_line = parent::line($line);
// If swap if not given, just return the line from the language file (default codeigniter functionality.)
if(!$swap) return $loaded_line;
// If an array is given
if (is_array($swap)) {
// Explode on '%s'
$exploded_line = explode('%s', $loaded_line);
// Loop through each exploded line
foreach ($exploded_line as $key => $value) {
// Check if the $swap is set
if(isset($swap[$key])) {
// Append the swap variables
$exploded_line[$key] .= $swap[$key];
}
}
// Return the implode of $exploded_line with appended swap variables
return implode('', $exploded_line);
}
// A string is given, just do a simple str_replace on the loaded line
else {
return str_replace('%s', $swap, $loaded_line);
}
}
}
ie. In your language file:
$lang['foo'] = 'Thanks, %s. Your %s has been changed.'
And where-ever you want to use it (controller / view etc.)
echo $this->lang->line('foo', array('Charlie', 'password'));
Will produce
Thanks, Charlie. Your password has been changed.
This handles single 'swaps' as well as multiple
Also it won't break any existing calls to $this->lang->line.
I've created a J2.5 component with some config fields using config.xml in the admin folder of the component.
How can I set parameters in the config programatically?
I've tried the code bellow, but it obviously doesn't save the result to the DB:
$params = & JComponentHelper::getParams('com_mycomponent');
$params->set('myvar', $the_value);
Could anyone please show some examples of how to achieve this?
The safest way to do this would be to include com_config/models/component.php and use it to validate and save the params. However, if you can somehow validate the data params yourself I would stick with the following (much more simple solution):
// Get the params and set the new values
$params = JComponentHelper::getParams('com_mycomponent');
$params->set('myvar', $the_value);
// Get a new database query instance
$db = JFactory::getDBO();
$query = $db->getQuery(true);
// Build the query
$query->update('#__extensions AS a');
$query->set('a.params = ' . $db->quote((string)$params));
$query->where('a.element = "com_mycomponent"');
// Execute the query
$db->setQuery($query);
$db->query();
Notice how I cast the params to a string (when building the query), it will convert the JRegistry object to a JSON formatted string.
If you get any caching problems, you might want to run the following after editing the params:
From a model:
$this->cleanCache('_system');
Or, else where:
$conf = JFactory::getConfig();
$options = array(
'defaultgroup' => '_system',
'cachebase' => $conf->get('cache_path', JPATH_SITE . '/cache')
);
$cache = JCache::getInstance('callback', $options);
$cache->clean();
The solution is here...
http://www.webtechriser.com/tutorials/82-joomla-3-0/86-how-to-save-component-parameters-to-database-programmatically
You can replace in Joomla 2.5+ the
// check for error
if (!$table->check()) {
$this->setError('lastcreatedate: check: ' . $table->getError());
return false;
}
if (!$table->store()) {
$this->setError('lastcreatedate: store: ' . $table->getError());
return false;
}
with
if (!$table->save()) {
$this->setError('Save Error: ' . $table->getError());
return false;
}