PHP - Euclidean Distance Algorithm In Php
I made a post a while back about this topic he 1. The input from the project will be coming from a mobile app which will be using a qr code. The qr code contains the Room Number and the 2 Access Points for each room. When a user scans the qr code it will pass that info to the web app that has the algorithm and verify what room he/she is in the access point that was 'scanned'. 2. For the testing of the project we decided to use two rooms of the building of our alma mater and the access points were already defined based on tests:
Room 413 has Access Point 1 that have the values of -67 dBm to -89 dBm and Access Point 2 that have the values of -40 dbm to -57 dBm while
3. I already inputted the values and the rooms I've mentioned above in mysql to verify if the input from the qr code that was scanned it correct. but sadly we are stuck with the algorithm itself.
Similar Tutorials
Hi,
Write a function that calculates the Euclidean distance for points: eucl(q1,z1,r2,z2). Date:
$r1=1; $z1=12; $r1=43; $z1=123;
formula to the Euclidean distance: (r1,z1,r2,z2)=sqrt[(r1-z1)*(r1-z1) + (r2-z2)*(r2-z2)],
Can anyone help? How do I show how many miles away the nearest location is? This code works with showing stores within the radius of the zip code entered, but it does not show the miles. Can anybody see what I have to do to display the miles? Code: [Select] <?php // Create page variables $r = NULL; $z = NULL; $stores = NULL; $Errors = NULL; include('inc/connect.db.mrk.php'); // Declare page functions function Dist($lat1, $lon1, $lat2, $lon2) { $distance = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($lon1 - $lon2)); $distance = (rad2deg(acos($distance))) * 69.09; return $distance; } ### Handle form if submitted if (isset ($_POST['submitted'])) { // Validate Postcode code field if (!empty ($_POST['zip']) && is_numeric ($_POST['zip'])) { $z = (int)$_POST['zip']; // Verify Postcode code exists $query = "SELECT latitude, longitude FROM zipdata WHERE zip = '$z'"; //$result = mysql_query ($query); $result=mysql_query($query) or die ('Invalid query.'); if (mysql_num_rows ($result) == 1) { $zip = mysql_fetch_assoc ($result); } else { $Errors = '<p>The postcode code you entered was not found!</p>'; $z=NULL; } } // Validate radius field if (isset ($_POST['radius']) && is_numeric ($_POST['radius'])) { $r = (int)$_POST['radius']; } // Proceed if no errors were found if ($r && $z) { // Retrieve coordinates of the locations $result = mysql_query("SELECT LocAddState, MktName, LocAddSt, LocAddZip, LocAddCity, x1, y1 FROM store INNER JOIN zipdata ON store.LocAddZip=zipdata.zip") or die(mysql_error()); //$result = mysql_query ($query); // Go through and check all locations while ($row = mysql_fetch_assoc ($result)) { // Separate closest locations $distance = Dist($row['y1'], $row['x1'], $zip['latitude'], $zip['longitude']); // Check if store is in radius if ($distance <= $r) { $stores[] = array ( 'name' => $row['MktName'], 'address' => $row['LocAddSt'], 'state' => $row['LocAddState'], 'town' => $row['LocAddCity'], 'postal' => $row['LocAddZip'], ); } } } else { $Errors = ($Errors) ? $Errors : '<p>Errors were found please try again!</p>'; } } ?><html> <head> <title>Store Locator</title> </head> <body> <form action="" method="post"> <p>Enter your zip code below to find locations near you.</p> <?php echo ($Errors) ? $Errors : ''; ?> <div> <label>Zip:</label> <input name="zip" type="text" size="10" maxlength="5" /> </div> <div> <label>Search Area:</label> <select name="radius" id="radius"> <option value="5">5 mi.</option> <option value="10">10 mi.</option> <option value="15">15 mi.</option> <option value="20">20 mi.</option> <option value="50">50 mi.</option> <option value="100">100 mi.</option> </select> </div> <div> <input type="hidden" name="submitted" value="submitted" /> <input type="submit" value="Submit" /> </div> </form> <?php if (isset ($stores)) { if (!empty ($stores)) { echo '<p><strong>' . count ($stores) . ' results were found.</strong></p>'; foreach ($stores as $value) { echo '<p><strong>' . $value['name'] . '</strong><br />'; echo $value['address'] . '<br />'; echo $value['town'] . ', ' . $value['state'] . ' ' . $value['postal'].'<br />'; echo $distance . ' miles away <br />'; /*echo ' <a target="_blank" href="http://maps.google.com/maps?q=', $value['address'], ' ', $value['town'], ', ', $value['state'], ' ', $value['postal'], '">Map this location</a><br />'; */ echo '</p>'; } } else { echo '<p><strong>No results found</strong></p>'; } } ?> </body> </html> Right now it shows like this Code: [Select] 1482.92070414 miles away Thanks in advance Table Of Contents - General Description - Database Image - Code - Code - Issue I have the following code (from outside sources), which, is apparently incompatible with my co-ordinate types. Here is a database excerpt (first thirty rows) of about 9200 airports from around the world. <?php function distance($lat1, $lon1, $lat2, $lon2, $unit) { $theta = $lon1 - $lon2; $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); $dist = acos($dist); $dist = rad2deg($dist); $miles = $dist * 60 * 1.1515; $unit = strtoupper($unit); if ($unit == "K") { return ($miles * 1.609344); } else if ($unit == "N") { return ($miles * 0.8684); } else { return $miles; } } $dep = $_GET['dep']; $arr = $_GET['arr']; $sql = 'SELECT * FROM `airports` WHERE `iata` = \'' . $dep . '\''; $query = mysql_query($sql); $dep = mysql_fetch_array($query); $sql = 'SELECT * FROM `airports` WHERE `iata` = \'' . $arr . '\''; $query = mysql_query($sql); $arr = mysql_fetch_array($query); echo distance($dep['latt'], $dep['long'], $arr['latt'], $arr['latt'], "k") . " km<br>"; ?> Here is my output [dep=yyz, arr=yul] with [yyz = 43.68, -79.63; yul = 45.47, -73.74] : 8719.64724823 km Obviously, with YYZ being Toronto, Canada and YUL being Montreal, Canada, it is definitely not 9000 km away (actually, ~500 km). Can you help me convert the units, or re-write the algorithms in order to make it function correctly. Thank you in advance. This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=348500.0 I have this script that works 9/10 of how it's suppose too. This does not calculate the correct distance for the results. Can anybody see where the problem lies? Here is the code Code: [Select] // see if our zip code has been posted, and if it is a 5 digit # if (isset($_POST['zip'])) { // remember to sanitize your inputs // this removes whitespace around the data and the next line makes sure its a 5 digit number $findzip = trim($_POST['zip']); if (preg_match("#^\d{5}$#",$findzip)) { include('inc/connect.php'); include('inc/functions.php'); // create a query that will select the zip code (if we can't find the user entered zip, we return an error) $query = "SELECT latitude,longitude,state,city FROM zipdata WHERE zip=".$findzip." LIMIT 1"; $result = mysql_query($query); if (mysql_num_rows($result) > 0) { // grab the latitude, longitude,state and city from our result list($flat,$flon,$fstate,$fcity) = mysql_fetch_row($result); // now get all markets in the same state, or all markets if no states match // we want to reduce the amount of work the database has to do so we see if a state matches $query = "SELECT * FROM mrk WHERE state='".$fstate."'"; $result = mysql_query($query); if (mysql_num_rows($result) < 1) { $query = "SELECT * FROM mrk"; $result = mysql_query($query); } // now we process the markets to gather their data, //this result should not be empty, so I was lazy and didn't write an else case if (mysql_num_rows($result) > 0) { while($row = mysql_fetch_assoc($result)) { // first put all of the data for this market into an array, with the market id as the key $storeinfo[$row['id']] = $row; // get the store zip $dzip = $row['zip']; // query for the store's latitude and longitude $query = "SELECT latitude,longitude FROM zipdata WHERE zip=".$dzip." LIMIT 1"; $result2 = mysql_query($query); if (mysql_num_rows($result2) > 0) { list($dlat,$dlon) = mysql_fetch_row($result2); // now get the distance from the user entered zip $stores[$row['id']] = calcDist($flat,$flon,$dlat,$dlon); } } } asort($stores); print "<p>The Markets closest to you: $findzip</p><br>\n"; $maploc = "'You are here','$findzip',"; foreach($stores as $k=>$v) { $output .= "<h3 style='margin:0;padding:0'><b>".$storeinfo[$k]['company']."</b><br>(approx ".round($v)." miles)</h3>"; $output .= "<p style='margin:0 0 10px 0;padding:0'><a href='".$storeinfo[$k]['url']."'>".$storeinfo[$k]['url']."</a><br>"; $output .= $storeinfo[$k]['city']." ".$storeinfo[$k]['state'].", ".$storeinfo[$k]['zip']."</p>"; } echo $output; } } } Here is the function.php Code: [Select] function calcDist($flat, $flon, $dlat, $dlon) { $distance = sin(deg2rad($flat)) * sin(deg2rad($dlat)) + cos(deg2rad($flat)) * cos(deg2rad($dlat)) * cos(deg2rad($flon - $dlon)); $distance = (rad2deg(acos($distance))) * 69.09; return $distance; } Thank you in advance I have a page that gets the closest stores to a latitude and longitude. I want to have a MySQL table like this: location_id:::::items showing how many items are at each store and then show 'spit' them in the following format with the lowest number of items first: location_id, distance to location_id, items. here is the code I am using to show location_id by distance Code: [Select] <?php include "connectionfile.php"; $lat = $_GET["lat"]; $lng = $_GET["lng"]; $sql = mysql_query("SELECT id, ( 6371 * acos( cos( radians($lat) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians($lng) ) + sin( radians($lat) ) * sin( radians( lat ) ) ) ) AS distance FROM locations HAVING distance < 250 ORDER BY distance LIMIT 0 , 60; "); WHILE($lstlocations = mysql_fetch_array($sql)) { $location_id[$count]=$lstlocations['id']; $distance=$lstlocations['distance']; echo "id = " . $location_id[$count] . " Distance = " . $distance. "<br>"; $count = $count + 1; } ?> What would be the best way to achieve this? Hi, I have been using the following function on my server and it works fine but when I try and use it on a different server it wont seem to work. Any ideas on why it wont work on the new server and any ideas on how I can do some error checking to figure out why ? Thanks in advance, Scott Code: [Select] <?php function get_driving_information($start, $finish, $raw = false) { # Convert any lon / lat coordingates if(preg_match('@-?[0-9]+\.?[0-9]*\s*,\s*-?[0-9]+\.?[0-9]@', $start)) { $url = 'http://maps.google.co.uk/m/local?q='.urlencode($start); if($data = file_get_contents($url)) { if(preg_match('@<div class="cpfxql"><a href="[^"]*defaultloc=(.*?)&ll=@smi', $data, $found)) { $start = trim(urldecode($found[1])); } else { throw new Exception('Start lon / lat coord conversion failed'); } } else { throw new Exception('Start lon / lat coord conversion failed'); } } if(preg_match('@-?[0-9]+\.?[0-9]*\s*,\s*-?[0-9]+\.?[0-9]@', $finish)) { $url = 'http://maps.google.co.uk/m/local?q='.urlencode($finish); if($data = file_get_contents($url)) { if(preg_match('@<div class="cpfxql"><a href="[^"]*defaultloc=(.*?)&ll=@smi', $data, $found)) { $finish = trim(urldecode($found[1])); } else { throw new Exception('Finish lon / lat coord conversion failed'); } } else { throw new Exception('Finish lon / lat coord conversion failed'); } } if(strcmp($start, $finish) == 0) { $time = 0; if($raw) { $time .= ' seconds'; } return array('distance' => 0, 'time' => $time); } $start = urlencode($start); $finish = urlencode($finish); $distance = 'unknown'; $time = 'unknown'; $url = 'http://maps.google.co.uk/m/directions?saddr='.$start.'&daddr='.$finish.'&hl=en&oi=nojs&dirflg=d'; if($data = file_get_contents($url)) { if(preg_match('@<span[^>]+>([^<]+) (mi|km)</span>@smi', $data, $found)) { $distanceNum = trim($found[1]); $distanceUnit = trim($found[2]); if($raw) { $distance = $distanceNum.' '.$distanceUnit; } else { $distance = number_format($distanceNum, 2); if(strcmp($distanceUnit, 'km') == 0) { $distance = $distanceNum / 1.609344; } } } else { throw new Exception('Could not find that route'); } if(preg_match('@<b>([^<]*)</b>@smi', $data, $found)) { $timeRaw = trim($found[1]); if($raw) { $time = $timeRaw; } else { $time = 0; $parts = preg_split('@days?@i', $timeRaw); if(count($parts) > 1) { $time += (86400 * $parts[0]); $timeRaw = $parts[1]; } $parts = preg_split('@hours?@i', $timeRaw); if(count($parts) > 1) { $time += (3600 * $parts[0]); $timeRaw = $parts[1]; } $time += (60 * (int)$timeRaw); } } return array('distance' => $distance, 'time' => $time); } else { throw new Exception('Could not resolve URL'); } } Hi Guys I need a PHP function to which I pass two postcodes and it works out the road distance, I dont mind using google or any other API I have managed to fing JS ways and php functions using crow route but I really really need a traffic distance in PHP Please advice, Help Thank you Getting the difference in seconds between two timestamps is easy. Taking the seconds and doing a breakdown of time frames is also easy. Code: [Select] <?php echo '<p>There are a total of ' . round($seconds) . ' seconds between Timestamp 1 and Timestamp 2.</p>'; echo '<p>There are a total of ' . round($seconds / 60) . ' minutes between Timestamp 1 and Timestamp 2.</p>'; echo '<p>There are a total of ' . round(($seconds / 60) / 1440) . ' days between Timestamp 1 and Timestamp 2.</p>'; echo '<p>There are a total of ' . round((($seconds / 60) / 1440) / 7) . ' weeks between Timestamp 1 and Timestamp 2.</p>'; echo '<p>There are a total of ' . round((((($seconds / 60) / 1440) / 7) / 30)) . ' months between Timestamp 1 and Timestamp 2.</p>'; echo '<p>The total breakdown of time from Timestamp 1 to Timestamp 2 is .</p>'; ?> What I am trying to figure out, is get a collective amount as well.... X years X months X weeks X days X minutes and X seconds. Does anyone have any good algorithm for handling that, or have any feedback on where to start to handle this type of math. Hi i am looping through some history data i have collected via soap. i have the data in an array containing lat, lon and timestamp. Code: [Select] foreach($history['data'] as $record) { echo 'add(jQuery(this), number += 1, "' . date("d-m-Y @ h:i:s",$record['timestamp']) . '", "map_post.php?n=' . $name . 'u=' . $history['user'] . '", "' . $history['user'] . '", "' . $record['latitude'] . '", "' . $record['longitude'] . '");'; } i wondered it it would be possible to check if each position is within say 300 metres of the last position and if so dont display it? I use mysql to retrieve data from database and use php to display the data onto website directly by the following codes : $query2 = "SELECT message FROM messages WHERE username='{$username1}'"; $result2 = mysql_query($query2,$connection) or die (mysql_error()); confirm_query($result2); while($userinfo = mysql_fetch_array($result2)){ echo "<div class=\"messagepiece\">" . $userinfo['message'] . "</div><br>"; } I want the div(s) arrange style like on the picture http://2aek.com/inventory/divs.jpg display the 1st 4 divs onto 1st column, jump to 2nd column to display another 4 divs.... Below are the codes of how the divs arrangement : <div class="test1" style="left:0px; top:0px;"> asdawdaw </div> <div class="test1" style="left:0px; top:70px;"> asdawdaw </div> <div class="test1" style="left:0px; top:140px;"> asdawdaw </div> <div class="test1" style="left:0px; top:210px;"> asdawdaw </div> <div class="test1" style="left:200px; top:35px;"> asdawdaw </div> <div class="test1" style="left:200px; top:105px;"> asdawdaw </div> <div class="test1" style="left:200px; top:175px;"> asdawdaw </div> <div class="test1" style="left:200px; top:245px;"> asdawdaw </div> <div class="test1" style="left:400px; top:0px;"> asdawdaw </div> <div class="test1" style="left:400px; top:70px;"> asdawdaw </div> <div class="test1" style="left:400px; top:140px;"> asdawdaw </div> <div class="test1" style="left:400px; top:210px;"> asdawdaw </div> So the looping styles should be something like : loop left 0 for four times > 200 for four times > 400 for four times. loop top 0 > 70 > 140 > 210 then 35 > 105 > 175 > 245 then again 0 > 70 > 140 > 210. Seriously I don't know how to write the algorithm of looping. I guess the looping algorithm for left should be something like : i = 0 ; i=>4 ; i++{ k=0; k=>20000; k+200{} } But it is so wrong, it will stop at 4th loop and each loop will be 0, 200, 400, 800. That's not what I want. Seriously I can't figure out the algorithm, my brain is stupid, so can you guys guide me please? Alright, so I have 100 user ids which I need sorted in a very specific way. Right now, they're organized in a 1-100 format. Let's think of each ID as ID#1, ID#2, ID#3 etc all the way up to ID#100. I need to code a script to echo them out in the following order: $ID2.'<br/>'; $ID1.'<br/>'; $ID4.'<br/>'; $ID3.'<br/>'; $ID6.'<br/>'; $ID5.'<br/>'; //etc up to $ID100.'<br/>'; $ID99.'<br/>'; Is there any special algorithm or trick with an array to do this? I will attach a file with each ID seperated by a semi-colon. And also here is the script I have right now which echo's them out in order: <?PHP $File = "IDs.txt"; $Login = file($File); $String = file_get_contents($File); $Logins = explode(";", $String); foreach($Logins as $Login) { echo $Login.'<br/>'; } ?> I'm decoding some strings that were encoded by someone else, I have the key and already made a decoder in C++ and it is working but I want to avoid call "exec". For now I've tried to use mcrypt_decrypt (mcrypt Version 2.5.8) with all possible options but none gives correct results, compared to the correct c++ .exe results. I tried to "convert" the function to PHP around 6 times but none worked, I'm sure there is something I'm missing or I don't know about. This is the working decoder function in c++: Code: [Select] void XTEADecode(LPCVOID lpBuffer, int dwSize, DWORD *lpXteaKey) { LPDWORD lpPtr = (LPDWORD)lpBuffer; int j; for(j=0; j<dwSize; j=j+8){ unsigned long v0=*lpPtr, v1=*(lpPtr+1), i; unsigned long delta=0x9E3779B9, sum=delta*32; for(i=0; i<32; i++) { v1 -= ((v0 << 4 ^ v0 >> 5) + v0) ^ (sum + lpXteaKey[sum>>11 & 3]); sum -= delta; v0 -= ((v1 << 4 ^ v1 >> 5) + v1) ^ (sum + lpXteaKey[sum & 3]); } *lpPtr=v0; *(lpPtr+1)=v1; lpPtr+=2; } } Any suggestions would be appreciated. Hi, I need to create a secure API at work so that 2 systems can interact with each other and request data (json format). I need to use an API key for this but don't want to use an API key stored in a database, what is the best way to go about this? I would like to use some sort of encryption algorithm and a white list of a few values to validate against once decrypted, is this safe and are there any algorithms I can use to generate my keys and white list? I am trying to write a PHP script that implements the MD5 algorithm just so that I can better understand MD5's inner-workings. For those of you already familiar with how MD5 works, could you help me figure out why my script is not producing the correct output? <?php $string = ""; $a = "01100111010001010010001100000001"; // 0x67452301 $b = "11101111110011011010101110001001"; // 0xEFCDAB89 $c = "10011000101110101101110011111110"; // 0x98BADCFE $d = "00010000001100100101010001110110"; // 0x10325476 $aa = $a; $bb = $b; $cc = $c; $dd = $d; // PADDED BINARY FOR NULL STRING, I.E.: "" $binary_md5 = "10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; $binary_md5_words = strlen($binary_md5) / 32; // SPLIT BINARY INTO 16 32-BIT WORDS for($i = 1; $i <= $binary_md5_words; $i++) { $m[] = substr($binary_md5, ($i - 1) * 32, 32); } // GENERATE T-VALUES for($i = 0; $i < 64; $i++) { $T[] = Pad(decbin(floor(4294967296 * abs(sin($i+1)))), 32); } /* // PRINT THE M[K] ARRAY echo "<h1>m[k] Array</h1><br>"; print_r($m); echo "<br><br>"; // PRINT THE T[t] ARRAY echo "<h1>T[t] Array</h1><br>"; print_r($T); echo "<br><br>"; // TEST ANDxy echo "<h1>Test ANDxy</h1><br>"; echo "$m[0]<br>$T[0]<br>"; echo ANDxy($m[0], $T[0]); echo "<br><br>"; // TEST ORxy echo "<h1>Test ORxy</h1><br>"; echo "$m[0]<br>$T[0]<br>"; echo ORxy($m[0], $T[0]); echo "<br><br>"; // TEST ADDxy echo "<h1>Test ADDxy</h1><br>"; echo "$m[0]<br>$T[0]<br>"; echo ADDxy($m[0], $T[0]); echo "<br><br>"; // TEST XORxy echo "<h1>Test XORxy</h1><br>"; echo "$m[0]<br>$T[0]<br>"; echo XORxy($m[0], $T[0]); echo "<br><br>"; // TEST NOTx echo "<h1>Test NOTx</h1><br>"; echo "$m[0]<br>"; echo NOTx($m[0]); echo "<br><br>"; // TEST SHIFTleft echo "<h1>Test SHIFTleft</h1><br>"; echo "$m[0]<br>"; echo SHIFTleft($m[0], 1); echo "<br><br>"; // TEST F echo "<h1>Test F</h1><br>"; echo "X = $m[0]<br>Y = $m[1]<br>Z = $m[2]<br>F = "; echo F($m[0], $m[1], $m[2]); $step1 = ANDxy($m[0], $m[1]); $step2 = ANDxy(NOTx($m[0]), $m[2]); $step3 = ORxy($step1, $step2); echo "<br>F = $step3"; echo "<br><br>"; // TEST H echo "<h1>Test H</h1><br>"; echo "X = $m[0]<br>Y = $m[1]<br>Z = $m[2]<br>F = "; echo H($m[0], $m[1], $m[2]); echo "<br><br>"; */ // ROUND 1 $a = ff($a, $b, $c, $d, $m, 0, 7, $T[0]); $d = ff($d, $a, $b, $c, $m, 1, 12, $T[1]); $c = ff($c, $d, $a, $b, $m, 2, 17, $T[2]); $b = ff($b, $c, $d, $a, $m, 3, 22, $T[3]); $a = ff($a, $b, $c, $d, $m, 4, 7, $T[4]); $d = ff($d, $a, $b, $c, $m, 5, 12, $T[5]); $c = ff($c, $d, $a, $b, $m, 6, 17, $T[6]); $b = ff($b, $c, $d, $a, $m, 7, 22, $T[7]); $a = ff($a, $b, $c, $d, $m, 8, 7, $T[8]); $d = ff($d, $a, $b, $c, $m, 9, 12, $T[9]); $c = ff($c, $d, $a, $b, $m, 10, 17, $T[10]); $b = ff($b, $c, $d, $a, $m, 11, 22, $T[11]); $a = ff($a, $b, $c, $d, $m, 12, 17, $T[12]); $d = ff($d, $a, $b, $c, $m, 13, 12, $T[13]); $c = ff($c, $d, $a, $b, $m, 14, 17, $T[14]); $b = ff($b, $c, $d, $a, $m, 15, 22, $T[15]); // ROUND 2 $a = gg($a, $b, $c, $d, $m, 1, 5, $T[16]); $d = gg($d, $a, $b, $c, $m, 6, 9, $T[17]); $c = gg($c, $d, $a, $b, $m, 11, 14, $T[18]); $b = gg($b, $c, $d, $a, $m, 0, 20, $T[19]); $a = gg($a, $b, $c, $d, $m, 5, 5, $T[20]); $d = gg($d, $a, $b, $c, $m, 10, 9, $T[21]); $c = gg($c, $d, $a, $b, $m, 15, 14, $T[22]); $b = gg($b, $c, $d, $a, $m, 4, 20, $T[23]); $a = gg($a, $b, $c, $d, $m, 9, 5, $T[24]); $d = gg($d, $a, $b, $c, $m, 14, 9, $T[25]); $c = gg($c, $d, $a, $b, $m, 3, 14, $T[26]); $b = gg($b, $c, $d, $a, $m, 8, 20, $T[27]); $a = gg($a, $b, $c, $d, $m, 13, 5, $T[28]); $d = gg($d, $a, $b, $c, $m, 2, 9, $T[29]); $c = gg($c, $d, $a, $b, $m, 7, 14, $T[30]); $b = gg($b, $c, $d, $a, $m, 12, 20, $T[31]); // ROUND 3 $a = hh($a, $b, $c, $d, $m, 5, 4, $T[32]); $d = hh($d, $a, $b, $c, $m, 8, 11, $T[33]); $c = hh($c, $d, $a, $b, $m, 11, 16, $T[34]); $b = hh($b, $c, $d, $a, $m, 14, 23, $T[35]); $a = hh($a, $b, $c, $d, $m, 1, 4, $T[36]); $d = hh($d, $a, $b, $c, $m, 4, 11, $T[37]); $c = hh($c, $d, $a, $b, $m, 7, 16, $T[38]); $b = hh($b, $c, $d, $a, $m, 10, 23, $T[39]); $a = hh($a, $b, $c, $d, $m, 13, 4, $T[40]); $d = hh($d, $a, $b, $c, $m, 0, 11, $T[41]); $c = hh($c, $d, $a, $b, $m, 3, 16, $T[42]); $b = hh($b, $c, $d, $a, $m, 6, 23, $T[43]); $a = hh($a, $b, $c, $d, $m, 9, 4, $T[44]); $d = hh($d, $a, $b, $c, $m, 12, 11, $T[45]); $c = hh($c, $d, $a, $b, $m, 15, 16, $T[46]); $b = hh($b, $c, $d, $a, $m, 2, 23, $T[47]); // ROUND 4 $a = ii($a, $b, $c, $d, $m, 0, 6, $T[48]); $d = ii($d, $a, $b, $c, $m, 7, 10, $T[49]); $c = ii($c, $d, $a, $b, $m, 14, 15, $T[50]); $b = ii($b, $c, $d, $a, $m, 5, 21, $T[51]); $a = ii($a, $b, $c, $d, $m, 12, 6, $T[52]); $d = ii($d, $a, $b, $c, $m, 3, 10, $T[53]); $c = ii($c, $d, $a, $b, $m, 10, 15, $T[54]); $b = ii($b, $c, $d, $a, $m, 1, 21, $T[55]); $a = ii($a, $b, $c, $d, $m, 8, 6, $T[56]); $d = ii($d, $a, $b, $c, $m, 15, 10, $T[57]); $c = ii($c, $d, $a, $b, $m, 6, 15, $T[58]); $b = ii($b, $c, $d, $a, $m, 13, 21, $T[59]); $a = ii($a, $b, $c, $d, $m, 4, 6, $T[60]); $d = ii($d, $a, $b, $c, $m, 11, 10, $T[61]); $c = ii($c, $d, $a, $b, $m, 2, 15, $T[62]); $b = ii($b, $c, $d, $a, $m, 9, 21, $T[63]); $a = ADDxy($a, $aa); $b = ADDxy($b, $bb); $c = ADDxy($c, $cc); $d = ADDxy($d, $dd); // ECHO RESULTS echo "<h1>String</h1><br>"; echo "String: '$string'<br>"; $md5 = md5($string); echo "MD5: $md5<br><br>"; $md5_1 = substr($md5, 0, 8); $md5_2 = substr($md5, 8, 8); $md5_3 = substr($md5, 16, 8); $md5_4 = substr($md5, 24, 8); echo "A = $md5_1<br>B = $md5_2<br>C = $md5_3<br>D = $md5_4<br><br>"; $md5_bin_a = Pad(decbin(hexdec($md5_1)), 32); $md5_bin_b = Pad(decbin(hexdec($md5_2)), 32); $md5_bin_c = Pad(decbin(hexdec($md5_3)), 32); $md5_bin_d = Pad(decbin(hexdec($md5_4)), 32); echo "A = $md5_bin_a<br>B = $md5_bin_b<br>C = $md5_bin_c<br>D = $md5_bin_d<br><br>"; echo "<h1>Results</h1><br>"; echo "A = $a<br>B = $b<br>C = $c<br>D = $d<br><br>"; $a_dec = bindec($a); $b_dec = bindec($b); $c_dec = bindec($c); $d_dec = bindec($d); $a_hex = dechex($a_dec); $b_hex = dechex($b_dec); $c_hex = dechex($c_dec); $d_hex = dechex($d_dec); echo "A = $a_hex<br>B = $b_hex<br>C = $c_hex<br>D = $d_hex<br><br>"; // FUNCTIONS function ff($a, $b, $c, $d, $m, $k, $s, $t) { //a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s) return ADDxy($b, SHIFTleft(ADDxy(ADDxy(ADDxy($a, F($b, $c, $d)), $m[$k]), $t), $s)); } function gg($a, $b, $c, $d, $m, $k, $s, $t) { //a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s) return ADDxy($b, SHIFTleft(ADDxy(ADDxy(ADDxy($a, G($b, $c, $d)), $m[$k]), $t), $s)); } function hh($a, $b, $c, $d, $m, $k, $s, $t) { //a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s) return ADDxy($b, SHIFTleft(ADDxy(ADDxy(ADDxy($a, H($b, $c, $d)), $m[$k]), $t), $s)); } function ii($a, $b, $c, $d, $m, $k, $s, $t) { //a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s) return ADDxy($b, SHIFTleft(ADDxy(ADDxy(ADDxy($a, I($b, $c, $d)), $m[$k]), $t), $s)); } function F($X, $Y, $Z) { //return ($X & $Y) | ((~$X) & $Z); return ORxy(ANDxy($X, $Y), ANDxy(NOTx($X), $Z)); } function G($X, $Y, $Z) { //return ($X & $Z) | ($Y & (~$Z)); return ORxy(ANDxy($X, $Z), ANDxy($Y, NOTx($Z))); } function H($X, $Y, $Z) { //return $X ^ $Y ^ $Z; return XORxy(XORxy($X, $Y), $Z); } function I($X, $Y, $Z) { //return $Y ^ ($X | (~$Z)); return XORxy($Y, ORxy($X, NOTx($Z))); } function Pad($binary, $pad_length) { $pad_length = $pad_length - strlen($binary); for($i = 0; $i < $pad_length; $i++) { $padding .= '0'; } return $padding . $binary; } function mod($val, $div) { $r = $val - (floor($val/$div)*$div); return $r; } function ANDxy($x, $y) { $x_dec = bindec($x); $y_dec = bindec($y); $result = $x_dec & $y_dec; $result = Pad(decbin($result), strlen($x)); return $result; } function ORxy($x, $y) { $x_dec = bindec($x); $y_dec = bindec($y); $result = $x_dec | $y_dec; $result = Pad(decbin($result), strlen($x)); return $result; } function ADDxy($x, $y) { $x_dec = bindec($x); $y_dec = bindec($y); $result = mod($x_dec + $y_dec, pow(2, 32)); $result = Pad(decbin($result), strlen($x)); return $result; } function XORxy($x, $y) { $x_dec = bindec($x); $y_dec = bindec($y); $result = $x_dec ^ $y_dec; $result = Pad(decbin($result), strlen($x)); return $result; } function NOTx($x) { $x_dec = bindec($x); $result = ~$x_dec; $result = Pad(decbin($result), strlen($x)); return $result; } function SHIFTleft($x, $y) { $x_dec = bindec($x); $result = $x_dec << $y; $result = Pad(decbin($result), strlen($x)); return $result; } function SHIFTright($x, $y) { $x_dec = bindec($x); $result = $x_dec >> $y; $result = Pad(decbin($result), strlen($x)); return $result; } ?> Hey all. I am racking my brain trying to figure out the best way to handle a certain process my company needs me to do. First I will give a general description of the issue, then I will get into specifics. Basically I have a file that contains a bunch of data. The data stored in the file is consistant, each entry has X number of elements with a total character size of Y. Element 1 in each entry will always take up the same amount of characters. So if I have 2 elements in each data entry, each 5 characters long, then each data entry is 10 characters. Whcih means to access the 2nd element of the 3rd entry I would grab characters 15-20. I would want to be able to search this data for a number of things. Basically id want to be able to say, "give me all results where element 1 = 'pancakes'. Or where element 2 >8. Or more substaintial searches such as element 1>10 AND element 2<5. Is there a good way to do this? My first line of thought would be to run through the file, grabbing every element that can be searched on. So lets say if elements 2 and 4 can be searched on, and I have 10 entries, I would run through and grab an array holding the values for entry 2 and 4. array( array('index=>0', 'element2'=>10, 'element4'=>12), array('index=>1', 'element2'=>11, 'element4'=>-2), array('index=>2', 'element2'=>0, 'element4'=>7) ) Then, depending on the search, I would reorder the array and search through it. So if I wanted to see if element2 was greater then 8, id reorder by element2 and then search. As if this wasnt difficult enough, the issue would be on complex searches such as 'element1>10 OR (element2=6 AND element3=0)' I suppose i could store the result array of each individual search result and then merge/union/intersect based on the AND/OR. To make things ever CRAZIER, the flat files can have other flat files as children. So if I have element1 in file 1 and element1 in file 2, all of file2 data would be part of the corrisponding data in file1. So, id basically need to be able to "join" files. I have thought of a number of solutions, but im not sure how they will pan out. Ugh. In case your wondering WHY I need to do this. My company runs a lot of data off an old database called filepro which uses flat files with index and map files. Right now we have a few systems which weve "synched" with mysql which runs batch updates between the two databases to keep data consistant. We wont be coming "off" of filepro for a long, long time. But a lot of my php/mysql apps need access to the data on filepro. So, Im trying to find a way to quickly be able to search and pull data from filepro into php. Basically, i want to run search queries on the flat files. Basically id like your input on a number of things: Is this even a reasonable attempt? Is the idea of pulling the searched elements into php to actually run the search, then collecting the correct rows and getting the data directly from them a smart move? Once I have the searchable elements and index, what algorithms are good for actually running the search? I am trying to find a tutorial on how to perform a depth first search. I've seen pseudocodes and sources in other languages, but I just can't implement it in PHP no matter what I try. Can anyone show me how or where I can read up on it or how to do it? Hello Guys,
You might have known about Luhn Algorithm, which is used to get checksum of IMEI of phones, credit cards etc etc. It is a public domain so it is not used for security but to ensure that client has passed the correct numbers etc etc.
Anyway, I am trying to get my hands on this algorithm and I will build a logic based on luhn algo to get the checksum, where I am stuck is how can I get the alternate numbers from a numeric string, for example I have written the following code to get all the numbers one by one into the array.
$imei = "356565451265856"; $lenOfStr= strlen($imei); $myArray = array(); //Get all numbers one by one in array for($i=0; $i < $lenOfStr; $i++){ $myArray[] = substr($imei,$i,1); } // Checking the array foreach($myArray as $seperatedNumbers){ echo $seperatedNumbers; }No the problem is that I want to select every 2nd number from right to left e-g 5,5,2,... or 6,8,6 How can I get it done? This logic may not be so good, there may be more brilliant solutions to write luhn algo, but I want to try myself once... Thanks. Edited by Digitizer, 31 August 2014 - 04:53 PM. Hello, I'm building a blog post website, and now I'm on the search part of it. I have a search field which I instruct the user to type in "keywords" they want to search for. The words they type in there are then to be searched in the "title" and "content" of each post in the "posts" table. Here's an example query of my current setup: SELECT * FROM (`posts`) WHERE MATCH(title,content) AGAINST('+term1* ' IN BOOLEAN MODE); This works fine if I have one or two words in they keywords. If I, however, copy and paste an entire sentence from an existing blog post, no results are found ??? Here's an example of a query where I just copy+pasted a sentence from a blog post: SELECT * FROM (`posts`) WHERE MATCH(title,content) AGAINST('+Hello* +everyone* +my* +name* +is* +Bob* ' IN BOOLEAN MODE); Yet, a search for just "Bob" returns the proper result. WHY? What's a better way to perform this search?! Hallo everybody!
I am looking for some information about creating PHP threaded forum (with MySQL). BB forum is easy - db table with forums, topics and posts, every post has foreign key to topic, topic to forum and it's done. But if I want something like Disqus, how to do this more efficiently? How to collect posts in db with minimum query needed to render any thread?
And what about post rating? How to prevent user from sending more then one rating?
|