This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
IGNORE THE QUESTION:
The CSS File I was including pulled in the the other files hence the correlation *facepalm*
We have the following code for picking a CNAME CDN reference per filename. It must return the same URL everytime based on a given filename. We thought this would be sufficiently random:
<?php
function cdn_prefix($fileName) {
$number_of_servers = 4;
$md5 = md5($fileName);
$md5 = substr($md5, 0, 4);
$hash_number = base_convert($md5, 16, 10);
$server_number = ($hash_number % $number_of_servers) + 1;
$server_prefix = '//static' . $server_number . '.' . $_SERVER['SERVER_NAME'];
return $server_prefix . $fileName;
}
?>
However it seems to favour the number 3:
No matter what I do (salt, different bases, random multiplication, etc) the results headerBg through to mainNavPipe (on the screen shot) all have the same number.
Is there a better algorithm?
EDIT:
Here are the results using same algorithm using a SHA1
Everywhere calls the same function - as it returns the whole URL and wouldn't show the static[1-4] domain unless it when through this function.
The array (for testing) is:
FILES = [
'/a/files/image/250.jpg',
'/a/files/image/244.jpg',
'/a/files/image/247.jpg',
'/a/css/global/core.css',
'/a/css/global/print.css',
'/a/img/global/new_logo.gif',
'/a/img/global/book-a-free-survey.gif',
'/a/img/global/make_an_enquiry.gif',
'/a/img/global/purchase-locks-blue.jpg',
'/a/files/image/251.jpg',
'/a/img/global/bg.gif',
'/a/img/global/headerBg.jpg',
'/a/img/global/basketBg.gif',
'/a/img/global/arrow.png',
'/a/img/global/trolley.gif',
'/a/img/global/mainNavBg.gif',
'/a/img/global/mainNavCurrentBg.gif',
'/a/img/global/mainNavPipe.gif',
'/a/img/common/sectionNavBg.jpg',
'/a/img/global/nav_arrow.gif',
'/a/img/global/footerBg.jpg',
'/a/img/global/footerCopyrightBg.jpg',
'/a/img/global/footerLogo.jpg'
]
This was probably a one-time thing or a bug elsewhere.
function cdn_prefix($fileName) {
$number_of_servers = 4;
$md5 = md5($fileName);
$md5 = substr($md5, 0, 4);
$hash_number = base_convert($md5, 16, 10);
$server_number = ($hash_number % $number_of_servers) + 1;
return $server_number;
}
$arr = array(1=>0, 2=>0, 3=>0, 4=>0,);
for ($i = 1; $i < 200000; $i++) {
$arr[cdn_prefix("anrg".$i)]++;
}
print_r($arr);
gives:
Array
(
[1] => 49770
[2] => 50090
[3] => 50026
[4] => 50113
)
Related
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
How do I validate a string against the following rules:
$string = 'int(11)';
Rule: first 4 characters MUST be 'int('
Rule: next must be a number between 1 and 11
Rule: next must be a ')'
Rule: Everything else will fail
Experienced PHP Developer here - Regular Expressions are not my strong point..
Any help or suggestions welcome.
Thanks guys..
if (preg_match('/int\((\d{1,2})\)/', $str, $matches)
&& (int) $matches[1] <= 11 && (int) $matches[1] > 0
) {
// ... do something nice
} else {
echo 'Failed!!!'
}
Or if you want to not use the pReg library (can be faster):
$str = 'int(11)';
$i = substr($str, 4, strpos($str, ')') - 4);
if (substr($str, 0, 4) === 'int('
&& $i <= 11
&& $i > 0
) {
echo 'succes';
} else {
echo 'fail';
}
use this regular expression int\((\d|1[01])\)
int\(( first rule
(\d|1[01]) second rule
\) third rule
This regular expression is even smaller:
int\((\d1?)\)
or without the capturing group (if you don't need to retrieve the numeric value).
int\(\d1?\)
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I dont understand why this is giving me an t string syntax error. It looks to me correct! Can somebody please help me out? I am few weeks into my php learning attempt and just trying to make sense of this jumble. I know this is something incredibly stupid but I cannot figure it out!
<?php
// set up some variables
// the toys
$item1 = "X−ray specs";
$item2 = "Watch with built−in poison gas canister";
$item3 = "Exploding chewing gum";
// the price
$item1_cost = 100; $item2_cost = 250; $item3_cost = 32;
// the amount
$item1_qty = 1; $item2_qty = 2; $item3_qty = 15;
// calculate cost for each item
$item1_total = $item1_cost * $item1_qty;
$item2_total = $item2_cost * $item2_qty;
$item3_total = $item3_cost * $item3_qty;
// calculate grand total
$grand_total = $item1_total + $item2_total + $item3_total;
//special secret agent discount − 10%
$discount = 10;
// which reduces total bill amount
$amount = ($grand_total * 10)/100;
// the bottom line
$net_total = $grand_total − $amount;
?>
Somehow you managed to use "–", an n-dash, instead of "-", a minus sign. Did you copy/paste it from a web article? That might have done it. You might also encounter this sort of error if you have “ or ” instead of ", which happens fairly frequently with copying code from web pages.
Change this
$net_total = $grand_total − $amount;
to this
$net_total = $grand_total - $amount;
or just retype the line.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am Having the data like:
$aa ="msg_1";
I want to add +1 at the end of string after doing the explode operation like the following:
$nwMsg =explode("_",$aa);
$inMsg =number_format($nwMsg[1])+1;
$finStr =$nwMsg[0].'_'.$inMsg;
After This i want to form the string again and repeating the same process again but it is increasing up to "10" after that it is not increasing...
You should put the +1 inside the number_format call, not after it.
EDIT: If you just want $nwMsg[1] to be treated as a number, just adding 1 to it will work fine, since + is a numerical operator.
function add_one($string) {
preg_match_all("/[a-zA-Z]+_\d+/", $string, $matches);
$elements = $matches[0];
$last = $elements[count($elements)-1];
$components = explode("_", $last);
$newnum = $components[1] + 1;
return $string . $components[0] . "_" . $newnum;
}
echo add_one("msg_1"); // prints "msg_1msg_2"
echo add_one("msg_1msg_2msg_3msg_4msg_5msg_6msg_7msg_8msg_9"); // prints "msg_1msg_2msg_3msg_4msg_5msg_6msg_7msg_8msg_9msg_10"
$nwMsg =explode("_",$aa);
$inMsg =number_format($nwMsg[1] +1) ;
$finStr =$nwMsg[0].'_'.$inMsg;
$aa= "msg_1";
$new_string= explode("_", $aa);
$new_aa= $new_string[0] ."10";
This is wrong
$inMsg =number_format($nwMsg[1])+1;
This is how it is done
$inMsg =number_format($nwMsg[1]+1);
$nwMsg =explode("_",$aa);
$inMsg =$nwMsg[1] +1 ;
$finStr =$nwMsg[0].'_'.$inMsg;
You will get the result with out using number_format.
One more thing, which can lead to errors and you need to take care - because you want to add two numbers, first make sure that you convert $nwMsg[1] into number (integer or float, it depends):
$nwMsg =explode("_",$aa);
$inMsg =number_format((int)$nwMsg[1]+1);
$finStr =$nwMsg[0].'_'.$inMsg;
How about a different solution:
function add($matches) {
return ++$matches[0];
}
$new = preg_replace_callback("(\d+)", "add", $aa);
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
will this function be safe for password and email hash/crypt? EDIT: Cleary not!
$password = mysql_real_escape_string(htmlspecialchars(trim($_POST['password'])));
$hash_algo = "sha512";
$raw_output = false;
$hash = hash($hash_algo, $password, $raw_output);
$hash_20 = substr($hash, 0, 20);
$salt = substr($hash, -20);
$crypt = crypt ( $hash_20, $salt);
$crypt_20 = substr($crypt, 0, 20);
EDIT:
Here is the code I'm using now. I think this one is pretty safe. It's a PBKDF2 password hash function with a random salt generator.
So, here is the PBKDF2 function.
p is for password.
s is for salt.
c is for iteration
kl is for key lenght.
a is for hash algorithm.
function pbkdf2( $p, $s, $c, $kl, $a = 'sha256' )
{
$hl = strlen(hash($a, null, true)); # Hash length
$kb = ceil($kl / $hl); # Key blocks to compute
$dk = ''; # Derived key
# Create key
for ( $block = 1; $block <= $kb; $block ++ ) {
# Initial hash for this block
$ib = $b = hash_hmac($a, $s . pack('N', $block), $p, true);
# Perform block iterations
for ( $i = 1; $i < $c; $i ++ )
# XOR each iterate
$ib ^= ($b = hash_hmac($a, $b, $p, true));
$dk .= $ib; # Append iterated block
}
# Return derived key of correct length
return substr($dk, 0, $kl);
}
Salt generator:
function salt( $length )
{
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$salt="";
$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ )
{
$salt.= $chars[ rand( 0, $size - 1 ) ];
}
return $salt;
}
In use:
if(isset($_POST['submit']))
{
$Password = mysql_real_escape_string(htmlspecialchars(trim($_POST['Password'])));
//To make sure the salt has never more chars than the password.
$salt_length = strlen($Password);
$salt = salt($salt_length);
//Hash Password
$hash = base64_encode(pbkdf2($Password, $salt, 100000, 32));
//--------------//
}
Googling a bit find out that 100000 iterations is pretty safe but I guess 10000 will be enough tho.
Since you're hashing the input, you cannot simply reverse it to the original value. Assuming an attacker knows this algorithm, the question is how long does it take to brute force the password. For that, test how long one iteration of the algorithm takes. Then calculate how many tries an attacker would have to do to try all possible passwords on a high-end machine. Then you have your answer how "safe" the algorithm is. You are looking for an answer measured at least in millennia, but preferably big bangs.
That is, assuming there are no actual attacks against the algorithm an attacker could try that would shorten that time.
Since you are deriving the salt from the input itself, you're simply stretching the algorithm a bit. You're not using an actual salt, which is a random unique value that is independent of the input. As such, you are using an unsalted input with a not so complicated hashing algorithm. My bet would be that it's not very hard to brute force a whole database of passwords "secured" with this algorithm.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Write a function GeneratePassword which accepts two arguments, an integer and a character string consisting of letters (a-z) and digits (0-9).
When GeneratePassword(5,'abc0123') is called, it should return a random string of 5 characters taken from 'abc0123'.
For Example : GeneratePassword(7,'abczxc012394') could return any of the following outputs :
2c00acb
2c23z93
030b2a4
I think you're looking for the homework tag.
In the spirit of helping others I'll post a commented solution. However, keep in mind the only way to get better is to try first, ask questions later. That is to say, make an attempt then ask others where you went wrong.
Example/Demo:
/**
* Generate a password N characters long consisting of characters
*
* #param int $size
* #param string $characters
* #param callback $random (optional) source of random, a function with two parameters, from and to
* #return string|NULL password
*/
function generate_password($size, $characters, $random = 'rand') {
// validate $size input
$size = (int) $size;
if ($size <= 0) {
trigger_error(sprintf('Can not create a password of size %d. [%s]', $size, __FUNCTION__), E_USER_WARNING);
return NULL;
}
if ($size > 255) {
trigger_error(sprintf('Refused to create a password of size %d as this is larger than 255. [%s]', $size, __FUNCTION__), E_USER_WARNING);
return NULL;
}
// normalize $characters input, remove duplicate characters
$characters = count_chars($characters, 3);
// validate number of characters
$length = strlen($characters);
if ($length < 1) {
trigger_error(sprintf('Can not create a random password out of %d character(s). [%s]', $length, __FUNCTION__), E_USER_WARNING);
return NULL;
}
// initialize the password result
$password = str_repeat("\x00", $size);
// get the number of characters minus one
// your string of characters actually begins at 0 and ends on the
// string-length - 1:
// $characters[0] = 'a'
// $characters[1] = 'b'
// $characters[2] = 'c'
$length--;
// get one random character per each place in the password
while ($size--)
{
// generate a random number between 0 and $length (including)
$randomValue = $random(0, $length);
// that random number is used to turn the number into a character
$character = $characters[$randomValue];
// set the random character
$password[$size] = $character;
}
// return the result
return $password;
}