use SELECT and SESSION to check login user doesn't work - session

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");
}

Related

$_SESSION variables use in queries

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"

Is it wrong to parse the verification from Google?

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';

Ajax, PHP. How can i send multiple variable with _GET or anyother way to other file?

Im trying to send two variables with get to a php file that contains an xlm format
function process(){
if (xmlHttp){
try{
email = encodeURIComponent(document.getElementById("email").value);
if (email=="") {email="empty email"};
xmlHttp.open("GET", "user_check.php?email=" + email, true);
username = encodeURIComponent(document.getElementById("username").value);
if (username=="") {username="empty username"};
xmlHttp.open("GET", "user_check.php?username=" + username, true);
the php file looks like
echo '<response>';
echo '<username>';
$username = ( isset($_GET['username']) ? $_GET['username'] : "something empty");
echo $username;
echo '</username>';
echo '<email>';
$email = ( isset($_GET['email']) ? $_GET['email'] : "something empty");
echo $email;
echo '</email>';
echo '</response>';
when i echo those variables it shows only one, actually it sends only the username which is the second on list(from top to bottom) that is sent. How can i send both or later more variables
function handleResponse(){
message_email = xmlHttp.responseXML.documentElement.getElementsByTagName("email").item(0).firstChild.data;
next_email = document.getElementById("next_email");
next_email.innerHTML =message_email;
message_username = xmlHttp.responseXML.documentElement.getElementsByTagName("username").item(0).firstChild.data;
next_username = document.getElementById("next_username");
next_username.innerHTML =message_username;
}
the output of this is
email : something empty
username : "the value from input"
i want email to have its value from its input.
I hope i made my question clear.
As far as I can understand you, you have to put both of variables into one request, because now, you are sending two requests, after everything reading only second one.
To send two variables in one GET request you use something like:
http://example.com/response.php?var1=foo&var2=bar
resulting in PHP:
$_GET['var1'] = "foo";
$_GET['var2'] = "bar";
So your AJAX code should look like:
email = encodeURIComponent(document.getElementById("email").value);
if (email=="") {
email="empty email"
};
username = encodeURIComponent(document.getElementById("username").value);
if (username=="") {
username="empty username"
};
xmlHttp.open("GET", "user_check.php?email=" + email + "&username=" + username, true);
Important thing is that order of GET variables doesn't matter - you can put email or username first, they will both be loaded into $_GET[] array.

Auto refresh content in Mediawiki

I added a new tag (<news />) to my mediawiki to list the last modified pages.
Unfortunately the list is not updated unless I modify the page where the tag is.
I'm looking for a way to do it, and I think of AJAX. But I didn't manage to make AJAX refreshing my list.
Does anyone know a simple way to add an auto refresh feature on my Mediawiki ?
Here is my extension code :
$wgHooks['ParserFirstCallInit'][] = 'replaceTags';
function replaceTags( Parser $parser ) {
$parser->setHook( 'news', 'newsRender' );
return true;
}
function newsRender( $input, array $args, Parser $parser, PPFrame $frame ) {
// Titre =News=
$output = $parser->parse( "=News=", $parser->mTitle, $parser->mOptions, false, false )->getText();
$nb = 5;
$querySQL = "SELECT page_namespace, page_title, page_id, page_latest, rev_timestamp
FROM page, revision
WHERE page.page_latest = revision.rev_id
AND page_namespace = 0
ORDER BY rev_timestamp
DESC LIMIT 0,$nb";
$dbr = wfGetDB( DB_SLAVE );
$res = $dbr->query( $querySQL );
$count = $dbr->numRows( $res );
if( $count > 0 ) {
$output .= "<ul>";
while( $row = $dbr->fetchObject( $res ) )
{
$pageTitle = $row->page_title;
$nicerPageTitle = str_replace("_", " ", $pageTitle);
$pageNamespace = $row->page_namespace;
$title = Title::makeTitleSafe( $pageNamespace, $pageTitle );
$url = $title->getFullURL();
$date = $row->rev_timestamp;
$date = wfTimestamp( TS_RFC2822, $date );
$output .= "<li>$nicerPageTitle $date</li>";
}
$output .= "</ul>";
} else {
$output .= "A l'ouest rien de nouveau !!!";
}
return $output;
}
Thanks to nischayn22, I go into the cache problem in depth.
And I found that it's possible to deactivate it :
$parser->disableCache();
I tried it, and it works !!!
http://www.mediawiki.org/wiki/Extensions_FAQ#How_do_I_disable_caching_for_pages_using_my_extension.3F
This probably happens because MediaWiki uses Cache for pages. What you could rather do is make a SpecialPage for the feature needed. AFAIK Special Pages are not cached (confirm this on irc #mediawiki).
Also you might already find a similar implementation done by someone if you search the extensions that exist on Mediawiki.org .(Otherwise I would be happy to build one for you :)
Update: Extensions you could use Dynamic List(used in wikinews) and news . There could be more if you search mediawiki.org.

codeigniter admin login hacked although I have used all security matters

how come have the code before hacked with SQL Injection :(
$query = $this->db->query("SELECT * FROM users WHERE username = ? AND password = ?", array(mysql_real_escape_string($this->input->post('username')), mysql_real_escape_string(MD5($this->input->post('password')))));
appreciate helps!!
You don't need to use mysql_real_escape_string() as CodeIgniter Database driver does that for you. Double escaping your string could well cause some problems.
Use like this for more safer queries:
$query_username = $this->db->query("SELECT COUNT(username) AS count_username FROM users WHERE username=?", $this->input->post('username'));
$row_username = $query_username->row_array();
if ($row_username['count_username'] > 0) {
$query_password = $this->db->query("SELECT password FROM users WHERE username=?", $this->input->post('username'));
$row_password = $query_password->row_array();
if ($row_password['password'] == MD5($this->input->post('password')) {
// LOGIN SUCCESS
} else {
// LOGIN FAILED
}
} else {
// LOGIN FAILED
}

Resources