I tried researching this but still have no answer for it. A program my friend designed writes to the MySQL db passwords using the MySQL password() function.
I am looking for a way to use this through the web front I designed but still have no luck. Does anyone have any suggestions?
The passwords look just like this example
mysql> SET old_passwords = 0;
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
I just need to figure out how to turn this into a function i.e
function password_hash
Here's the rest the login query for an example
if (isset($_POST["username"], $_POST["password"], $_POST[$CONF["LOGIN_SIGNAL_TRIGGER"]])) {
/*
If we got a login signal, a password and a username, we will
proceed to check login information. We will first extract
the user row from the db.
*/
$user = myF(myQ("
SELECT `username`,`password`,`id`,`disable_until`,`active`
FROM `[x]users`
WHERE LCASE(`username`)='".strtolower($_POST["username"])."'
"));
if (!$user["id"]) $GLOBALS["LOGIN_FAIL_TYPE"] = "e.user";
elseif ($user["active"] != 1 && $CONF["LOGIN_REQUIRE_ACTIVE"]) $GLOBALS["LOGIN_FAIL_TYPE"] = "e.active";
else {
/*
If the user's account 'disabled' value is greater than
the actual date value, and that the bruteforce protection
system is enabled, we will show an error message
*/
if (($user["disable_until"] > date("U")) && ($CONF["LOGIN_BRUTEFORCE_PROTECT:ENABLE"])) {
$GLOBALS["LOGIN_FAIL_TYPE"] = "e.bruteforce";
(isset($_SESSION["loginFailCount"])?session_unregister('loginFailCount'):false);
}
/*
Account is not disabled
*/
else {
if ((isset($_SESSION["loginFailCount"])) && ($_SESSION["loginFailCount"] > $CONF["LOGIN_BRUTEFORCE_FAILCOUNT"])) {
myQ("UPDATE `[x]users`
SET `disable_until` = ".(date("U")+$CONF["LOGIN_BRUTEFORCE_DISABLE_DURATION"])."
WHERE LCASE(`username`)='".strtolower($_POST["username"])."'
LIMIT 1"
);
(isset($_SESSION["loginFailCount"])?session_unregister('loginFailCount'):false);
$GLOBALS["LOGIN_FAIL_TYPE"] = "e.bruteforce";
}
else {
/*
All the information correct, we will proceed to login
*/
if ($user["password"] == md5(trim($_POST["password"]))) {
$_SESSION["id"] = (integer)$user["id"];
session_write_close();
/*
Update the last login key
*/
$me_last_login = me("last_login");
myQ("UPDATE `[x]users` SET `last_login`='".date("U")."' WHERE `id`='".me('id')."'");
/*
Route the user
*/
if (!$GLOBALS["WAP_MODE"]) {
header("Location: ".(!$me_last_login?$CONF["LOGIN_FIRST_ROUTE_TO"]:$CONF["LOGIN_ROUTE_TO"]));
} else header("Location: {$CONF["WAP_LOGIN_ROUTE_TO"]}");
}
else {
(isset($_SESSION["loginFailCount"])?$_SESSION["loginFailCount"]++:$_SESSION["loginFailCount"]=1);
$GLOBALS["LOGIN_FAIL_TYPE"] = "e.password";
}
}
}
}
}
if ((isset($_GET[$CONF["LOGOUT_SIGNAL_TRIGGER"]])) && (!isset($_POST[$CONF["LOGIN_SIGNAL_TRIGGER"]]))) {
/*
Handle admin swapping
*/
if (isset($_SESSION["swap_id"])) {
$_SESSION["id"] = $_SESSION["swap_id"];
session_unregister("swap_id");
header("Location: ?L=admin.index");
}
else {
(isset($_SESSION["id"])?session_unregister('id'):false);
(isset($_SESSION["SELF_USER_DATA"])?session_unregister('SELF_USER_DATA'):false);
header("Location: {$CONF["LOGOUT_ROUTE_TO"]}");
}
}
OP asked how to do this in php. This is how to do it in php:
function sqlPassword($input) {
$pass = strtoupper(
sha1(
sha1($input, true)
)
);
$pass = '*' . $pass;
return $pass;
}
Added for posterity (No reason you would use this, use it if mysql decides to deprecate the PASSWORD function?, for informative purposes only) the mysql equivalent of the php equivalent
SELECT
UPPER(
CONCAT('*', SHA1(UNHEX(SHA1('password'))))
)
Also see MySQL Hashing Function Implementation
If I understand you correctly there is no need to reproduce PASSWORD() in php do all your validation in one go on mysql side using PASSWORD() in your select like this
SELECT `username`,`password`,`id`,`disable_until`,`active`
FROM `[x]users`
WHERE `username` = 'user1'
AND `password` = PASSWORD('password')
Here is SQLFiddle demo
Unless you use case sensitive collation don't use LCASE() on username column in your statements. It prevents MySql from using an index (indices) if any is defined on that column and cause a full scan on the table.
On a side note: your code is vulnerable to sql-injections. Consider to use prepared statements.
Copy-paste from a password encoder interface for a Symfony2 app I wrote that migrated from an old system using the MySQL PASSWORD function:
function mysqlPassword($raw) {
return '*'.strtoupper(hash('sha1',pack('H*',hash('sha1', $raw))));
}
My version of the pre-MySQL 4.1 code.
/* PHP implementation of MySQL pre-4.1 password function.
Based on Perl Crypt::MySQL C code */
function mysql_old_password_hash($password) {
$len = strlen($password);
$add = 7;
$nr = 1345345333;
$nr2 = 0x12345671;
$tmp = 0;
foreach (str_split($password) as $chr) {
if ($chr == " " || $chr == "\t") {
continue;
}
$tmp = ord($chr);
$nr ^= ((($nr & 0x3f)+$add)*$tmp) + ($nr << 8);
$nr2 += ($nr2 << 8) ^ $nr;
$nr2 &= 0xffffffff; # We need to limit this to 32-bit
$add += $tmp;
}
// Strip sign bit
$nr &= 0x7fffffff;
$nr2 &= 0x7fffffff;
return sprintf("%08x%08x",$nr,$nr2);
}
For post-4.1, pre-5.7.something versions, look at sjagr or chiliNUT's answers.
The only reason to use this is in order to check passwords in a database that was written in spite of MySQL's advice not to use PASSWORD() for your own applications.
first use mysql_escape_string($_POST['password']) to escape the password.
then use that as a variable inside the sql query in
WHERE password_field = PASSWORD(USER_SUPPLIED_PASSWORD)
Related
I want to generate a session ID. This unique sessionId represents some different data for every different user.
My code till now:
onclick and onload of a page I call a function create_session_id();
function create_session_id() {
// This function sends a string to a PHP page using ajax post.
}
On my PHP page, I receive this data and then insert it:
session_start();
$a = session_id();
$object->insert_sessionid($a);
My Question
Is it possible to use only session_start() (no session_id()) and store some unique session ID value that I can use later when I fetch data and throw data to my web page. I don’t want any clicks to register sessionid. It should happen on page load and without any function create_session_id().
I am thinking to bring some cookies in to the picture.
Note: My website doesn’t allow login.
use a function like
function createRandomVal($val){
$chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,-";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;
while ($i<=$val)
{
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
and pass return value in session id
The above code is a little bit buggy since user669677 has edited it.
Here is the proper code:
function createRandomVal($val) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,-";
srand((double)microtime() * 1000000);
$i = 0;
$pass = '';
while ($i < $val) {
$num = rand() % 64;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
I have a bunch of passwords and usernames stored in a txt file and i need to check for matches. I know this is not a safe method but its for leaning purposes.
This code writes the usernames and passwords to a txt file
if(isset($_POST['register'])) //
{
$user = $_POST['username'];
$password=$_POST['password'].PHP_EOL;
$fh = fopen("file.txt","a+");
fwrite($fh,$user." ".$password); //write to txtfile
fclose($fh);
}
Here's the code im having trouble with.
Username and Passwords are stored like this in results
username1 passwords1 username2 password2 etc.
So I need to check if result[0] = userinput AND if it exists check if result[1] = passwordInput and so on.
if(isset($_POST['Logg']))
{
//$_SESSION['username']=$user;
//$_SESSION['password']=$password;
$file = file_get_contents("file.txt"); // Returns a string
$result = explode(" ",$file);
$boolC= false;
for($i=0; $i< count($result); $i++)
{
if($result[$i] === $user)
{
$boolC=true;
$i =$i+1;
if($boolC === true)
{
if($result[$i]===$password)
{
echo 'Password and Username Correct';
}
}
}
}
}
Consider the possibility of having a space in the password so as any symbols. Perhaps you should split on a line break ("\n").
if( $result[$i] === $user && $result[$i+1] === $password )
The first part of the statement has to be true for the second one to be evaluated.
The $i variable is never changed
$file = "username1 passwords1 username2 password2";
$result = explode(" ",$file);
$user = "username1";
$password = "passwords1";
for($i=0; $i< count($result); $i++){
if($result[$i] === $user && $result[$i+1] === $password)
{
echo 'Password and Username Correct';
}
}
Before you go ahead and try to correct this code, I strongly suggest you stay away from storing passwords in a plain text file. It is a huge security hole in your system.
Another architecture issue I can see is that your code would fail if the username or passwords contain a space in them. You probably should use line jumps as a delimiter instead (\n).
I think there is nothing wrong with the logic of the original post.
You should print all the variables to check whether they hold the correct value or not.
the "$user" and "$password" variables are global or not since they would not be known within the braces of the other if block i.e in the block where you check $_POST['logg']
I'm just working on the Backend of a project an have a small problem with this snippet
if (isset($_POST['id'])) {
$cat_delete = "DELETE FROM category WHERE categoryid='".$_POST['id']."' ";
$cat_delete_ex = mysql_query($cat_delete);}`
But if the id is set with post, nothing happens.
The mysql query is working when I delete the
if (isset($_POST['id']))
anyone have an idea ?
Well I am not sure if your method is safe or not, but I would do it like this, might even throw in a regex to check for just numbers if the id is numeric:
EDIT: I made a revision, since you are dealing with an ID, I will assume the ID is numeric only, so instead of escaping it, I just will strip out everything but numbers. This may be a better fit for your situation. I also converted the function to a class so you will be able to reuse the script for several types of sanitizing strings. Maybe its because I am an overachiever too, I don't know. ADD, OCD, etc. Blame it on that :)
$postID = isset($_POST['id']) ? sanitize::ID($_POST['id']) : '';
if (sanitize::email("test#example.com")){
echo "Real email";
} else {
echo "Fake email";
}
if ($postID != ''){
$cat_delete = "DELETE FROM category WHERE categoryid='".$postID."' ";
$cat_delete_ex = mysql_query($cat_delete);
}
class sanitize{
function ID($string){
$string = preg_replace('/[^0-9,]|,[0-9]*$/','',$string);
return $string;
}
# I added another sanitize function so you can see what you can do
# with it. Add phone numbers, domain names, etc... Each one could
# be called with sanitize::{FUNCTION}
function email($string){
if (!ereg("^[^#]{1,64}#[^#]{1,255}$", $string)) {
return false;
}
$email_array = explode("#", $string);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",$local_array[$i])) return false;
}
if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) return false;
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) return false;
}
}
return true;
}
}
are you sure you are using post for the id?(asking because is the right way, but i have one too many times
<form action="action.php?id=hereistheid"
which will bring the id in the $_GET not $_POST.
next the checking
$id=(int)$_POST['id'];
if($id)
{
//do smth
}
I want to block visitor between 2 to 5 minutes every 100 view.. if user view 100 page between 2 to 5 minutes then block user, if user view 100 view in 6 minutes then don't block and reset the counter.
I already create the counter script but i have issue with creating the function which can block visitor between 2-5 mint.
I need help to fix this problem... I try to create a if condition but no luck.. help me please...
$sb_current_time = date("Y-m-d H:i:s", Time());
/////////////////// Cookies Encryption //////////////
function encrypt($text)
{
$key = "E4HD9h4DhS23DYfhHemkS3Nf"; // 24 bit Key
$iv = "fYfhHeDm"; // 8 bit IV
$bit_check = 8;
$text_num = str_split($text, $bit_check);
$text_num = $bit_check - strlen($text_num[count($text_num) - 1]);
for ($i = 0; $i < $text_num; $i++) {
$text = $text . chr($text_num);
}
$cipher = mcrypt_module_open(MCRYPT_TRIPLEDES, '', 'cbc', '');
mcrypt_generic_init($cipher, $key, $iv);
$decrypted = mcrypt_generic($cipher, $text);
mcrypt_generic_deinit($cipher);
return base64_encode($decrypted);
}
//////////////// Encription end /////////
////// Cookies decription /////
function decrypt($encrypted_text)
{
$key = "E4HD9h4DhS23DYfhHemkS3Nf"; // 24 bit Key
$iv = "fYfhHeDm"; // 8 bit IV
$bit_check = 8;
$cipher = mcrypt_module_open(MCRYPT_TRIPLEDES, '', 'cbc', '');
mcrypt_generic_init($cipher, $key, $iv);
if ($encrypted_text != "") {
$decrypted = mdecrypt_generic($cipher, base64_decode($encrypted_text));
mcrypt_generic_deinit($cipher);
$last_char = substr($decrypted, -1);
for ($i = 0; $i < $bit_check - 1; $i++) {
if (chr($i) == $last_char) {
$decrypted = substr($decrypted, 0, strlen($decrypted) - $i);
break;
}
}
}
return $decrypted;
}
///////// Coookies decription end /////////////////
//$sb_check_ban_time = date($sb_current_time, strtotime("+20 minute"));
if ($_COOKIE['spamer_check_time'] == "") {
setcookie('spamer_check_time', encrypt(time()));
}
function time_deff($date2)
{
$date1 = time();
//sleep(2000);
// $date2 = decrypt($_COOKIE['spamer_check_time']);
//echo $date2;
$mins = ($date1 - $date2) / 60;
//echo $mins;
return $mins;
}
//$sb_cookie_expiration = time() + 1200;
//echo $sb_cookie_expiration;
if ($_COOKIE['view2'] != "") {
$explod = explode("-", decrypt($_COOKIE["view2"]));
}
$i_print = $explod[0];
// $i2=$explod[1];
//echo $i2;
$i = 1 + $i_print;
setcookie("view2", encrypt($i . "-123456789")); //// Need to add extra bit to block unwanted text and secure the cookes more..
//
$i = $i++;
// echo $i_print;
//echo "empty".decrypt($_COOKIE["spamer_check_time"]);
$spammer_blocker = decrypt($_COOKIE["spammer_blocker"]);
// or $spammer_blocker==""
$mins = time_deff(decrypt($_COOKIE['spamer_check_time']));
$diff_time = .1; /// User BLock Time
if ($mins >=1 or $mins <=2) {
$block_user=1;
} elseif ($mins >= 2.1) {
$block_user=2;
} else {
}
/* if (.2>$mint) {
// echo "not done";
$block_user=0;
} elseif (.2 <= $mint) {
echo "block User";
$block_user=1;
} elseif ($mins>=1) {
echo "reset cookies";
$block_user=2;
}*/
if ($block_user==1 and $i_print >= 15) {
if ($spammer_blocker == "") {
setcookie("spammer_blocker", encrypt(time()));
header('HTTP/1.1 403 Forbidden');
$time_rev = $diff_block_time - $diff_time;
$round_time = round($time_rev, 2);
$time_reverse = str_replace('-', '', $round_time);
echo "Wait " . $time_reverse . " Minuts before using this site..";
exit(0);
} else {
//$sb_check_ban_time = $spammer_blocker;
$diff_block_time = time_deff($spammer_blocker);
//echo $diff_block_time;
//$sb_check_ban_time = date($spammer_blocker, strtotime("+1 minute"));
if ($diff_time <= $diff_block_time) {
/// echo "Delete the IP and cookies";
setcookie("spammer_blocker", "");
setcookie("view2", "");
setcookie("spamer_check_time", "");
} else {
//echo "Still Block"; /// echo "Still Block";
header('HTTP/1.1 403 Forbidden');
// echo "IP Block for Spaming wait few mint";
$time_rev = $diff_block_time - $diff_time;
$round_time = round($time_rev, 2);
$time_reverse = str_replace('-', '', $round_time);
echo "Wait " . $time_reverse . " Minuts before using this site..";
exit(0);
}
}
} elseif ($block_user==2) {
setcookie("spammer_blocker", "");
setcookie("view2", "");
setcookie("spamer_check_time", "");
echo "cookies reset";
} else {
}
First, you need to know who they are...
For casual users, you can rely on cookies. But if you are having problem with an abuser, then they will simply ignore your attempt to stop them and not send a cookie.
There are various levels of knowing "who" someone is.
ID in URL
Cookies
IP Address
And they can ALL be overcome with different levels of diffulculty...
Way too easy (just spoof a different ID, etc...)
Cookies are the same as #1
IP addresses are harder to overcome unless you have a botnet or similar
For your case, you should likely block the IP address as it's the only reasonable way for you to get done what you are looking for.
--
Next, you need to be able to keep track of their connections. iptables in Linux has a way to track the number of connections and block for a specific number of minutes after a certian threshold is reached.
Using only PHP, you need to record each hit, and the IP address of that hit. An SQL database would be one of the more efficient ways of doing this.
If you don't care about history, then simply (mysql):
INSERT INTO HitTable SET IP=..., Visits=1
ON DUPLICATE KEY UPDATE Visits=Visits+1
A background crontab could run a query like this every minute?
UPDATE HitTable SET Visits = Visits - 10
DELETE FROM HitTable WHERE Visits < 1
Finally, when a visitor visits, you would check the database table for
SELECT Visits<100 WHERE IP=...
AND if that returns True, let them in, else block them.
Hope this helps a bit.
Storing the timeout value in a cookie will be absolutely trivial for a user to change/delete the cookie
Storing it in a session variable is a bit more reliable, but again - the user could just delete the session cookie, get a new session going, and start reading again.
That being said, you'd do something like this:
<?php
session_start();
if (user_should_be_blocked()) {
$_SESSION['blocked_start_time'] = time();
header("Location: timeout.html");
}
if ($_SESSION['blocked_start_time'] > (time() - 300)) {
header("Location: timeout.html");
}
// got here, must not be blocked and/or timeout has expired
$_SESSION['blocked'] = false;
$_SESSION['block_start_time'] = null;
.... continue on
I would use the header funciton to redirect them to another page, either empty or just less bankwidth intensive (assuming that's why you're making this anyway). Soemthing like...
if ($block_user == 1)
header("Location: blockPage.php");
At the top of all pages you need to block.
Edit: actually, come to think of it, (2) is of course not necessary, if 2 people or 2 computers are logged in they'll only consume their alloted amount of views faster..
You can do this provided:
A user needs to be logged in to see the pages.
You don't allow the same user(name) to be logged in twice with different sessions.
You store the count per-user, not per-session or per-ip/whatever.
(2) is not possible with default file based sessions. A custom database or other persistent storage solution is needed in which you can scan for other session-id's of a current user-id. In a database you would just store a user-id field, a custom memcached solution could also be built, etc. To prevent users being locked out of a session they no longer have my solution was always to destroy any old session a user had the moment they log in. Effectively, if it's tried with multiple sessions/ips, they'll have to log in again and again invalidating the previous session.
(3) again some persistent storage with a timestamp+userid+count (in MySQL's case an INSERT INTO tablename (user_id,time,count) VALUES (<id>,NOW(),1) ON DUPLICATE KEY UPDATE count=count+1 comes to mind to easily increment view counts.
And on every view query the database again and again about how many views the visitor had the last X minutes.
I am generating unique id for my small application but I am facing some variable scope problem. my code-
function create_id()
{
global $myusername;
$part1 = substr($myusername, 0, -4);
$part2 = rand (99,99999);
$part3 = date("s");
return $part1.$part2.$part3;
}
$id;
$count=0;
while($count == 1)
{
$id;
$id=create_id();
$sqlcheck = "Select * FROM ruser WHERE userId='$id';";
$count =mysql_query($sqlcheck,$link)or die(mysql_error());
}
echo $id;
I dont know which variable I have to declare as global
That doesn't look like a variable scope problem, it looks like a simple variable assign problem:
$count=0;
while($count == 1)
{
This block will clearly never execute.
Further, please use a boolean with a good name when doing boolean checks. It reads so much cleaner. i.e.:
function isUniqueUserID($userIDToCheck)
{
$sqlcheck = "Select * FROM user WHERE userId='$userIDToCheck';";
$resource = mysql_query($sqlcheck)or die(mysql_error());
$count = mysql_fetch_assoc($resource);
if( count($count) > 0)
{return false;}
return true;
}
$userIDVerifiedUnique = false;
while(! $userIDVerifiedUnique )
{
$userIDToCheck = create_id();
$userIDVerifiedUnique = isUniqueUserID($userIDToCheck );
}
Note that mysql_query will use the last used connection if you don't specify a link:
http://us2.php.net/mysql_query
No need to make it global.
in adition to Zak's answer i'd pass the username into the function instead of using globals
function create_id($username)
{
$part1 = substr($username, 0, -4);
$part2 = rand (99,99999);
$part3 = date("s");
return $part1.$part2.$part3;
}
also
//$id; no need for this
$count=1; // this bit
while($count == 1) // not sure what's going on
{
//$id; again same thing no need for this
$id=create_id($myusername);
edit: now that i think of it: how do you expect to find "Select * FROM ruser WHERE userId='$id';"? A Select query is used to find something specific, your username is so random, i think the likely hood of actually successfully getting a record is 1 in a bajillion.
edit2 whoops, i see the whole point is to get a unique username... O_O
In addition to the others:
$count =mysql_query($sqlcheck,$link)or die(mysql_error());
mysql_query doesn't return a record count but, rather, a resource.
mysql_query