Re: [PHP] Comparing data - big file
דניאל דנון wrote: As continuation to my last question, I got another one. a brief summary: I had to process a file that contains 700,000 lines, each line contained some data (lets assume each line was like: name|age|work|lastaccessed) age contains the person's age in time() format, how many seconds has past since he was born. lastaccessed contains also a time(), with his last access. work is some text, also is name. ) so I inserted it (with stacked queries), My question is - lets assume I get a new file, and I need to compare the changes - how would you suggest me to do it? diff. I also don't have the old file. Recreate it? /Per -- Per Jessen, Zürich (18.8°C) -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing strings (revisited)
On Mon, 25 May 2009 02:11:24 -0400, pa...@quillandmouse.com (Paul M Foster) wrote: . This is why I originated a thread along these lines some time ago. I sympathize with your pain, being a C programmer as well. Apparently, PHP plays fast and loose with types when doing == comparisons. And empty() has a really wild way of determining if something is empty (an integer 0 is empty?). Which is why I originally asked if strcmp() was the preferred method of comparison for the list members. In any case, strcmp() does what you want and is the safest way to compare strings, which is what PHP passes around a lot (data comes out of databases as strings, comes back from forms as strings, etc.). And since most of the syntax and library functions of PHP are based on C paradigms, I'm guessing that the PHP strcmp() function is a thin veneer over the actual C function. Thanks, Paul. I have done some more experimenting, and have a better handle on what is going on now, so I don't think I will fall into any unexpected holes (apart from by being careless!) If you enter a value directly (eg. $a[0] = 000a; ) it tries to convert the input to a number, and rejects any input it cannot convert (such as 000a). However if the value is quoted it is stored internally as a string. If the data is stored as elements of a string, and is exploded into an array no attempt is made to interpret them, and they are stored as strings in their original form. They appear to retain this form, but if they are compared with some other value the two values are adjusted until they are of the same type, and then they are compared. The results often seem absurd at first glance. For example 000A 2 10, but A . I think the reason for this is that if the values can be treated as numbers they are compared directly, but otherwise the one with less characters is right padded with spaces, and then there are compared as strings. Thus '000A' '2 ', and 'A ' ''. If the values are compared as strings (using strcmp or SORT_STRING) the results are entirely logical if all the strings are of the same length. If the strings are of different lengths the shorter one is again right padded (probably with spaces) and then the two are compared. These points are illustrated in the following test programs. ?php // Test one data: $a[] = 2000;$a[] = 20e2;$a[] = 2.e3;$a[] = 2.E3; $a[] = 2.000e3; $a[] = 4000/2; $a[] = 4.0e3/2.0; $a[] = '20E2'; $a[] = ;$a[] = ''; $a[] = '000A'; // $a[] = 000A; echo 'pnbsp;/pTest 1. Values entered directlypnbsp;/p'; $i = 0; $n = count ($a); while ($i $n) { echo 'p $a['.$i.']: '.$a[$i].' = '; $j = 0; while ($j $n) { if (($i != $j) ($a[$i] == $a[$j])) { echo $a[$j].', '; } ++$j; } ++$i; echo '/p'; } // Test two data: $ss = 2000;20e2;2.e3;2.E3;2.000e3;4000/2;4.0e3/2.0;20E2;;000A;A000;2;0010; A;10;20;21'; $a = explode (';',$ss); echo 'pnbsp;/pTest 2. Values exploded into arraypnbsp;/p'; $i = 0; $n = count ($a); while ($i $n) { echo 'p $a['.$i.']: '.$a[$i].' = '; $j = 0; while ($j $n) { if (($i != $j) ($a[$i] == $a[$j])) { echo $a[$j].', '; } ++$j; } ++$i; echo '/p'; } // Test 3. $b = $a; sort ($b, SORT_STRING); sort ($a); echo 'pnbsp;/pp Sort normal./p'; $i = 0; while ($i $n) { echo 'p$a['.$i.'] = '.$a[$i].'/p'; ++$i; } echo 'pnbsp;/pp Sort string./p'; $i = 0; while ($i $n) { echo 'p$b['.$i.'] = '.$b[$i].'/p'; ++$i; } ? Results: Test 1. Values entered directly. All values are converted to the simplest form on input. $a[0]: 2000 = 2000, 2000, 2000, 2000, 2000, 2000, 20E2, $a[1]: 2000 = 2000, 2000, 2000, 2000, 2000, 2000, 20E2, $a[2]: 2000 = 2000, 2000, 2000, 2000, 2000, 2000, 20E2, $a[3]: 2000 = 2000, 2000, 2000, 2000, 2000, 2000, 20E2, $a[4]: 2000 = 2000, 2000, 2000, 2000, 2000, 2000, 20E2, $a[5]: 2000 = 2000, 2000, 2000, 2000, 2000, 2000, 20E2, $a[6]: 2000 = 2000, 2000, 2000, 2000, 2000, 2000, 20E2, $a[7]: 20E2 = 2000, 2000, 2000, 2000, 2000, 2000, 2000, $a[8]: = , $a[9]: = , $a[10]: 000A = Test 2. Values exploded into array. Values are preserved as strings until compared. $a[0]: 2000 = 20e2, 2.e3, 2.E3, 2.000e3, 20E2, $a[1]: 20e2 = 2000, 2.e3, 2.E3, 2.000e3, 20E2, $a[2]: 2.e3 = 2000, 20e2, 2.E3, 2.000e3, 20E2, $a[3]: 2.E3 = 2000, 20e2, 2.e3, 2.000e3, 20E2, $a[4]: 2.000e3 = 2000, 20e2,
Re: [PHP] Comparing strings (revisited)
On Mon, May 25, 2009 at 12:46:16PM +1000, Clancy wrote: For some time I have been working on a text based database, in which each entry contains one or more lines of data, with the various fields delimited by semicolons, e.g. A;b;20GM;Restaurant;090508 n;;;Arintji;; a;Federation Square;;; p;9663 9900;;;9663 9901;;i...@arintji.com.au; All was going well but recently I decided to allocate every entry a unique identifier, and, in what with hindsight was clearly misguided enthusiasm, decided that each identifier should be a four digit base 36 number (the 20GM in the first line). This did not cause any problems until yesterday, when I tried to load a name beginning with 'R', and got the first name on the list. When I investigated I found that I was searching the array containing the data using: if ($ident == $data[$i]['group']['ident']) { .. I then found that I was searching for 20E2, but was getting a match on 2000. I tried 'if ((string) $ident == (string) $data[$i]['group']['ident'])', but this still matched. However 'if($ident === ' worked, as did 'if (!strcmp($ident, $data[$i])) {...'. After puzzling about this for a long time, I realised that the comparison process must have been treating the second value as a floating point number, and converting it to integer, or vice versa. (In floating point notation 20E2 = 20*10^^2 = 2000). I had thought that the (string) override meant to treat the actual value as a string, but in this case it must be converting the (assumed) actual value to a string, and then comparing the results. This surprised me considerably as it is clear from the results I achieve in other circumstances that the data is actually stored as a raw string. $data is a variable format array, and when the original data is read each line is exploded into a term of the data array: $data[][] = explode(';',$line[$i]);. If I print the value of the ident (or any other field) it is always shown as the original string, and when I save an updated version of the data, each term of the data array is imploded into a line of the data file in its original format. However if this value were actually converted to a floating point number when it was entered I would have to specify a format before I could write it out again, and as 20E2 is a rather non-standard format it is most unlikely that it would come out as this unaided. Is there any way to specify that each field is always to be treated as a string when I originally explode the input file into the data array?For someone brought up on rigidly defined data types dynamic typing can be very confusing! This is why I originated a thread along these lines some time ago. I sympathize with your pain, being a C programmer as well. Apparently, PHP plays fast and loose with types when doing == comparisons. And empty() has a really wild way of determining if something is empty (an integer 0 is empty?). Which is why I originally asked if strcmp() was the preferred method of comparison for the list members. In any case, strcmp() does what you want and is the safest way to compare strings, which is what PHP passes around a lot (data comes out of databases as strings, comes back from forms as strings, etc.). And since most of the syntax and library functions of PHP are based on C paradigms, I'm guessing that the PHP strcmp() function is a thin veneer over the actual C function. Paul -- Paul M. Foster -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing strings (revisited)
With the initial explode, I may be wrong but I don't think it's possible to force every entry to be string-typed. However, this little snippet could help: $foo = explode(';', $db); foreach($foo as $bar) { $bar = settype($bar, 'string); } which will set each element's type to string, but is hardly a fast or elegant solution, but a solution it is nonetheless. Alternatively, every time you reference a field that ought to be an element but isn't, you can use strval($element), but that's even uglier! On an aside, coming from strict typing to loose typing is certainly an enormous transition, you grow to learn these little things and work around them. The benefits and ease of the loose typing, at least to me, seem to outweigh the overhead handling fringe type cases like these. For a performance nut like myself, though, it certainly drives me insane! On Sun, May 24, 2009 at 10:46 PM, Clancy clanc...@cybec.com.au wrote: For some time I have been working on a text based database, in which each entry contains one or more lines of data, with the various fields delimited by semicolons, e.g. A;b;20GM;Restaurant;090508 n;;;Arintji;; a;Federation Square;;; p;9663 9900;;;9663 9901;;i...@arintji.com.au9901%3b%3bi...@arintji.com.au ; All was going well but recently I decided to allocate every entry a unique identifier, and, in what with hindsight was clearly misguided enthusiasm, decided that each identifier should be a four digit base 36 number (the 20GM in the first line). This did not cause any problems until yesterday, when I tried to load a name beginning with 'R', and got the first name on the list. When I investigated I found that I was searching the array containing the data using: if ($ident == $data[$i]['group']['ident']) { .. I then found that I was searching for 20E2, but was getting a match on 2000. I tried 'if ((string) $ident == (string) $data[$i]['group']['ident'])', but this still matched. However 'if($ident === ' worked, as did 'if (!strcmp($ident, $data[$i])) {...'. After puzzling about this for a long time, I realised that the comparison process must have been treating the second value as a floating point number, and converting it to integer, or vice versa. (In floating point notation 20E2 = 20*10^^2 = 2000). I had thought that the (string) override meant to treat the actual value as a string, but in this case it must be converting the (assumed) actual value to a string, and then comparing the results. This surprised me considerably as it is clear from the results I achieve in other circumstances that the data is actually stored as a raw string. $data is a variable format array, and when the original data is read each line is exploded into a term of the data array: $data[][] = explode(';',$line[$i]);. If I print the value of the ident (or any other field) it is always shown as the original string, and when I save an updated version of the data, each term of the data array is imploded into a line of the data file in its original format. However if this value were actually converted to a floating point number when it was entered I would have to specify a format before I could write it out again, and as 20E2 is a rather non-standard format it is most unlikely that it would come out as this unaided. Is there any way to specify that each field is always to be treated as a string when I originally explode the input file into the data array? For someone brought up on rigidly defined data types dynamic typing can be very confusing! -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing file creating dates...
Ryan S wrote: Hey all, Heres what i am trying to do: When someone sends a message from my site, i take their ip address and make a file with their ip address in a directory called hash-directory, the file looks like this: 169.34.534.243.txt I want to make sure they cant send too many messages because of the potential to spam, so I want to limit them to sending a message every X number of minutes... heres what i have written (its not working for some damn reason) # Start PHP file if(isset($_SERVER['REMOTE_ADDR'])) {$rem_address=$_SERVER['REMOTE_ADDR'];} $directory_with_files=hash-directory/; $threshold = strtotime('-2 minutes'); echo File created on: b.$rem_address ..txt - . date(F d Y H:i:s., filectime($directory_with_files.$rem_address..txt)). .$file_time_details[0]./bbrbr; if (file_exists($directory_with_files.$rem_address..txt)) { if (getdate(filectime($directory_with_files.$rem_address..txt)) $threshold) From the manual This returns a timestamp int strtotime ( string $time [, int $now ] ) This returns an hash array with all the date/time info in it. array getdate ([ int $timestamp ] ) You are trying to compare two things that are completely different. Get rid of the getdate() function. All you need is the filectime() call, it returns a unix timestamp. {echo bPlease wait more than 1 minute before posting./bbr;} else{echo bEnough time has elapsed./bbr;} } # END PHP file Where am I going wrong? Thanks! Ryan -- - The faulty interface lies between the chair and the keyboard. - Creativity is great, but plagiarism is faster! - Smile, everyone loves a moron. :-) Looking for last minute shopping deals? Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing file creating dates...
you may need to use filemtime() and not filectime(); Jim Lucas wrote: Ryan S wrote: Hey all, Heres what i am trying to do: When someone sends a message from my site, i take their ip address and make a file with their ip address in a directory called hash-directory, the file looks like this: 169.34.534.243.txt I want to make sure they cant send too many messages because of the potential to spam, so I want to limit them to sending a message every X number of minutes... heres what i have written (its not working for some damn reason) # Start PHP file if(isset($_SERVER['REMOTE_ADDR'])) {$rem_address=$_SERVER['REMOTE_ADDR'];} $directory_with_files=hash-directory/; $threshold = strtotime('-2 minutes'); echo File created on: b.$rem_address ..txt - . date(F d Y H:i:s., filectime($directory_with_files.$rem_address..txt)). .$file_time_details[0]./bbrbr; if (file_exists($directory_with_files.$rem_address..txt)) { if (getdate(filectime($directory_with_files.$rem_address..txt)) $threshold) From the manual This returns a timestamp int strtotime ( string $time [, int $now ] ) This returns an hash array with all the date/time info in it. array getdate ([ int $timestamp ] ) You are trying to compare two things that are completely different. Get rid of the getdate() function. All you need is the filectime() call, it returns a unix timestamp. {echo bPlease wait more than 1 minute before posting./bbr;} else{echo bEnough time has elapsed./bbr;} } # END PHP file Where am I going wrong? Thanks! Ryan -- - The faulty interface lies between the chair and the keyboard. - Creativity is great, but plagiarism is faster! - Smile, everyone loves a moron. :-) Looking for last minute shopping deals? Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing files
Quoting mathieu leddet [EMAIL PROTECTED]: Hi all, I have a simple question : how can I ensure that 2 files are identical ? How about this ? 8-- function files_identical($path1, $path2) { return (file_get_contents($path1) == file_get_contents($path2)); } 8-- Note that I would like to compare any type of files (text and binary). Thanks for any help, -- Mathieu You could use md5_file for this. Something like: function files_identical($path1, $path2) { return (md5_file($path1) == md5_file($path2)); } -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing files
mathieu leddet wrote: I have a simple question : how can I ensure that 2 files are identical ? How about this ? 8-- function files_identical($path1, $path2) { return (file_get_contents($path1) == file_get_contents($path2)); } 8-- Note that I would like to compare any type of files (text and binary). http://php.net/md5_file -Stut -- http://stut.net/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing files
mathieu leddet wrote: Hi all, I have a simple question : how can I ensure that 2 files are identical ? How about this ? 8-- function files_identical($path1, $path2) { return (file_get_contents($path1) == file_get_contents($path2)); } I would say, use a md5 checksum on both files: function files_identical($path1, $path2) { return (md5(file_get_contents($path1)) === md5(file_get_contents($path2))); } -- Aschwin Wesselius /'What you would like to be done to you, do that to the other'/
RE: [PHP] Comparing files
-Original Message- From: mathieu leddet [mailto:[EMAIL PROTECTED] Sent: 12 March 2008 11:04 To: php-general@lists.php.net Subject: [PHP] Comparing files Hi all, I have a simple question : how can I ensure that 2 files are identical ? How about this ? 8-- function files_identical($path1, $path2) { return (file_get_contents($path1) == file_get_contents($path2)); } 8-- Note that I would like to compare any type of files (text and binary). Thanks for any help, Depending upon the size of the files, I would expect it would be quicker to compare a hash of each file. Edward -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Comparing files
Yes! Thanks a lot, md5_file suits perfectly well my needs. I've read that 'exec'ing the md5 command is faster... I'll see when performance on large files will become an issue. Thanks again, -- Mathieu -Message d'origine- De : Thijs Lensselink [mailto:[EMAIL PROTECTED] Envoyé : Wednesday, March 12, 2008 12:09 PM À : php-general@lists.php.net Objet : Re: [PHP] Comparing files Quoting mathieu leddet [EMAIL PROTECTED]: Hi all, I have a simple question : how can I ensure that 2 files are identical ? How about this ? 8-- function files_identical($path1, $path2) { return (file_get_contents($path1) == file_get_contents($path2)); } 8-- Note that I would like to compare any type of files (text and binary). Thanks for any help, -- Mathieu You could use md5_file for this. Something like: function files_identical($path1, $path2) { return (md5_file($path1) == md5_file($path2)); } -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Comparing files
mathieu leddet wrote: Yes! Thanks a lot, md5_file suits perfectly well my needs. I've read that 'exec'ing the md5 command is faster... I'll see when performance on large files will become an issue. Doing a diff on the files would make absolutely certain - an md5 checksum is not. /Per Jessen, Zürich -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Comparing files
-Original Message- From: Edward Kay [mailto:[EMAIL PROTECTED] Sent: Wednesday, March 12, 2008 7:13 AM To: mathieu leddet; php-general@lists.php.net Subject: RE: [PHP] Comparing files -Original Message- From: mathieu leddet [mailto:[EMAIL PROTECTED] Sent: 12 March 2008 11:04 To: php-general@lists.php.net Subject: [PHP] Comparing files Hi all, I have a simple question : how can I ensure that 2 files are identical ? How about this ? 8-- function files_identical($path1, $path2) { return (file_get_contents($path1) == file_get_contents($path2)); } 8-- Note that I would like to compare any type of files (text and binary). Thanks for any help, Depending upon the size of the files, I would expect it would be quicker to compare a hash of each file. Edward I don't understand how comparing hashes can be faster than comparing contents, except for big files for which you will likely hit the memory limit first and for files who only differ from each other at the very end of them, so the comparison will only be halted then. If the file sizes vary too much, however, a mixed strategy would be the winner; and certainly, you will want to store path names and calculated hashes in a database of some kind to save yourself from hogging the server each time (yeah, CPU and RAM are cheap, but not unlimited resources). Comparing hashes means that a hash must be calculated for files A and B and the related overhead will increase according to the file size (right or wrong?). Comparing the file contents will have an associated overhead for buffering and moving the file contents into memory, and it's also a linear operation (strings are compared byte to byte till there's a difference). So... why not doing the following? 1 - Compare file sizes (this is just a property stored in the file system structures, right?). If sizes are different, the files are different. Otherwise move to step 2. 2 - If the file sizes are smaller than certain size (up to you to find the optimal file size), just compare contents through, say, file_get_contents. Otherwise move to step 3. 3 - Grab some random bytes at the beginning, at the middle and at the end of both files and compare them. If they are different, the files are different. Otherwise move to step 4. 4 - If you reach this point, you are doomed. You have 2 big files that you must compare and they are apparently equal so far. Comparing contents will be over killing if at all possible, so you will want to generate hashes and compare them. Run md5_file on both files (it would be great if you have, say, file A's hash already calculated and stored in a DB or data file) and compare results. It is always up to what kind of files you are dealing with, if the files are often different only at the end of the stream, you may want to skip step 2. But this is what I would generally do. By the way, md5 is a great hashing function, but it is not bullet-proof, collisions may happen (though it's much better than crc32, for example). So, you may also think of how critical is to you to have some false positives (some files that are considered equal by md5_file and they are not) and probably use some diff-like solution instead of md5_file. Anyway, having compared sizes and random bytes (steps 1 through 3), it's very likely that md5_file will catch it if two files are different in just a few bytes. Regards, Rob Andrés Robinet | Lead Developer | BESTPLACE CORPORATION 5100 Bayview Drive 206, Royal Lauderdale Landings, Fort Lauderdale, FL 33308 | TEL 954-607-4207 | FAX 954-337-2695 | Email: [EMAIL PROTECTED] | MSN Chat: [EMAIL PROTECTED] | SKYPE: bestplace | Web: bestplace.biz | Web: seo-diy.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Comparing files
-Original Message- From: Andrés Robinet [mailto:[EMAIL PROTECTED] Sent: 12 March 2008 12:33 To: 'Edward Kay'; 'mathieu leddet'; php-general@lists.php.net Subject: RE: [PHP] Comparing files -Original Message- From: Edward Kay [mailto:[EMAIL PROTECTED] Sent: Wednesday, March 12, 2008 7:13 AM To: mathieu leddet; php-general@lists.php.net Subject: RE: [PHP] Comparing files -Original Message- From: mathieu leddet [mailto:[EMAIL PROTECTED] Sent: 12 March 2008 11:04 To: php-general@lists.php.net Subject: [PHP] Comparing files Hi all, I have a simple question : how can I ensure that 2 files are identical ? How about this ? 8-- function files_identical($path1, $path2) { return (file_get_contents($path1) == file_get_contents($path2)); } 8-- Note that I would like to compare any type of files (text and binary). Thanks for any help, Depending upon the size of the files, I would expect it would be quicker to compare a hash of each file. Edward I don't understand how comparing hashes can be faster than comparing contents, except for big files for which you will likely hit the memory limit first and for files who only differ from each other at the very end of them, so the comparison will only be halted then. If the file sizes vary too much, however, a mixed strategy would be the winner; and certainly, you will want to store path names and calculated hashes in a database of some kind to save yourself from hogging the server each time (yeah, CPU and RAM are cheap, but not unlimited resources). Comparing hashes means that a hash must be calculated for files A and B and the related overhead will increase according to the file size (right or wrong?). Comparing the file contents will have an associated overhead for buffering and moving the file contents into memory, and it's also a linear operation (strings are compared byte to byte till there's a difference). So... why not doing the following? 1 - Compare file sizes (this is just a property stored in the file system structures, right?). If sizes are different, the files are different. Otherwise move to step 2. 2 - If the file sizes are smaller than certain size (up to you to find the optimal file size), just compare contents through, say, file_get_contents. Otherwise move to step 3. 3 - Grab some random bytes at the beginning, at the middle and at the end of both files and compare them. If they are different, the files are different. Otherwise move to step 4. 4 - If you reach this point, you are doomed. You have 2 big files that you must compare and they are apparently equal so far. Comparing contents will be over killing if at all possible, so you will want to generate hashes and compare them. Run md5_file on both files (it would be great if you have, say, file A's hash already calculated and stored in a DB or data file) and compare results. It is always up to what kind of files you are dealing with, if the files are often different only at the end of the stream, you may want to skip step 2. But this is what I would generally do. By the way, md5 is a great hashing function, but it is not bullet-proof, collisions may happen (though it's much better than crc32, for example). So, you may also think of how critical is to you to have some false positives (some files that are considered equal by md5_file and they are not) and probably use some diff-like solution instead of md5_file. Anyway, having compared sizes and random bytes (steps 1 through 3), it's very likely that md5_file will catch it if two files are different in just a few bytes. Agreed. In by first reply, I meant that hashes would likely be quicker/more memory friendly when handling larger files, but this is just a hunch - I haven't benchmarked anything. It was really meant to give the OP other possibilities to look into. Edward -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Comparing files
Quoting Andrés Robinet [EMAIL PROTECTED]: -Original Message- From: Edward Kay [mailto:[EMAIL PROTECTED] Sent: Wednesday, March 12, 2008 7:13 AM To: mathieu leddet; php-general@lists.php.net Subject: RE: [PHP] Comparing files -Original Message- From: mathieu leddet [mailto:[EMAIL PROTECTED] Sent: 12 March 2008 11:04 To: php-general@lists.php.net Subject: [PHP] Comparing files Hi all, I have a simple question : how can I ensure that 2 files are identical ? How about this ? 8-- function files_identical($path1, $path2) { return (file_get_contents($path1) == file_get_contents($path2)); } 8-- Note that I would like to compare any type of files (text and binary). Thanks for any help, Depending upon the size of the files, I would expect it would be quicker to compare a hash of each file. Edward I don't understand how comparing hashes can be faster than comparing contents, except for big files for which you will likely hit the memory limit first and for files who only differ from each other at the very end of them, so the comparison will only be halted then. If the file sizes vary too much, however, a mixed strategy would be the winner; and certainly, you will want to store path names and calculated hashes in a database of some kind to save yourself from hogging the server each time (yeah, CPU and RAM are cheap, but not unlimited resources). I must agree that a mixed solution would be best here. Comparing hashes means that a hash must be calculated for files A and B and the related overhead will increase according to the file size (right or wrong?). Comparing the file contents will have an associated overhead for buffering and moving the file contents into memory, and it's also a linear operation (strings are compared byte to byte till there's a difference). So... why not doing the following? 1 - Compare file sizes (this is just a property stored in the file system structures, right?). If sizes are different, the files are different. Otherwise move to step 2. I like this idea. It's fast and will catch most differences. 2 - If the file sizes are smaller than certain size (up to you to find the optimal file size), just compare contents through, say, file_get_contents. Otherwise move to step 3. 3 - Grab some random bytes at the beginning, at the middle and at the end of both files and compare them. If they are different, the files are different. Otherwise move to step 4. Not sure about this one. Will all the file operations not create to much overhead if you are dealing with large files? 4 - If you reach this point, you are doomed. You have 2 big files that you must compare and they are apparently equal so far. Comparing contents will be over killing if at all possible, so you will want to generate hashes and compare them. Run md5_file on both files (it would be great if you have, say, file A's hash already calculated and stored in a DB or data file) and compare results. It is always up to what kind of files you are dealing with, if the files are often different only at the end of the stream, you may want to skip step 2. But this is what I would generally do. By the way, md5 is a great hashing function, but it is not bullet-proof, collisions may happen (though it's much better than crc32, for example). So, you MD5 is for sure not bullet-proof. You could always switch to sha1_file for a bit more security. may also think of how critical is to you to have some false positives (some files that are considered equal by md5_file and they are not) and probably use some diff-like solution instead of md5_file. Anyway, having compared sizes and random bytes (steps 1 through 3), it's very likely that md5_file will catch it if two files are different in just a few bytes. Regards, Rob Andrés Robinet | Lead Developer | BESTPLACE CORPORATION 5100 Bayview Drive 206, Royal Lauderdale Landings, Fort Lauderdale, FL 33308 | TEL 954-607-4207 | FAX 954-337-2695 | Email: [EMAIL PROTECTED] | MSN Chat: [EMAIL PROTECTED] | SKYPE: bestplace | Web: bestplace.biz | Web: seo-diy.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing string to array
Richard Davey wrote: Hi all, Ok it's 2am, my brain has gone to mush and I am having trouble figuring out an easy way to do this, can anyone shed some light? Take a peek at the following code: // START pre ?php print_r($_POST); $userparam = test['sam'][]; // How to check if $userparam exists in the $_POST array // and get all the values from it? // Obviously this won't work, but you get the idea: if (isset($_POST[$userparam])) { echo 'yeah'; $values = $_POST[$userparam]; } else { echo 'nah'; } ? /pre form method=post input type=checkbox name=test['bob'][] value=redredbr input type=checkbox name=test['bob'][] value=greengreenbr input type=checkbox name=test['bob'][] value=bluebluebr input type=checkbox name=test['sam'][] value=red2red2br input type=checkbox name=test['sam'][] value=green2green2br input type=checkbox name=test['sam'][] value=blue2blue2br input type=submit /form // END From the code above I'm trying to figure out how to tell if the $userparam exists in the $_POST array. PHP automatically expands the form element name into multi-dim arrays within $_POST, so a simple 'isset' as shown in the code above won't play because it's got a totally useless array key passed to it. I need a way to turn the string: test['sam'][] into something I can look into $_POST for. Any ideas? The coffee boost is wearing off, but I want to get this licked tonight :-\ Do you have control over what $userparam looks like? I'm not entirely sure what you're after due to the [] on the end of it, but I'm going to assume you want to know if any of the 'sam' checkboxes were ticked. Maybe the following is a possibility... $userparam = test.sam; // How to check if $userparam exists in the $_POST array // and get all the values from it? $idx = '[\''.implode('\'][\']', explode('.', $userparam)).'\']'; eval('$isset = isset($_POST'.$idx.');'); // Obviously this won't work, but you get the idea: if ($isset) { echo 'yeah'; eval('$values = $_POST'.$idx.';'); } else { echo 'nah'; } Untested, and remember that eval is pure evil. If you can't control $userparam and it has to look like you have it then you're parsing of it is a little more involved, but still fairly simple. What are you actually trying to do? Where will $userparam actually come from? There is almost certainly a better way to do this, but without knowing all the details I'd be peeing in the wind. -Stut -- http://stut.net/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing string to array
Richard Davey wrote: Hi Stut, Tuesday, June 19, 2007, 10:16:02 AM, you wrote: If you can't control $userparam and it has to look like you have it then you're parsing of it is a little more involved, but still fairly simple. What are you actually trying to do? Where will $userparam actually come from? There is almost certainly a better way to do this, but without knowing all the details I'd be peeing in the wind. Thank you for your code so far. Here is a more detailed explanation of what I'm trying to do: The designers here can create forms with whatever form elements they like on them. They can name the form elements with any valid name. As you know sometimes it is useful to give the form elements names which will convert them into arrays in PHP, i.e.: input type=checkbox name=test[color][] value=red2red2br input type=checkbox name=test[color][] value=green2green2br input type=checkbox name=test[color][] value=blue2blue2br So $_POST['test']['color'] would contain an array of all the checked values. So far so good. The problem comes in that I don't know what the form elements will be named, but I still need to check to see if they exist within the $_POST array. So knowing that $input_name = 'test[color][]' I then need to see if $_POST['test']['color'] exists and get the value if it does. To make matters worse it's perfectly legal to have a form element named like: input type=checkbox name=test['bob']['jazz'][] value=redred input type=checkbox name=test['bob']['jazz'][] value=greengreen input type=checkbox name=test['bob']['jazz'][] value=blueblue Which when bought back into PHP will come out as: array(1) { [test]= array(2) { ['bob']= array(1) { ['jazz']= array(3) { [0]= string(3) red [1]= string(5) green [2]= string(4) blue } } Does that make it any clearer? I have been playing with the RecursiveIteratorIterator this morning in an attempt to solve it, but the results from that are less than useless :( I'm happy to try and explore the RAW post value instead if that would be easier. I just figured there must be an easier way? Here is the complete page you can test with: START pre ?php var_dump($_POST); $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($_POST)); while($iterator-valid()) { echo $iterator-key() . ' -- ' . $iterator-current(); echo \n; $iterator-next(); } $userparam = test['bob'][jazz][]; // How to determine if $userparam exists in $_POST ? /pre form method=post input type=checkbox name=test['bob'][jazz][] value=redredbr input type=checkbox name=test['bob'][jazz][] value=greengreenbr input type=checkbox name=test['bob'][jazz][] value=bluebluebr input type=checkbox name=test[sam][] value=red2red2br input type=checkbox name=test[sam][] value=green2green2br input type=checkbox name=test[sam][] value=blue2blue2br input type=submit /form END Remember the whole crux of this problem is that I have no control over what the form name will be. It will be *valid*, but that is all. They could nest the resulting array as deep in $_POST as they like. If you have no control over what the fields in the form will be, what are you doing with the data? Surely if you're writing logic that requires you to know what the fields are called, you need to have control over it. On the other hand, if you're just squidging the data somewhere can't you just iterate over the contents of $_POST? I understand now that you're not in control of the form. What are you doing with the data that's submitted? -Stut -- http://stut.net/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing string to array
Richard Davey wrote: Hi Stut, Tuesday, June 19, 2007, 12:09:12 PM, you wrote: If you have no control over what the fields in the form will be, what are you doing with the data? Surely if you're writing logic that requires you to know what the fields are called, you need to have control over it. Here, this should help expand it further: $icecream = $form-addSelectList('list', icecream[flavor][], 1, true, 'xml', 'icecream.xml', '//flavour'); The above code will add a select list into the current form (the contents of which come from the icecream.xml file, using the xpath query at the end, but this isn't relevant to the problem) The 2nd parameter is the form name. In this instance the flavors from the multi-select list will come into $_POST in: icecream[flavor] When the form is submitted I take all of these form elements, and if they exist in the filtered $_POST array, I re-populate them on error. If the input name is just 'icecream' then you can do a simple: if (isset($_POST[$input_name])) .. and get the submitted value back. If the input name is 'icecream[flavor][]' the above will no longer work. The problem is finding a way to expand the input name (which is a string) into a format that $_POST can be searched for. Or do the reverse, iterate through $_POST to find a match for the input name and get that value. Try this overly commented snippet on for size... http://dev.stut.net/php/davey.php -Stut -- http://stut.net/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing string to array
Richard Davey wrote: Hi Stut, Tuesday, June 19, 2007, 1:16:54 PM, you wrote: The problem is finding a way to expand the input name (which is a string) into a format that $_POST can be searched for. Or do the reverse, iterate through $_POST to find a match for the input name and get that value. Try this overly commented snippet on for size... http://dev.stut.net/php/davey.php Very nice, thank you. I was hoping there would be a way to do it without resorting to eval(), but if even you can't figure out how, I'm not going to waste any more time trying to either :) You probably could by breaking it into each part and then using a loop to descend to the right place, but I don't think that's going to be any better than using eval. I'm assuming the source for $target is trusted. If not then you'll want to sanitise it further by removing anything that's not a-z, 0-9 and [] just to ensure no dodgy code can be inserted. I loved this part: // The target - offensive American spelling! :) Cheers, No probs. -Stut -- http://stut.net/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing string to array
Richard Davey wrote: Hi Stut, Tuesday, June 19, 2007, 1:49:53 PM, you wrote: Very nice, thank you. I was hoping there would be a way to do it without resorting to eval(), but if even you can't figure out how, I'm not going to waste any more time trying to either :) You probably could by breaking it into each part and then using a loop to descend to the right place, but I don't think that's going to be any better than using eval. I was wondering about doing something like this: Recurse through $_POST, grabbing all of the keys, and then building a string from them, something like: icecream_batch2_flavours and then storing the value of 'flavours' in a new array with the above as the key. Then I could manipulate the form input name: name=icecream[batch2][flavours][] or name=icecream['batch2']['flavours'][] To resemble the above key relatively simply. Not quite what I was thinking of. More like this: http://dev.stut.net/php/davey2.php -Stut -- http://stut.net/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing string to array
Richard Davey wrote: Hi all, Ok it's 2am, my brain has gone to mush and I am having trouble figuring out an easy way to do this, can anyone shed some light? Take a peek at the following code: // START pre ?php print_r($_POST); $userparam = test['sam'][]; // How to check if $userparam exists in the $_POST array // and get all the values from it? // Obviously this won't work, but you get the idea: if (isset($_POST[$userparam])) { echo 'yeah'; $values = $_POST[$userparam]; } else { echo 'nah'; } ? /pre form method=post input type=checkbox name=test['bob'][] value=redredbr input type=checkbox name=test['bob'][] value=greengreenbr input type=checkbox name=test['bob'][] value=bluebluebr input type=checkbox name=test['sam'][] value=red2red2br input type=checkbox name=test['sam'][] value=green2green2br input type=checkbox name=test['sam'][] value=blue2blue2br DON'T USE SINGLE QUOTES IN YOUR NAME= ATTRIBUTE input type=checkbox name=test[bob][red] value=redredbr input type=checkbox name=test[bob][green] value=greengreenbr input type=checkbox name=test[bob][blue] value=bluebluebr input type=checkbox name=test[sam][red] value=redredbr input type=checkbox name=test[sam][green] value=greengreenbr input type=checkbox name=test[sam][blue] value=bluebluebr Now print_r() should show this. Array ( [test] = Array ( ['bob'] = Array -- notice the single quotes?? they are in your actual value ( [red] = red [green] = green [blue] = blue ) [sam] = Array ( [red] = red [green] = green [blue] = blue ) ) ) input type=submit /form // END From the code above I'm trying to figure out how to tell if the $userparam exists in the $_POST array. PHP automatically expands the form element name into multi-dim arrays within $_POST, so a simple 'isset' as shown in the code above won't play because it's got a totally useless array key passed to it. I need a way to turn the string: test['sam'][] into something I can look into $_POST for. Any ideas? The coffee boost is wearing off, but I want to get this licked tonight :-\ Cheers, Rich -- Jim Lucas Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them. Twelfth Night, Act II, Scene V by William Shakespeare -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing string to array
Richard Davey wrote: Hi Jim, Tuesday, June 19, 2007, 5:06:47 PM, you wrote: DON'T USE SINGLE QUOTES IN YOUR NAME= ATTRIBUTE Hate to piss on your bonfire but a single quote is a perfectly valid (if somewhat stupid choice of) character for inclusion in an array key. Cheers, Rich in this case, it isn't a valid char. Look at his output, you will see that the single quotes are being included in the actual value of the submitted array. So, in this case, they will mess with his comparison. you'll be comparing 'bob' not bob Look at the output a little closer... -- Jim Lucas Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them. Twelfth Night, Act II, Scene V by William Shakespeare -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing string to array
Richard Davey wrote: Hi Jim, Tuesday, June 19, 2007, 5:06:47 PM, you wrote: DON'T USE SINGLE QUOTES IN YOUR NAME= ATTRIBUTE Hate to piss on your bonfire but a single quote is a perfectly valid (if somewhat stupid choice of) character for inclusion in an array key. Cheers, Rich if you use var_dump() instead of print_r() you will see what I am talking about. -- Jim Lucas Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them. Twelfth Night, Act II, Scene V by William Shakespeare -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing string to array
Richard Davey wrote: Hi Jim, Tuesday, June 19, 2007, 5:06:47 PM, you wrote: DON'T USE SINGLE QUOTES IN YOUR NAME= ATTRIBUTE where in this sentence did I say that it was invalid? just told you not to use them, because it is going to mess with your output Hate to piss on your bonfire but a single quote is a perfectly valid (if somewhat stupid choice of) character for inclusion in an array key. Cheers, Rich -- Jim Lucas Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them. Twelfth Night, Act II, Scene V by William Shakespeare -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing string to array
Jim Lucas wrote: Richard Davey wrote: Hi Jim, Tuesday, June 19, 2007, 5:06:47 PM, you wrote: DON'T USE SINGLE QUOTES IN YOUR NAME= ATTRIBUTE Hate to piss on your bonfire but a single quote is a perfectly valid (if somewhat stupid choice of) character for inclusion in an array key. Cheers, Rich in this case, it isn't a valid char. Look at his output, you will see that the single quotes are being included in the actual value of the submitted array. So, in this case, they will mess with his comparison. you'll be comparing 'bob' not bob Look at the output a little closer... I'm not sure who's output you are referring to, but while you're making sense as a comment to a competely different question, it's not relevant to this question. -Stut -- http://stut.net/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing string to array
Stut wrote: Jim Lucas wrote: Richard Davey wrote: Hi Jim, Tuesday, June 19, 2007, 5:06:47 PM, you wrote: DON'T USE SINGLE QUOTES IN YOUR NAME= ATTRIBUTE Hate to piss on your bonfire but a single quote is a perfectly valid (if somewhat stupid choice of) character for inclusion in an array key. Cheers, Rich in this case, it isn't a valid char. Look at his output, you will see that the single quotes are being included in the actual value of the submitted array. So, in this case, they will mess with his comparison. you'll be comparing 'bob' not bob Look at the output a little closer... I'm not sure who's output you are referring to, but while you're making sense as a comment to a competely different question, it's not relevant to this question. -Stut What do you mean? This is the op's output Array ( [test] = Array ( ['bob'] = Array ( [0] = red [1] = green [2] = blue ) ) ) Do you see the single quotes in the array hey at the second level?? They should not be there. it will mess with things. but, for the op here is what I think you might be looking for. pre ?php $user = sam; if ( isset($_POST['test'][$user]) count($_POST['test'][$user]) 0 ) { echo yeah\n; echo join(':', $_POST['test'][$user]); } else { echo 'nah'; } ? /pre form method=post input type=checkbox name=test[bob][red] value=redredbr input type=checkbox name=test[bob][green] value=greengreenbr input type=checkbox name=test[bob][blue] value=bluebluebr input type=checkbox name=test[sam][red] value=redredbr input type=checkbox name=test[sam][green] value=greengreenbr input type=checkbox name=test[sam][blue] value=bluebluebr input type=submit /form -- Jim Lucas Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them. Twelfth Night, Act II, Scene V by William Shakespeare -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing string to array
Jim Lucas wrote: $userparam = test['sam'][]; then what you are saying it that this HAS to be your search string? -- Jim Lucas Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them. Twelfth Night, Act II, Scene V by William Shakespeare -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing string to array
Jim Lucas wrote: Stut wrote: Jim Lucas wrote: Richard Davey wrote: Hi Jim, Tuesday, June 19, 2007, 5:06:47 PM, you wrote: DON'T USE SINGLE QUOTES IN YOUR NAME= ATTRIBUTE Hate to piss on your bonfire but a single quote is a perfectly valid (if somewhat stupid choice of) character for inclusion in an array key. Cheers, Rich in this case, it isn't a valid char. Look at his output, you will see that the single quotes are being included in the actual value of the submitted array. So, in this case, they will mess with his comparison. you'll be comparing 'bob' not bob Look at the output a little closer... I'm not sure who's output you are referring to, but while you're making sense as a comment to a competely different question, it's not relevant to this question. -Stut What do you mean? I thought I was pretty clear. This is the op's output Array ( [test] = Array ( ['bob'] = Array ( [0] = red [1] = green [2] = blue ) ) ) Do you see the single quotes in the array hey at the second level?? I do indeed. They should not be there. Why not? They're in the form so they're in the post data. Seems reasonable to me. it will mess with things. Only if you let it. Stand up to the quotes!! Fight for your rights!! but, for the op here is what I think you might be looking for. pre ?php $user = sam; if ( isset($_POST['test'][$user]) count($_POST['test'][$user]) 0 ) { echo yeah\n; echo join(':', $_POST['test'][$user]); } else { echo 'nah'; } ? /pre form method=post input type=checkbox name=test[bob][red] value=redredbr input type=checkbox name=test[bob][green] value=greengreenbr input type=checkbox name=test[bob][blue] value=bluebluebr input type=checkbox name=test[sam][red] value=redredbr input type=checkbox name=test[sam][green] value=greengreenbr input type=checkbox name=test[sam][blue] value=bluebluebr input type=submit /form That's so far off the mark it's just not funny. As Richard has suggested, read the full thread otherwise you're never going to understand what the actual problem was. -Stut -- http://stut.net/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing string to array
Richard Davey wrote: Hi Jim, Tuesday, June 19, 2007, 5:47:29 PM, you wrote: Jim Lucas wrote: $userparam = test['sam'][]; then what you are saying it that this HAS to be your search string? Heck no, it doesn't *have* to be. Feel free to remove the quotes from it and then attempt my original question again. It's still not as simple as an isset() or count() call. (but boy I wish it was!) Cheers, Rich well, here lets break it down. You need to know that for a given use, if they have any values set in the POST? Correct? What exactly are you looking to find. -- Jim Lucas Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them. Twelfth Night, Act II, Scene V by William Shakespeare -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing string to array
Richard Davey wrote: Hi Jim, Tuesday, June 19, 2007, 5:47:29 PM, you wrote: Jim Lucas wrote: $userparam = test['sam'][]; then what you are saying it that this HAS to be your search string? Heck no, it doesn't *have* to be. Feel free to remove the quotes from it and then attempt my original question again. It's still not as simple as an isset() or count() call. (but boy I wish it was!) Cheers, Rich let me try this again. in the submitted $_POST array, you are looking for a key (test) that contains a given $username that may or may not have any values set? Correct? -- Jim Lucas Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them. Twelfth Night, Act II, Scene V by William Shakespeare -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing string to array
Jim Lucas wrote: Richard Davey wrote: Hi Jim, Tuesday, June 19, 2007, 5:47:29 PM, you wrote: Jim Lucas wrote: $userparam = test['sam'][]; then what you are saying it that this HAS to be your search string? Heck no, it doesn't *have* to be. Feel free to remove the quotes from it and then attempt my original question again. It's still not as simple as an isset() or count() call. (but boy I wish it was!) Cheers, Rich let me try this again. in the submitted $_POST array, you are looking for a key (test) that contains a given $username that may or may not have any values set? Correct? Seriously, read the rest of the damn thread before trying again. As an example of how far off you are... $username has never appeared in this thread until you just said it. -Stut -- http://stut.net/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing string to array
Stut wrote: Jim Lucas wrote: Richard Davey wrote: Hi Jim, Tuesday, June 19, 2007, 5:47:29 PM, you wrote: Jim Lucas wrote: $userparam = test['sam'][]; then what you are saying it that this HAS to be your search string? Heck no, it doesn't *have* to be. Feel free to remove the quotes from it and then attempt my original question again. It's still not as simple as an isset() or count() call. (but boy I wish it was!) Cheers, Rich let me try this again. in the submitted $_POST array, you are looking for a key (test) that contains a given $username that may or may not have any values set? Correct? Seriously, read the rest of the damn thread before trying again. As an example of how far off you are... $username has never appeared in this thread until you just said it. -Stut You're not getting my point. Never mind. Maybe the op understands better. -- Jim Lucas Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them. Twelfth Night, Act II, Scene V by William Shakespeare -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing string to array
Richard Davey wrote: Hi all, Ok it's 2am, my brain has gone to mush and I am having trouble figuring out an easy way to do this, can anyone shed some light? Take a peek at the following code: // START pre ?php print_r($_POST); $userparam = test['sam'][]; // How to check if $userparam exists in the $_POST array // and get all the values from it? // Obviously this won't work, but you get the idea: if (isset($_POST[$userparam])) { echo 'yeah'; $values = $_POST[$userparam]; } else { echo 'nah'; } ? /pre form method=post input type=checkbox name=test['bob'][] value=redredbr input type=checkbox name=test['bob'][] value=greengreenbr input type=checkbox name=test['bob'][] value=bluebluebr input type=checkbox name=test['sam'][] value=red2red2br input type=checkbox name=test['sam'][] value=green2green2br input type=checkbox name=test['sam'][] value=blue2blue2br input type=submit /form // END From the code above I'm trying to figure out how to tell if the $userparam exists in the $_POST array. PHP automatically expands the form element name into multi-dim arrays within $_POST, so a simple 'isset' as shown in the code above won't play because it's got a totally useless array key passed to it. I need a way to turn the string: test['sam'][] into something I can look into $_POST for. Any ideas? The coffee boost is wearing off, but I want to get this licked tonight :-\ Cheers, Rich taking a step back and looking a little closer at the problem. I have come up with this Which does not require eval() Maybe this will work for the OP pre ?php $param = 'test[sam][colors][]'; function find_within_array($string, $source) { $data = array(); $tmp = $source; if ( preg_match_all('/(\[?([\w]+)\]?)/', $string, $matches, PREG_SET_ORDER) ) { if ( count($matches) 1 ) { for ( $i = 0; $icount($matches); $i++ ) { if ( isset($tmp[$matches[$i][2]]) ) { if ( is_array($tmp[$matches[$i][2]]) ) { foreach ($tmp[$matches[$i][2]] AS $value ) { if ( is_string($value) ) { $data[] = $value; } } } $tmp = $tmp[$matches[$i][2]]; } } return $data; } } return array(); } $results = find_within_array($param, $_POST); if ( count($results) 0 ) { echo yeah\n; echo join(':', $results); } else { echo 'nah'; } ? /pre form method=post input type=checkbox name=test[bob][colors][] value=redredbr input type=checkbox name=test[bob][colors][] value=greengreenbr input type=checkbox name=test[bob][colors][] value=bluebluebr input type=checkbox name=test[sam][colors][] value=redredbr input type=checkbox name=test[sam][colors][] value=greengreenbr input type=checkbox name=test[sam][colors][] value=bluebluebr input type=submit /form -- Jim Lucas Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them. Twelfth Night, Act II, Scene V by William Shakespeare -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing string to array
On 19/06/07, Richard Davey [EMAIL PROTECTED] wrote: $userparam = test['sam'][]; // How to check if $userparam exists in the $_POST array // and get all the values from it? full_key_exists(test['sam'][], $_POST) // returns true if key is set full_find_key(test['sam'][], $_POST) // returns value of key or undef. function full_key_exists ($key, $array) { preg_match_all('/[^][]+/', $key, $branch); if (!sizeof($branch[0])) false; foreach ($branch[0] as $index) { if (!(is_array($array) isset($array[$index]))) return false; $array = $array[$index]; } return true; } function full_find_key ($key, $array) { preg_match_all('/[^][]+/', $key, $branch); if (!sizeof($branch[0])) return; foreach ($branch[0] as $index) { if (!(is_array($array) isset($array[$index]))) return; $array = $array[$index]; } return $array; } -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing string to array
Perhaps you're looking for in_array()? On Monday 18 June 2007, Richard Davey wrote: Hi all, Ok it's 2am, my brain has gone to mush and I am having trouble figuring out an easy way to do this, can anyone shed some light? Take a peek at the following code: // START pre ?php print_r($_POST); $userparam = test['sam'][]; // How to check if $userparam exists in the $_POST array // and get all the values from it? // Obviously this won't work, but you get the idea: if (isset($_POST[$userparam])) { echo 'yeah'; $values = $_POST[$userparam]; } else { echo 'nah'; } ? /pre form method=post input type=checkbox name=test['bob'][] value=redredbr input type=checkbox name=test['bob'][] value=greengreenbr input type=checkbox name=test['bob'][] value=bluebluebr input type=checkbox name=test['sam'][] value=red2red2br input type=checkbox name=test['sam'][] value=green2green2br input type=checkbox name=test['sam'][] value=blue2blue2br input type=submit /form // END From the code above I'm trying to figure out how to tell if the $userparam exists in the $_POST array. PHP automatically expands the form element name into multi-dim arrays within $_POST, so a simple 'isset' as shown in the code above won't play because it's got a totally useless array key passed to it. I need a way to turn the string: test['sam'][] into something I can look into $_POST for. Any ideas? The coffee boost is wearing off, but I want to get this licked tonight :-\ Cheers, Rich -- Zend Certified Engineer http://www.corephp.co.uk Never trust a computer you can't throw out of a window -- Larry Garfield AIM: LOLG42 [EMAIL PROTECTED] ICQ: 6817012 If nature has made any one thing less susceptible than all others of exclusive property, it is the action of the thinking power called an idea, which an individual may exclusively possess as long as he keeps it to himself; but the moment it is divulged, it forces itself into the possession of every one, and the receiver cannot dispossess himself of it. -- Thomas Jefferson -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing strings... need advice. :)
On Mon, 28 Aug 2006 19:39:49 -0400, Robert Cummings wrote: On Mon, 2006-08-28 at 16:50 +0200, Ivo F.A.C. Fokkema wrote: On Mon, 28 Aug 2006 09:47:02 +0100, Stut wrote: Micky Hulse wrote: I am looking for the most secure/efficient way to compare these two strings: /folder1/folder2/folder3/folder4/ /folder1/folder2/folder3/folder4/file.php Basically I am trying to setup as many security features as possible for a simplistic (home-grown/hand-coded) CMS... This appears to work: $haystack = '/folder1/folder2/folder3/folder4/someFileName.php'; $needle = '/folder1/folder2/folder3/folder4/'; if(substr_count($haystack, $needle) === 1) echo yea; Before making changes to someFileName.php I want to make sure it is within the allowed path ($needle). First of all make sure you are sending both strings through realpath (http://php.net/realpath) to remove any symbolic links and relative references. Then you can compare the two strings. The way you're doing it will work but it's probably not very efficient. This is what I use... $valid = (strcmp($needle, substr($haystack, 0, strlen($needle))) == 0); Personally, this seems simpler to me: $valid = (dirname($haystack) == $needle); But the way the above folders are presented, it should become $valid = (dirname($haystack) == rtrim($needle, '/')); less simple already... Possibly, this is not the best solution for some reason I don't know. If so, I would like to know :) The above technique doesn't allow for sub-directories. It only allows for files within the needle directory. Ah, thanks. Misunderstood the question, then. Thought just checking if it's a file in that directory was what's needed. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing strings... need advice. :)
Ivo F.A.C. Fokkema wrote: Ah, thanks. Misunderstood the question, then. Thought just checking if it's a file in that directory was what's needed. You were right. :) I did not plan on looking-in anything other than one or two hard-coded folder locations. But, it is good to know the details. ;) Thanks again for the help... Time for me to hit the hay. I have een geeking-out for way too long today. Cheers, Micky -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing strings... need advice. :)
Micky Hulse wrote: I am looking for the most secure/efficient way to compare these two strings: /folder1/folder2/folder3/folder4/ /folder1/folder2/folder3/folder4/file.php Basically I am trying to setup as many security features as possible for a simplistic (home-grown/hand-coded) CMS... This appears to work: $haystack = '/folder1/folder2/folder3/folder4/someFileName.php'; $needle = '/folder1/folder2/folder3/folder4/'; if(substr_count($haystack, $needle) === 1) echo yea; Before making changes to someFileName.php I want to make sure it is within the allowed path ($needle). First of all make sure you are sending both strings through realpath (http://php.net/realpath) to remove any symbolic links and relative references. Then you can compare the two strings. The way you're doing it will work but it's probably not very efficient. This is what I use... $valid = (strcmp($needle, substr($haystack, 0, strlen($needle))) == 0); -Stut -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing strings... need advice. :)
Stut wrote: First of all make sure you are sending both strings through realpath (http://php.net/realpath) to remove any symbolic links and relative references. Then you can compare the two strings. The way you're doing it will work but it's probably not very efficient. This is what I use... $valid = (strcmp($needle, substr($haystack, 0, strlen($needle))) == 0); Awsome! Thanks for the info. Reading-up on realpath right now. I appreciate the tips/example code. :) Have a great day/night. Cheers, Micky -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing strings... need advice. :)
Micky Hulse wrote: Hi, I am looking for the most secure/efficient way to compare these two strings: /folder1/folder2/folder3/folder4/ /folder1/folder2/folder3/folder4/file.php Basically I am trying to setup as many security features as possible for a simplistic (home-grown/hand-coded) CMS... This appears to work: $haystack = '/folder1/folder2/folder3/folder4/someFileName.php'; $needle = '/folder1/folder2/folder3/folder4/'; if(substr_count($haystack, $needle) === 1) echo yea; Before making changes to someFileName.php I want to make sure it is within the allowed path ($needle). I would appreciate any advice. Even RTFM is cool. :D Using your technique I would try an attack like: '/etc/passwd;/folder1/folder2/folder3/folder4/' or '/folder1/folder2/folder3/folder4/../../../../etc/passwd' or some other variant depending on how you then use the file. I'm a big fan of lists of allowed files, typically I use aliases too. $allow_files = array('page' = '/folder/.../filename.php'). This list can be automatically generated and used by mod_rewrite to boost speed. By using a fixed list of files like this it's impossible to be attacked on your filename. Assuming you don't want to go that strong and want to allow your users to set the filename you have to try and lock down the path. By not allowing them to change the path you can hold them in the directory you set. Check for any / characters and reject or strip them out. Use '/folder1/folder2/.../'.$file. It's vital if you do this that you don't allow any way to upload files in to the directory you execute from. If you want to allow them to set the path or part of the path then the check gets far more complicated. You have to catch .. and // patterns, ensuring that you don't combine to form a // and catch cases like '.\./'. If you need to have multiple directories I would strongly suggest using dynamically generated fixed lists. David -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing strings... need advice. :)
On Mon, 28 Aug 2006 09:47:02 +0100, Stut wrote: Micky Hulse wrote: I am looking for the most secure/efficient way to compare these two strings: /folder1/folder2/folder3/folder4/ /folder1/folder2/folder3/folder4/file.php Basically I am trying to setup as many security features as possible for a simplistic (home-grown/hand-coded) CMS... This appears to work: $haystack = '/folder1/folder2/folder3/folder4/someFileName.php'; $needle = '/folder1/folder2/folder3/folder4/'; if(substr_count($haystack, $needle) === 1) echo yea; Before making changes to someFileName.php I want to make sure it is within the allowed path ($needle). First of all make sure you are sending both strings through realpath (http://php.net/realpath) to remove any symbolic links and relative references. Then you can compare the two strings. The way you're doing it will work but it's probably not very efficient. This is what I use... $valid = (strcmp($needle, substr($haystack, 0, strlen($needle))) == 0); Personally, this seems simpler to me: $valid = (dirname($haystack) == $needle); But the way the above folders are presented, it should become $valid = (dirname($haystack) == rtrim($needle, '/')); less simple already... Possibly, this is not the best solution for some reason I don't know. If so, I would like to know :) Ivo -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing strings... need advice. :)
On Mon, 2006-08-28 at 09:47 +0100, Stut wrote: Micky Hulse wrote: I am looking for the most secure/efficient way to compare these two strings: /folder1/folder2/folder3/folder4/ /folder1/folder2/folder3/folder4/file.php Basically I am trying to setup as many security features as possible for a simplistic (home-grown/hand-coded) CMS... This appears to work: $haystack = '/folder1/folder2/folder3/folder4/someFileName.php'; $needle = '/folder1/folder2/folder3/folder4/'; if(substr_count($haystack, $needle) === 1) echo yea; Before making changes to someFileName.php I want to make sure it is within the allowed path ($needle). First of all make sure you are sending both strings through realpath (http://php.net/realpath) to remove any symbolic links and relative references. Then you can compare the two strings. The way you're doing it will work but it's probably not very efficient. This is what I use... $valid = (strcmp($needle, substr($haystack, 0, strlen($needle))) == 0); ?php function isAllowedPath( $needle, $haystack ) { $needle = realpath( $needle ).'/'; $haystack = realpath( $haystack ); return (strpos( $haystack, $needle ) === 0); } ? It is VERY important that you append the trailing slash onto the needle path returned by realpath otherwise it will match more than you expect. Stut didn't point that out so I thought I'd make sure you caught it. Also I'm not sure why Stut used 3 function calls when one suffices :) Cheers, Rob. -- .. | InterJinn Application Framework - http://www.interjinn.com | :: | An application and templating framework for PHP. Boasting | | a powerful, scalable system for accessing system services | | such as forms, properties, sessions, and caches. InterJinn | | also provides an extremely flexible architecture for | | creating re-usable components quickly and easily. | `' -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing strings... need advice. :)
Wow, thanks for all the great information folks (Stut, Ivo, Rob, and David.) I really appreciate all of the top-notch advice and expert information. :D Looks like I have a lot to think about... Currently, I hard-code the paths to the folders that house the files I want my CMS to edit (via a config file.) The script then iterates through the directory and adds all files of a specific type to a dropdown menu. The user can then choose one of the files to edit and load that file into a textarea... After changes are made, the content/code gets saved back to the same file/location. I do have an uploads folder, but it is in a different location on the server. I do not allow the user to create new files (I would have to do that manually)... it is a /very/ basic CMS. Anyway, looks like I have some great info to work with. Thanks again everyone for sharing your expertise. Much appreciated all. Have an excellent day. Cheers, Micky -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing strings... need advice. :)
On Mon, 2006-08-28 at 16:50 +0200, Ivo F.A.C. Fokkema wrote: On Mon, 28 Aug 2006 09:47:02 +0100, Stut wrote: Micky Hulse wrote: I am looking for the most secure/efficient way to compare these two strings: /folder1/folder2/folder3/folder4/ /folder1/folder2/folder3/folder4/file.php Basically I am trying to setup as many security features as possible for a simplistic (home-grown/hand-coded) CMS... This appears to work: $haystack = '/folder1/folder2/folder3/folder4/someFileName.php'; $needle = '/folder1/folder2/folder3/folder4/'; if(substr_count($haystack, $needle) === 1) echo yea; Before making changes to someFileName.php I want to make sure it is within the allowed path ($needle). First of all make sure you are sending both strings through realpath (http://php.net/realpath) to remove any symbolic links and relative references. Then you can compare the two strings. The way you're doing it will work but it's probably not very efficient. This is what I use... $valid = (strcmp($needle, substr($haystack, 0, strlen($needle))) == 0); Personally, this seems simpler to me: $valid = (dirname($haystack) == $needle); But the way the above folders are presented, it should become $valid = (dirname($haystack) == rtrim($needle, '/')); less simple already... Possibly, this is not the best solution for some reason I don't know. If so, I would like to know :) The above technique doesn't allow for sub-directories. It only allows for files within the needle directory. Cheers, Rob. -- .. | InterJinn Application Framework - http://www.interjinn.com | :: | An application and templating framework for PHP. Boasting | | a powerful, scalable system for accessing system services | | such as forms, properties, sessions, and caches. InterJinn | | also provides an extremely flexible architecture for | | creating re-usable components quickly and easily. | `' -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing strings... need advice. :)
On Mon, 2006-08-28 at 16:28 -0700, Micky Hulse wrote: Wow, thanks for all the great information folks (Stut, Ivo, Rob, and David.) I really appreciate all of the top-notch advice and expert information. :D Looks like I have a lot to think about... Currently, I hard-code the paths to the folders that house the files I want my CMS to edit (via a config file.) The script then iterates through the directory and adds all files of a specific type to a dropdown menu. The user can then choose one of the files to edit and load that file into a textarea... After changes are made, the content/code gets saved back to the same file/location. I do have an uploads folder, but it is in a different location on the server. I do not allow the user to create new files (I would have to do that manually)... it is a /very/ basic CMS. Anyway, looks like I have some great info to work with. Thanks again everyone for sharing your expertise. How are these saved files then imported into the content? Are they included or do you retrieve the contents using something like file(), file_get_contents(), or fread() and then echo it? If you are using include or require on a file whose contents are based on web input content then you are opening up a can of security worms since anyone with access tot he CMS could embed PHP code in the content and do anything for which the webserver has permissions. Cheers, Rob. -- .. | InterJinn Application Framework - http://www.interjinn.com | :: | An application and templating framework for PHP. Boasting | | a powerful, scalable system for accessing system services | | such as forms, properties, sessions, and caches. InterJinn | | also provides an extremely flexible architecture for | | creating re-usable components quickly and easily. | `' -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing strings... need advice. :)
Hi Robert, Robert Cummings wrote: How are these saved files then imported into the content? Are they included or do you retrieve the contents using something like file(), file_get_contents(), or fread() and then echo it? If you are using Currently I am using readfile() (plus some other security checking) to display the contents of the edited files. I setup my script to only allow specific file types (txt, html, htm). include or require on a file whose contents are based on web input content then you are opening up a can of security worms since anyone with access tot he CMS could embed PHP code in the content and do anything for which the webserver has permissions. Thanks for pointing that out. Now that you mention it, I should probably re-work my code to use a different method of page inclusion. I am pretty concerned about security breaches... what are your thoughts on readfile()? Would you suggest I use file(), file_get_contents(), or fread() instead? Thanks for the help Robert, I really appreciate your time. :) Cheers, Micky -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing strings... need advice. :)
On Mon, 2006-08-28 at 17:07 -0700, Micky Hulse wrote: Hi Robert, Robert Cummings wrote: How are these saved files then imported into the content? Are they included or do you retrieve the contents using something like file(), file_get_contents(), or fread() and then echo it? If you are using Currently I am using readfile() (plus some other security checking) to display the contents of the edited files. I setup my script to only allow specific file types (txt, html, htm). include or require on a file whose contents are based on web input content then you are opening up a can of security worms since anyone with access tot he CMS could embed PHP code in the content and do anything for which the webserver has permissions. Thanks for pointing that out. Now that you mention it, I should probably re-work my code to use a different method of page inclusion. I am pretty concerned about security breaches... what are your thoughts on readfile()? Would you suggest I use file(), file_get_contents(), or fread() instead? Readfile works great, it's the same as file_get_contents() and then issuing an echo. You may want to also stored content generated by web users outside of the web tree. There may not be any issue with how you have things now, but imagine down the road someone using your system enables PHP processing on .html files and then someone created content with PHP tags and accesses it directly from their browser... boom, same security hole. Thanks for the help Robert, I really appreciate your time. :) No problem :) Cheers, Rob. -- .. | InterJinn Application Framework - http://www.interjinn.com | :: | An application and templating framework for PHP. Boasting | | a powerful, scalable system for accessing system services | | such as forms, properties, sessions, and caches. InterJinn | | also provides an extremely flexible architecture for | | creating re-usable components quickly and easily. | `' -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing strings... need advice. :)
Robert Cummings wrote: Readfile works great, it's the same as file_get_contents() and then Ah, good to hear. :D issuing an echo. You may want to also stored content generated by web users outside of the web tree. There may not be any issue with how you [...] with PHP tags and accesses it directly from their browser... boom, same security hole. Ah! Yes, good idea. :) I think I will work this in to my script/system. Like I said, I am very concerned about security. I would have used a pre-built CMS like Textpattern or Wordpress, but the server I am on does not have database support. :( Anyway, many thanks for the tips Rob and all! You guys/gals rock! Cheers, Micky -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing a string
= is the assignment operator. It is not a comparison. == is the weak equality comparator. === is the strong equality comparator. On Tuesday 20 June 2006 06:43, Ross wrote: I have a quiz where the ansers are held in a array called $correct answers. When I compare the string if ($_REQUEST['x']= $correct_answers[$page-1]) { with a double == the answer is always correct with the single = it is always wrong. when I echo out the posted answer and the value from the answers arrray they are correct. echo post equals.$_POST['x']. corect answer is.$correct_answers[$page-1]; Ross -- Larry Garfield AIM: LOLG42 [EMAIL PROTECTED] ICQ: 6817012 If nature has made any one thing less susceptible than all others of exclusive property, it is the action of the thinking power called an idea, which an individual may exclusively possess as long as he keeps it to himself; but the moment it is divulged, it forces itself into the possession of every one, and the receiver cannot dispossess himself of it. -- Thomas Jefferson -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing a string
At 12:43 PM +0100 6/20/06, Ross wrote: I have a quiz where the ansers are held in a array called $correct answers. When I compare the string if ($_REQUEST['x']= $correct_answers[$page-1]) { with a double == the answer is always correct with the single = it is always wrong. when I echo out the posted answer and the value from the answers arrray they are correct. When you say == the answer is always correct -- does that mean even when the answer is wrong? If so, then there's something else going on here. But, I believe the answer is: if ($_REQUEST['x'] == $correct_answers[$page-1]) { This will compare the two and if they are the same will report true. You should read the manual. hth's tedd -- http://sperling.com http://ancientstones.com http://earthstones.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] comparing a string
When the $_REQUEST['x'] is not 0 or '', it will be always correct condition of your if. see the magic*. -Original Message- From: tedd [mailto:[EMAIL PROTECTED] Sent: Tuesday, June 20, 2006 10:02 PM To: Ross; php-general@lists.php.net Subject: Re: [PHP] comparing a string At 12:43 PM +0100 6/20/06, Ross wrote: I have a quiz where the ansers are held in a array called $correct answers. When I compare the string if ($_REQUEST['x']= $correct_answers[$page-1]) { with a double == the answer is always correct with the single = it is always wrong. when I echo out the posted answer and the value from the answers arrray they are correct. When you say == the answer is always correct -- does that mean even when the answer is wrong? If so, then there's something else going on here. But, I believe the answer is: if ($_REQUEST['x'] == $correct_answers[$page-1]) { This will compare the two and if they are the same will report true. You should read the manual. hth's tedd -- http://sperling.com http://ancientstones.com http://earthstones.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing of string
Hi Jeremy, I tried if ( strcmp( trim($SollKombination), trim($formCheck) ) ) same negativ result. For some reason both strings are not considered to be the same. They have the same length, are of the same type and have the same content. Why PHP doesn't recognize them as beeing equal I don't get it. thanks for your help so far janbro Jeremy Privett schrieb: janbro wrote: Hello List I've got the following little code: $formCheck= $_GET['formCheck']; $SollKombination = $_SESSION['zufall']; echo $SollKombinationbr$formCheck; print gettype($formCheck); echo ---; print gettype($SollKombination); if ($SollKombination == $formCheck){ echo test; } To give you some background: This code is supposed to check if a user has tried to login via my form. Which gives me the following output: ZL0X~TT4PQ%0~R0OXPRUHY7E!4~W337J71V4WDDI6$GS9480XP0TNP2I$1YX75S ZL0X~TT4PQ%0~R0OXPRUHY7E!4~W337J71V4WDDI6$GS9480XP0TNP2I$1YX75S string---string Everything the way it's supposed to be What I don't get is, why isn't the if statement true? Shouldn't it show test as well? Where is my mistake? I run PHP 5.1.1 on Windows. On my Win PHP 5.0 this code works proper, but not here ?!? thx JanBro Hey JanBro, Try replacing the if statement you have with this: if ( strcmp( trim($SollKombination), trim($formCheck) ) ) { echo test; } --- Jeremy Privett [ http://www.jeremyprivett.com ] Founder - Lead Software Developer - Hosting Systems Administrator Omega Vortex (http://www.omegavortex.com) -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing of string
janbro wrote: Hi Jeremy, I tried if ( strcmp( trim($SollKombination), trim($formCheck) ) ) same negativ result. For some reason both strings are not considered to be the same. They have the same length, are of the same type and have the same content. Why PHP doesn't recognize them as beeing equal I don't get it. thanks for your help so far janbro This is just a shot in the dark, but have you checked the HTML source of your test to make sure that some of the characters aren't been parsed as HTML entities? That would technically make the strings different, but you wouldn't be able to tell with just echoing alone. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing of string
I would guess that the '' in $_GET['formCheck'] will cause problems... Trying your code without the ampersand as in: $_GET['formCheck'] = 'ZL0X~TT4PQ%0~R0OXPRUHY7E!4~W337J71V4WDDI6$GS9480XP0TNP2I$1YX75S' It works just fine. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing of string
Hi JanBro: Quick guess: are the strings the same length? I've been bitten many times by string comparisons that appear to be identical but which fail due to trailing spaces, other invisible (i.e., non-printing) characters, and the like. Hope this helps. Jon - Original Message - From: janbro [EMAIL PROTECTED] To: php-general@lists.php.net Sent: Tuesday, January 03, 2006 11:22 PM Subject: [PHP] Comparing of string Hello List I've got the following little code: $formCheck= $_GET['formCheck']; $SollKombination = $_SESSION['zufall']; echo $SollKombinationbr$formCheck; print gettype($formCheck); echo ---; print gettype($SollKombination); if ($SollKombination == $formCheck){ echo test; } To give you some background: This code is supposed to check if a user has tried to login via my form. Which gives me the following output: ZL0X~TT4PQ%0~R0OXPRUHY7E!4~W337J71V4WDDI6$GS9480XP0TNP2I$1YX75S ZL0X~TT4PQ%0~R0OXPRUHY7E!4~W337J71V4WDDI6$GS9480XP0TNP2I$1YX75S string---string Everything the way it's supposed to be What I don't get is, why isn't the if statement true? Shouldn't it show test as well? Where is my mistake? I run PHP 5.1.1 on Windows. On my Win PHP 5.0 this code works proper, but not here ?!? thx JanBro -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing of string
Yep, they are of the same length. here they are: $SollKombination ZL0X~TT4PQ%0~R0OXPRUHY7E!4~W337J71V4WDDI6$GS9480XP0TNP2I$1YX75S $formCheck ZL0X~TT4PQ%0~R0OXPRUHY7E!4~W337J71V4WDDI6$GS9480XP0TNP2I$1YX75S When creating the string on the form page only visible characters were allowed. thanks but that's not it. Jon Westcot schrieb: Hi JanBro: Quick guess: are the strings the same length? I've been bitten many times by string comparisons that appear to be identical but which fail due to trailing spaces, other invisible (i.e., non-printing) characters, and the like. Hope this helps. Jon - Original Message - From: janbro [EMAIL PROTECTED] To: php-general@lists.php.net Sent: Tuesday, January 03, 2006 11:22 PM Subject: [PHP] Comparing of string Hello List I've got the following little code: $formCheck= $_GET['formCheck']; $SollKombination = $_SESSION['zufall']; echo $SollKombinationbr$formCheck; print gettype($formCheck); echo ---; print gettype($SollKombination); if ($SollKombination == $formCheck){ echo test; } To give you some background: This code is supposed to check if a user has tried to login via my form. Which gives me the following output: ZL0X~TT4PQ%0~R0OXPRUHY7E!4~W337J71V4WDDI6$GS9480XP0TNP2I$1YX75S ZL0X~TT4PQ%0~R0OXPRUHY7E!4~W337J71V4WDDI6$GS9480XP0TNP2I$1YX75S string---string Everything the way it's supposed to be What I don't get is, why isn't the if statement true? Shouldn't it show test as well? Where is my mistake? I run PHP 5.1.1 on Windows. On my Win PHP 5.0 this code works proper, but not here ?!? thx JanBro -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing of string
janbro wrote: Hello List I've got the following little code: $formCheck= $_GET['formCheck']; $SollKombination = $_SESSION['zufall']; echo $SollKombinationbr$formCheck; print gettype($formCheck); echo ---; print gettype($SollKombination); if ($SollKombination == $formCheck){ echo test; } To give you some background: This code is supposed to check if a user has tried to login via my form. Which gives me the following output: ZL0X~TT4PQ%0~R0OXPRUHY7E!4~W337J71V4WDDI6$GS9480XP0TNP2I$1YX75S ZL0X~TT4PQ%0~R0OXPRUHY7E!4~W337J71V4WDDI6$GS9480XP0TNP2I$1YX75S string---string Everything the way it's supposed to be What I don't get is, why isn't the if statement true? Shouldn't it show test as well? Where is my mistake? I run PHP 5.1.1 on Windows. On my Win PHP 5.0 this code works proper, but not here ?!? thx JanBro Hey JanBro, Try replacing the if statement you have with this: if ( strcmp( trim($SollKombination), trim($formCheck) ) ) { echo test; } --- Jeremy Privett [ http://www.jeremyprivett.com ] Founder - Lead Software Developer - Hosting Systems Administrator Omega Vortex (http://www.omegavortex.com) -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing dates
Is there a quick way to compare dates in the format dd/mm/yy without exploding and comparing the individual parts? Compare them in what way? Before, after, days between? In any case, i'd look at strtotime() to convert them into timestamps, then diff them to get the number of seconds b/n them, then go from there. If strtotime() won't do it because it expects mm/dd/yy (consider 01/02/05 is that feb 1st or jan 2nd?) then split up the string and use mktime(). good luck. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing two texts
Robert Cummings wrote: On Wed, 2005-06-22 at 22:55, Richard Lynch wrote: ... Well some noobs might think crude works quite well for them :) Ya want me to do Jenny's work for her for free or what?! :-) No but it seemed like Jenny did *grin*. _seemed_ ??? r u kidding :-) whereas I'll happily spend an hour writing up and contemplating someone else's problem - I don't have five minutes for people who are expecting to be spoonfed (go learn ASP and get a support contract, thanks ;-). The point was that depending on what Jenny wants for output, it could be pretty easy to compare two strings character by character. Or it could be incredibly difficult, if you need diff-like capabilities of recognizing similar lines of text interspersed with radically different lines of text. She obviously didn't like the use diff answer, so I gave her the yeast to roll her own. 'Course, she didn't like that either, but that's hardly my fault. don't suppose you want to hear a joke about 'womens perogative' do you? ;-) [shrug] -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing two texts
On Sun, June 19, 2005 8:33 am, Robert Cummings said: On Sun, 2005-06-19 at 09:22, M. Sokolewicz wrote: jenny mathew wrote: Untested, very crude: ^^ It's a bit of a dirty hack though. If I compare a 2 character text against a 40k text, the error handler will be invoked (39998 * 3) times if $text1 is the 2 byte string. That's extremely inefficient. I don't think I've ever seen error suppression abused so badly to prevent writing an extra line or 2 using isset(). Don't you think I knew that when I typed it? What part of very crude did you not get? Ya want me to do Jenny's work for her for free or what?! :-) The point was that depending on what Jenny wants for output, it could be pretty easy to compare two strings character by character. Or it could be incredibly difficult, if you need diff-like capabilities of recognizing similar lines of text interspersed with radically different lines of text. She obviously didn't like the use diff answer, so I gave her the yeast to roll her own. 'Course, she didn't like that either, but that's hardly my fault. [shrug] -- Like Music? http://l-i-e.com/artists.htm -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing two texts
On Wed, 2005-06-22 at 22:55, Richard Lynch wrote: On Sun, June 19, 2005 8:33 am, Robert Cummings said: On Sun, 2005-06-19 at 09:22, M. Sokolewicz wrote: jenny mathew wrote: Untested, very crude: ^^ It's a bit of a dirty hack though. If I compare a 2 character text against a 40k text, the error handler will be invoked (39998 * 3) times if $text1 is the 2 byte string. That's extremely inefficient. I don't think I've ever seen error suppression abused so badly to prevent writing an extra line or 2 using isset(). Don't you think I knew that when I typed it? What part of very crude did you not get? Well some noobs might think crude works quite well for them :) Ya want me to do Jenny's work for her for free or what?! :-) No but it seemed like Jenny did *grin*. The point was that depending on what Jenny wants for output, it could be pretty easy to compare two strings character by character. Or it could be incredibly difficult, if you need diff-like capabilities of recognizing similar lines of text interspersed with radically different lines of text. She obviously didn't like the use diff answer, so I gave her the yeast to roll her own. 'Course, she didn't like that either, but that's hardly my fault. [shrug] -- .. | InterJinn Application Framework - http://www.interjinn.com | :: | An application and templating framework for PHP. Boasting | | a powerful, scalable system for accessing system services | | such as forms, properties, sessions, and caches. InterJinn | | also provides an extremely flexible architecture for | | creating re-usable components quickly and easily. | `' -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing two texts
jenny mathew wrote: so,what what should i conclude .it is not possible to compare two texts and hight the difference at this moment. 1. conclude whatever the you like 2. 'hight' is not an english word (I guess you mean highlight) 3. actually it is possible but you have to write some code 4. nobody will be writing a compare_these_two_strings_and_show_the_differences_in_a_complete_webpage_styled_the_way_I_like_it() function for php anytime soon. 5. go read about 'DIFF' like I said the first time. thanks. Yours , humour class=monday, crass, dark, sexist with regard to the concept of 'objectification of women' you might consider another sign off than 'Yours' - or maybe you want to be 0wn3d? /humour Jenny On 6/19/05, Robert Cummings [EMAIL PROTECTED] wrote: On Sun, 2005-06-19 at 12:33, M. Sokolewicz wrote: Robert Cummings wrote: On Sun, 2005-06-19 at 09:22, M. Sokolewicz wrote: jenny mathew wrote: Untested, very crude: ?php $maxlen = max(strlen($text1), strlen($text2)); for ($i = 0; $i $maxlen; $i++){ if (@$text1[$i] == @$text2[$i]) echo @$text1[$i]; else @echo font color=red$text1[$i]|$text2[$i]/font; } ? donot you think you program will just bring the server to its foot ,if the text message encountered is very large of order of 40 KB or larger.is http://larger.ishttp://larger.isthere any other efficient method. 40KB isn't large... now, when you're talking about hundreds of MBs of text, then it gets large :) 40KB, with that method, is nothing... It's a bit of a dirty hack though. If I compare a 2 character text against a 40k text, the error handler will be invoked (39998 * 3) times if $text1 is the 2 byte string. That's extremely inefficient. I don't think I've ever seen error suppression abused so badly to prevent writing an extra line or 2 using isset(). Cheers, Rob. I agree with what you said fully; however, even though that's the case, and it indeed could be written a lot faster and cleaner, it would not pose a problem on most systems. That was the point I tried to make ;) Oh absolutely, 40k is tiny :) Just never seen error suppression used for such mundane processing. Now if we up it to 2 chars and 5 megs :) With a custom user space error handler in the background... ugh. Cheers, Rob. -- .. | InterJinn Application Framework - http://www.interjinn.com | :: | An application and templating framework for PHP. Boasting | | a powerful, scalable system for accessing system services | | such as forms, properties, sessions, and caches. InterJinn | | also provides an extremely flexible architecture for | | creating re-usable components quickly and easily. | `' -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing two texts
I saw a function in the php manual the other day which displays the difference as a percentage, for instance two strings, foo foos would be maybe 90% match, not sure thats what you mean though, you can always do a str_replace like so, $string1 = 'foo'; $string2 = 'foos'; $string = (str_replace($string1, , $string2)); echo $string; The difference being one letter in this case, the letter 's', whether that would work for what your after im not sure because it would depend on string1 containg string in the same order but not work for random characters. jenny mathew wrote: so,what what should i conclude .it is not possible to compare two texts and hight the difference at this moment. thanks. Yours , Jenny On 6/19/05, Robert Cummings [EMAIL PROTECTED] wrote: On Sun, 2005-06-19 at 12:33, M. Sokolewicz wrote: Robert Cummings wrote: On Sun, 2005-06-19 at 09:22, M. Sokolewicz wrote: jenny mathew wrote: Untested, very crude: ?php $maxlen = max(strlen($text1), strlen($text2)); for ($i = 0; $i $maxlen; $i++){ if (@$text1[$i] == @$text2[$i]) echo @$text1[$i]; else @echo font color=red$text1[$i]|$text2[$i]/font; } ? donot you think you program will just bring the server to its foot ,if the text message encountered is very large of order of 40 KB or larger.is http://larger.ishttp://larger.isthere any other efficient method. 40KB isn't large... now, when you're talking about hundreds of MBs of text, then it gets large :) 40KB, with that method, is nothing... It's a bit of a dirty hack though. If I compare a 2 character text against a 40k text, the error handler will be invoked (39998 * 3) times if $text1 is the 2 byte string. That's extremely inefficient. I don't think I've ever seen error suppression abused so badly to prevent writing an extra line or 2 using isset(). Cheers, Rob. I agree with what you said fully; however, even though that's the case, and it indeed could be written a lot faster and cleaner, it would not pose a problem on most systems. That was the point I tried to make ;) Oh absolutely, 40k is tiny :) Just never seen error suppression used for such mundane processing. Now if we up it to 2 chars and 5 megs :) With a custom user space error handler in the background... ugh. Cheers, Rob. -- .. | InterJinn Application Framework - http://www.interjinn.com | :: | An application and templating framework for PHP. Boasting | | a powerful, scalable system for accessing system services | | such as forms, properties, sessions, and caches. InterJinn | | also provides an extremely flexible architecture for | | creating re-usable components quickly and easily. | `' -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing two texts
Untested, very crude: ?php $maxlen = max(strlen($text1), strlen($text2)); for ($i = 0; $i $maxlen; $i++){ if (@$text1[$i] == @$text2[$i]) echo @$text1[$i]; else @echo font color=red$text1[$i]|$text2[$i]/font; } ? donot you think you program will just bring the server to its foot ,if the text message encountered is very large of order of 40 KB or larger.ishttp://larger.isthere any other efficient method.
Re: [PHP] comparing two texts
jenny mathew wrote: Untested, very crude: ?php $maxlen = max(strlen($text1), strlen($text2)); for ($i = 0; $i $maxlen; $i++){ if (@$text1[$i] == @$text2[$i]) echo @$text1[$i]; else @echo font color=red$text1[$i]|$text2[$i]/font; } ? donot you think you program will just bring the server to its foot ,if the text message encountered is very large of order of 40 KB or larger.ishttp://larger.isthere any other efficient method. 40KB isn't large... now, when you're talking about hundreds of MBs of text, then it gets large :) 40KB, with that method, is nothing... -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing two texts
On Sun, 2005-06-19 at 09:22, M. Sokolewicz wrote: jenny mathew wrote: Untested, very crude: ?php $maxlen = max(strlen($text1), strlen($text2)); for ($i = 0; $i $maxlen; $i++){ if (@$text1[$i] == @$text2[$i]) echo @$text1[$i]; else @echo font color=red$text1[$i]|$text2[$i]/font; } ? donot you think you program will just bring the server to its foot ,if the text message encountered is very large of order of 40 KB or larger.ishttp://larger.isthere any other efficient method. 40KB isn't large... now, when you're talking about hundreds of MBs of text, then it gets large :) 40KB, with that method, is nothing... It's a bit of a dirty hack though. If I compare a 2 character text against a 40k text, the error handler will be invoked (39998 * 3) times if $text1 is the 2 byte string. That's extremely inefficient. I don't think I've ever seen error suppression abused so badly to prevent writing an extra line or 2 using isset(). Cheers, Rob. -- .. | InterJinn Application Framework - http://www.interjinn.com | :: | An application and templating framework for PHP. Boasting | | a powerful, scalable system for accessing system services | | such as forms, properties, sessions, and caches. InterJinn | | also provides an extremely flexible architecture for | | creating re-usable components quickly and easily. | `' -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing two texts
Robert Cummings wrote: On Sun, 2005-06-19 at 09:22, M. Sokolewicz wrote: jenny mathew wrote: Untested, very crude: ?php $maxlen = max(strlen($text1), strlen($text2)); for ($i = 0; $i $maxlen; $i++){ if (@$text1[$i] == @$text2[$i]) echo @$text1[$i]; else @echo font color=red$text1[$i]|$text2[$i]/font; } ? donot you think you program will just bring the server to its foot ,if the text message encountered is very large of order of 40 KB or larger.ishttp://larger.isthere any other efficient method. 40KB isn't large... now, when you're talking about hundreds of MBs of text, then it gets large :) 40KB, with that method, is nothing... It's a bit of a dirty hack though. If I compare a 2 character text against a 40k text, the error handler will be invoked (39998 * 3) times if $text1 is the 2 byte string. That's extremely inefficient. I don't think I've ever seen error suppression abused so badly to prevent writing an extra line or 2 using isset(). Cheers, Rob. I agree with what you said fully; however, even though that's the case, and it indeed could be written a lot faster and cleaner, it would not pose a problem on most systems. That was the point I tried to make ;) -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing two texts
On Sun, 2005-06-19 at 12:33, M. Sokolewicz wrote: Robert Cummings wrote: On Sun, 2005-06-19 at 09:22, M. Sokolewicz wrote: jenny mathew wrote: Untested, very crude: ?php $maxlen = max(strlen($text1), strlen($text2)); for ($i = 0; $i $maxlen; $i++){ if (@$text1[$i] == @$text2[$i]) echo @$text1[$i]; else @echo font color=red$text1[$i]|$text2[$i]/font; } ? donot you think you program will just bring the server to its foot ,if the text message encountered is very large of order of 40 KB or larger.ishttp://larger.isthere any other efficient method. 40KB isn't large... now, when you're talking about hundreds of MBs of text, then it gets large :) 40KB, with that method, is nothing... It's a bit of a dirty hack though. If I compare a 2 character text against a 40k text, the error handler will be invoked (39998 * 3) times if $text1 is the 2 byte string. That's extremely inefficient. I don't think I've ever seen error suppression abused so badly to prevent writing an extra line or 2 using isset(). Cheers, Rob. I agree with what you said fully; however, even though that's the case, and it indeed could be written a lot faster and cleaner, it would not pose a problem on most systems. That was the point I tried to make ;) Oh absolutely, 40k is tiny :) Just never seen error suppression used for such mundane processing. Now if we up it to 2 chars and 5 megs :) With a custom user space error handler in the background... ugh. Cheers, Rob. -- .. | InterJinn Application Framework - http://www.interjinn.com | :: | An application and templating framework for PHP. Boasting | | a powerful, scalable system for accessing system services | | such as forms, properties, sessions, and caches. InterJinn | | also provides an extremely flexible architecture for | | creating re-usable components quickly and easily. | `' -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing two texts
so,what what should i conclude .it is not possible to compare two texts and hight the difference at this moment. thanks. Yours , Jenny On 6/19/05, Robert Cummings [EMAIL PROTECTED] wrote: On Sun, 2005-06-19 at 12:33, M. Sokolewicz wrote: Robert Cummings wrote: On Sun, 2005-06-19 at 09:22, M. Sokolewicz wrote: jenny mathew wrote: Untested, very crude: ?php $maxlen = max(strlen($text1), strlen($text2)); for ($i = 0; $i $maxlen; $i++){ if (@$text1[$i] == @$text2[$i]) echo @$text1[$i]; else @echo font color=red$text1[$i]|$text2[$i]/font; } ? donot you think you program will just bring the server to its foot ,if the text message encountered is very large of order of 40 KB or larger.is http://larger.ishttp://larger.isthere any other efficient method. 40KB isn't large... now, when you're talking about hundreds of MBs of text, then it gets large :) 40KB, with that method, is nothing... It's a bit of a dirty hack though. If I compare a 2 character text against a 40k text, the error handler will be invoked (39998 * 3) times if $text1 is the 2 byte string. That's extremely inefficient. I don't think I've ever seen error suppression abused so badly to prevent writing an extra line or 2 using isset(). Cheers, Rob. I agree with what you said fully; however, even though that's the case, and it indeed could be written a lot faster and cleaner, it would not pose a problem on most systems. That was the point I tried to make ;) Oh absolutely, 40k is tiny :) Just never seen error suppression used for such mundane processing. Now if we up it to 2 chars and 5 megs :) With a custom user space error handler in the background... ugh. Cheers, Rob. -- .. | InterJinn Application Framework - http://www.interjinn.com | :: | An application and templating framework for PHP. Boasting | | a powerful, scalable system for accessing system services | | such as forms, properties, sessions, and caches. InterJinn | | also provides an extremely flexible architecture for | | creating re-usable components quickly and easily. | `' -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing two texts
jenny mathew wrote: hello group, is it possible to compare two different text messages and highlight the difference in php. i mean to say that $text1=message 1 $text2=message 2 i want to compare both $text1 and $text2 for differences and highlight the differece in php.is it possible. yes. is it easy? that depends on how far you want to go with diff'ing (and how good you are at string manipulation :-) this is a general problem which has been solved by very skilled people already, I would suggest reading some more about 'diff' etc and figure out if you can use existing tools to get what you want: http://www.gnu.org/software/diffutils/diffutils.html http://en.wikipedia.org/wiki/Diff waiting for your reply. thanks. Yours, Jenny -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing two texts
i want to compare two text fetched out of database and echo the result on the webpage.i want to do it in php language and i donot want to compare two text files ,i wanna compare two text messages (that is fetched out from database). thanks. Yours, Jenny. On 6/18/05, Jochem Maas [EMAIL PROTECTED] wrote: jenny mathew wrote: hello group, is it possible to compare two different text messages and highlight the difference in php. i mean to say that $text1=message 1 $text2=message 2 i want to compare both $text1 and $text2 for differences and highlight the differece in php.is it possible. yes. is it easy? that depends on how far you want to go with diff'ing (and how good you are at string manipulation :-) this is a general problem which has been solved by very skilled people already, I would suggest reading some more about 'diff' etc and figure out if you can use existing tools to get what you want: http://www.gnu.org/software/diffutils/diffutils.html http://en.wikipedia.org/wiki/Diff waiting for your reply. thanks. Yours, Jenny -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing two texts
On Sat, June 18, 2005 9:41 am, jenny mathew said: i want to compare two text fetched out of database and echo the result on the webpage.i want to do it in php language and i donot want to compare two text files ,i wanna compare two text messages (that is fetched out from database). I believe you will find it more feasible to throw your two messages into files and use exec() to call diff on them than to write essentially all of diff in PHP... -- Like Music? http://l-i-e.com/artists.htm -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing two texts
On Sat, June 18, 2005 3:21 am, jenny mathew said: is it possible to compare two different text messages and highlight the difference in php. i mean to say that $text1=message 1 $text2=message 2 i want to compare both $text1 and $text2 for differences and highlight the differece in php.is it possible. waiting for your reply. Untested, very crude: ?php $maxlen = max(strlen($text1), strlen($text2)); for ($i = 0; $i $maxlen; $i++){ if (@$text1[$i] == @$text2[$i]) echo @$text1[$i]; else @echo font color=red$text1[$i]|$text2[$i]/font; } ? -- Like Music? http://l-i-e.com/artists.htm -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing two texts
On Jun 18, 2005, at 3:42 PM, Richard Lynch wrote: On Sat, June 18, 2005 3:21 am, jenny mathew said: is it possible to compare two different text messages and highlight the difference in php. i mean to say that $text1=message 1 $text2=message 2 i want to compare both $text1 and $text2 for differences and highlight the differece in php.is it possible. waiting for your reply. Untested, very crude: ?php $maxlen = max(strlen($text1), strlen($text2)); for ($i = 0; $i $maxlen; $i++){ if (@$text1[$i] == @$text2[$i]) echo @$text1[$i]; else @echo font color=red$text1[$i]|$text2[$i]/font; } ? -- Like Music? http://l-i-e.com/artists.htm -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php Would it be possible to explode both messages oninto an array and run array_diff() and work from there? Just a thought late in the day... Edward Vermillion [EMAIL PROTECTED] -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing timestamps
Chris Mach wrote --- napísal:: I want to compare a timestamp in my database with the current time. I want to be able to tell if the timestamp is within 5 mins of the current time. How would I do this? Please? timestamp_column BETWEEN UNIX_TIMESTAMP(NOW() - INTERVAL 5 MINUTE) AND UNIX_TIMESTAMP(NOW() + INTERVAL 5 MINUTE) -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing 2 files
You are reinventng the wheel try `diff file1 file2`; Jens Schmeiser wrote: Dear list. I want to compare two text files and print the differences. The text files contain the structure of a database, so they are very big (6000 lines). The file looks like that: TABLENAME#COLUMNNAME#DATATYPE#DATALENGTH#DATAPRECISION#NULLS ... I only check if the datatype and nulls are different. If so, then the two lines of the files will be printed. I tried to do that and it works excellent if there aren't many differences, but if there are many diffs, it takes time and time. What I do now is to read the to files to an array and get the differences with array_diff $array1=file('file1.txt'); $array2=file('file2.txt'); $result1 = array_diff($array1,$array2); $result2 = array_diff($array2,$array1); After that I do the following: foreach ($result1 as $line1) { foreach ($result2 as $line2) { // compare the two lines and show the differences; continue; } } Is there a better way to do that (and of course faster)? Regards Jens -- Raditha Dissanayake. - http://www.radinks.com/print/upload.php SFTP, FTP and HTTP File Upload solutions -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing multiple Mysql tables to find duplicates
HI John, I have this working with the exception of when there is a ' in an email address that I want to remove. I have modified your line { $email_list .= '{$row['email']}',; }, with { $email_list .= str_replace(', \', '{$r[email]}',); }, but now it escapes all the single quotes. Is there a php function that escapes single quotes in Mysql queries? If not, do you know the best way to escape *only* single quotes in the email address string and not the single quotes surrounding the string? Example (output of $email_list) '[EMAIL PROTECTED]','[EMAIL PROTECTED]'that.com','etc... Need to escape the [EMAIL PROTECTED]'that.com Thanks. -- Chris Bruce [EMAIL PROTECTED] Idextrus E-Business Architects http://www.idextrus.com 3282 Wilmar Cres. Mississauga, ON L5L4B2 CA 905.828.9189 This e-mail and its contents are privileged, confidential and subject to copyright. If you are not the intended recipient, please delete this e-mail immediately. Any unauthorized use or disclosure of the information herein is prohibited. On Jan 30, 2004, at 12:54 PM, John W. Holmes wrote: From: Chris Bruce [EMAIL PROTECTED] Mysql 3.23.54. My first thought was to load the output from the tables into an array and they use a foreach and in_array to create a list of dups, but I wanted to see if there was an easier way. Ah, in that case, my other query won't work. :) This should: ?php $query = SELECT list1.email FROM master_list, list1 WHERE master_list.email = list1.email; $result = mysql_query($query) or die(mysql_error()); while($r = mysql_fetch_assoc($result)) { $email_list .= '{$row['email']}',; } $email_list = substr($email_list,0,-1); //remove last comma $query = DELETE FROM list1 WHERE email IN ($email_list); $result = mysql_query($query) or die(mysql_error()); ? Repeat for other tables. ---John Holmes... -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing multiple Mysql tables to find duplicates
From: Chris Bruce Is there a php function that escapes single quotes in Mysql queries? addslashes() mysql_escape_string() mysql_real_escape_string() ---John Holmes... -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing multiple Mysql tables to find duplicates
On Wednesday 04 February 2004 00:09, Chris Bruce wrote: I have modified your line { $email_list .= '{$row['email']}',; }, with { $email_list .= str_replace(', \', '{$r[email]}',); }, but now it escapes all the single quotes. Is there a php function that escapes single quotes in Mysql queries? Yes, surprisingly enough it's called mysql_escape_string(). If not, do you know the best way to escape *only* single quotes in the email address string and not the single quotes surrounding the string? Example (output of $email_list) '[EMAIL PROTECTED]','[EMAIL PROTECTED]'that.com','etc... Need to escape the [EMAIL PROTECTED]'that.com I don't understand why you want to escape the single-quote. You shouldn't be allowing such entries anyway because quotes are not valid characters for domain names thus it's an invalid email address. -- Jason Wong - Gremlins Associates - www.gremlins.biz Open Source Software Systems Integrators * Web Design Hosting * Internet Intranet Applications Development * -- Search the list archives before you post http://marc.theaimsgroup.com/?l=php-general -- /* Trust everybody, but cut the cards. -- Finlay Peter Dunne, Mr. Dooley's Philosophy */ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] comparing dates
Is it possible to pull that dates out as unix time stamps? Then all you need to do is subtract one from the other, convert the results to days/hours/minutes and Bob's your uncle. If not, then you'll need to do some string manipulation to get the string into a format that strtotime() understands and repeat the above.. HTH Martin -Original Message- From: Ryan A [mailto:[EMAIL PROTECTED] Sent: Monday, 2 February 2004 10:04 AM To: [EMAIL PROTECTED] Subject: [PHP] comparing dates Hi, Am a bit confused as to how to do this, I have some dates in the database as expire_login timestamp(14). I am entering dates 1 day,11 hours,59 minutes in advance. The user can sign in anytime and it should display how many days, hours and mins before his account expires... I am selecting the data as select expire_login, now() from allow_logins; which gives me two 14 numberic characters strings like: 20040202091212 20040201070500 How do I compare it to display something like this to the visitor: You have $xdays day/s, $xhours hours and $xmins minutes before your account expires Been hitting the manual, but have either been searching in the wrong places or? I think I will have to use explode,strtotime on this...but am not sure. Any help appreciated. Thanks, -Ryan -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php __ Information from NOD32 1.614 (20040129) __ This message was checked by NOD32 for Exchange e-mail monitor. http://www.nod32.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing dates
On Monday, February 2, 2004, at 10:04 AM, Ryan A wrote: which gives me two 14 numberic characters strings like: 20040202091212 20040201070500 How do I compare it to display something like this to the visitor: You have $xdays day/s, $xhours hours and $xmins minutes before your account expires Been hitting the manual, but have either been searching in the wrong places or? I think I will have to use explode,strtotime on this...but am not sure. Ryan, explode() won't help (nothing to explode on) strtotime() won't help, as it can't work directly with the above date format There's a decent comment on http://php.net/strtotime (RTFM) by 'tobi at schluer dot de' ...You can read the db using the UNIX_TIMESTAMP()-function, which returns the timestamp from the date(time) field. So you don't need to convert the dates in PHP, but let SQL do that job. So, you can do it with MySQL. Otherwise, a function like this in PHP would do it: ? function mysqlToUnixStamp($in) { $y = substr($in,0,4); $m = substr($in,4,2); $d = substr($in,6,2); $h = substr($in,8,2); $i = substr($in,10,2); $s = substr($in,12,2); return mktime($h,$i,$s,$m,$d,$y); } ? So then pass your mysql stamps to it like this: ? $d1 = '20040202091212'; $d2 = '20040201070500'; $d1 = mysqlToUnixStamp($d1); $d2 = mysqlToUnixStamp($d2); ? An you can then compare them (for example): ? if($d1 = $d2) { /*something*/ } ? Or find the difference in seconds: ? $diff = $d1 - $d2; ? Converting this into a human readable $xdays day/s, $xhours hours and $xmins minutes is not exactly easy, but here's some hints for you to build on: ? function secondsToString($in) { $secsInDay = (60 * 60) * 24; $secsInHour = 60 * 60; $secsInMin = 60; $ret = ''; if($in $secsInDay) { $days = round($in / $secsInDay); $remainder = $in % $secsInDay; $ret .= {$days} days, ; } if($remainder $secsInHour) { $hours = round($remainder / $secsInHour); $remainder = $in % $secsInHour; $ret .= {$hours} hours, ; } if($remainder $secsInMin) { $mins = round($remainder / $secsInMin); $remainder = $in % $secsInMin; $ret .= {$mins} mins, ; } // strip off last ', ' $ret = substr($ret,0,-2); return $ret; } // converting to human readable $timeLeft = secondsToString($diff); // print to screen echo you have {$timeLeft} remain on your membership; ? Out of all this, what you need to look-up in the manual and understand is the modulus (%), an arithmetic operator substr(). http://www.php.net/manual/en/language.operators.arithmetic.php http://www.php.net/substr Justin French -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing dates
Hey, Thanks for replying. I did find an easier way, but only after going through what you sent me...the way i found was using substr. I do read the manual, but not the online one, I have a downloaded windows helpfile copy, its much faster and easier to access but one disadvantage is...it does not have the user comments. Cheers, -Ryan http://Bestwebhosters.com - Original Message - From: Justin French [EMAIL PROTECTED] To: Ryan A [EMAIL PROTECTED] Cc: [EMAIL PROTECTED] Sent: Monday, February 02, 2004 1:21 AM Subject: Re: [PHP] comparing dates On Monday, February 2, 2004, at 10:04 AM, Ryan A wrote: which gives me two 14 numberic characters strings like: 20040202091212 20040201070500 How do I compare it to display something like this to the visitor: You have $xdays day/s, $xhours hours and $xmins minutes before your account expires Been hitting the manual, but have either been searching in the wrong places or? I think I will have to use explode,strtotime on this...but am not sure. Ryan, explode() won't help (nothing to explode on) strtotime() won't help, as it can't work directly with the above date format There's a decent comment on http://php.net/strtotime (RTFM) by 'tobi at schluer dot de' ...You can read the db using the UNIX_TIMESTAMP()-function, which returns the timestamp from the date(time) field. So you don't need to convert the dates in PHP, but let SQL do that job. So, you can do it with MySQL. Otherwise, a function like this in PHP would do it: ? function mysqlToUnixStamp($in) { $y = substr($in,0,4); $m = substr($in,4,2); $d = substr($in,6,2); $h = substr($in,8,2); $i = substr($in,10,2); $s = substr($in,12,2); return mktime($h,$i,$s,$m,$d,$y); } ? So then pass your mysql stamps to it like this: ? $d1 = '20040202091212'; $d2 = '20040201070500'; $d1 = mysqlToUnixStamp($d1); $d2 = mysqlToUnixStamp($d2); ? An you can then compare them (for example): ? if($d1 = $d2) { /*something*/ } ? Or find the difference in seconds: ? $diff = $d1 - $d2; ? Converting this into a human readable $xdays day/s, $xhours hours and $xmins minutes is not exactly easy, but here's some hints for you to build on: ? function secondsToString($in) { $secsInDay = (60 * 60) * 24; $secsInHour = 60 * 60; $secsInMin = 60; $ret = ''; if($in $secsInDay) { $days = round($in / $secsInDay); $remainder = $in % $secsInDay; $ret .= {$days} days, ; } if($remainder $secsInHour) { $hours = round($remainder / $secsInHour); $remainder = $in % $secsInHour; $ret .= {$hours} hours, ; } if($remainder $secsInMin) { $mins = round($remainder / $secsInMin); $remainder = $in % $secsInMin; $ret .= {$mins} mins, ; } // strip off last ', ' $ret = substr($ret,0,-2); return $ret; } // converting to human readable $timeLeft = secondsToString($diff); // print to screen echo you have {$timeLeft} remain on your membership; ? Out of all this, what you need to look-up in the manual and understand is the modulus (%), an arithmetic operator substr(). http://www.php.net/manual/en/language.operators.arithmetic.php http://www.php.net/substr Justin French -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing multiple Mysql tables to find duplicates
Hi, If you are using mysql 4 you can use subselects to delete from where in (select) the select itself can be a multi table join. if you are on mysql 3.xx you can use PHP to mimic a subselect. Chris Bruce wrote: Hello everyone, I am trying to write a function that would compare one table to a number of other tables in Mysql and remove any duplicates found. This is for tables of email addresses where I want to remove any dups found. Example: Master list - compare to list1, list2, list3, and so on and remove matches found from list1, list2, list3 etc. *not* from Master list. Does anyone know of any such beast before I set out to reinvent it? Thanks. Chris -- Raditha Dissanayake. http://www.radinks.com/sftp/ | http://www.raditha.com/megaupload Lean and mean Secure FTP applet with | Mega Upload - PHP file uploader Graphical User Inteface. Just 150 KB | with progress bar. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing multiple Mysql tables to find duplicates
Mysql 3.23.54. My first thought was to load the output from the tables into an array and they use a foreach and in_array to create a list of dups, but I wanted to see if there was an easier way. -- Chris Bruce [EMAIL PROTECTED] Idextrus E-Business Architects http://www.idextrus.com 3282 Wilmar Cres. Mississauga, ON L5L4B2 CA 905.828.9189 On Jan 30, 2004, at 12:54 PM, Raditha Dissanayake wrote: Hi, If you are using mysql 4 you can use subselects to delete from where in (select) the select itself can be a multi table join. if you are on mysql 3.xx you can use PHP to mimic a subselect. Chris Bruce wrote: Hello everyone, I am trying to write a function that would compare one table to a number of other tables in Mysql and remove any duplicates found. This is for tables of email addresses where I want to remove any dups found. Example: Master list - compare to list1, list2, list3, and so on and remove matches found from list1, list2, list3 etc. *not* from Master list. Does anyone know of any such beast before I set out to reinvent it? Thanks. Chris -- Raditha Dissanayake. --- - http://www.radinks.com/sftp/ | http://www.raditha.com/megaupload Lean and mean Secure FTP applet with | Mega Upload - PHP file uploader Graphical User Inteface. Just 150 KB | with progress bar.
Re: [PHP] Comparing multiple Mysql tables to find duplicates
From: Chris Bruce [EMAIL PROTECTED] I am trying to write a function that would compare one table to a number of other tables in Mysql and remove any duplicates found. This is for tables of email addresses where I want to remove any dups found. Example: Master list - compare to list1, list2, list3, and so on and remove matches found from list1, list2, list3 etc. *not* from Master list. Does anyone know of any such beast before I set out to reinvent it? DELETE FROM list1 USING master_list, list1 WHERE list1.email = master_list.email Repeat for other tables. ---John Holmes... -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Comparing multiple Mysql tables to find duplicates
My first thought was to load the output from the tables into an array and they use a foreach and in_array to create a list of dups, but I wanted to see if there was an easier way. -- If you're not using MySQL 4, then yeah, that's probably the best way. Just realize that this isn't going to be the fastest script in the world. If it's a one-off or very infrequently run script, then that's not a big deal. -M -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing multiple Mysql tables to find duplicates
From: Chris Bruce [EMAIL PROTECTED] Mysql 3.23.54. My first thought was to load the output from the tables into an array and they use a foreach and in_array to create a list of dups, but I wanted to see if there was an easier way. Ah, in that case, my other query won't work. :) This should: ?php $query = SELECT list1.email FROM master_list, list1 WHERE master_list.email = list1.email; $result = mysql_query($query) or die(mysql_error()); while($r = mysql_fetch_assoc($result)) { $email_list .= '{$row['email']}',; } $email_list = substr($email_list,0,-1); //remove last comma $query = DELETE FROM list1 WHERE email IN ($email_list); $result = mysql_query($query) or die(mysql_error()); ? Repeat for other tables. ---John Holmes... -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing multiple Mysql tables to find duplicates
This will work for Mysql 3.23.54? -- Chris Bruce [EMAIL PROTECTED] Idextrus E-Business Architects http://www.idextrus.com 3282 Wilmar Cres. Mississauga, ON L5L4B2 CA 905.828.9189 On Jan 30, 2004, at 12:48 PM, John W. Holmes wrote: From: Chris Bruce [EMAIL PROTECTED] I am trying to write a function that would compare one table to a number of other tables in Mysql and remove any duplicates found. This is for tables of email addresses where I want to remove any dups found. Example: Master list - compare to list1, list2, list3, and so on and remove matches found from list1, list2, list3 etc. *not* from Master list. Does anyone know of any such beast before I set out to reinvent it? DELETE FROM list1 USING master_list, list1 WHERE list1.email = master_list.email Repeat for other tables. ---John Holmes...
Re: [PHP] Comparing multiple Mysql tables to find duplicates
Cool, thanks John, I'll give it a shot. Sorry for the last email, I sent it before you sent this one :) -- Chris Bruce [EMAIL PROTECTED] Idextrus E-Business Architects http://www.idextrus.com 3282 Wilmar Cres. Mississauga, ON L5L4B2 CA 905.828.9189 On Jan 30, 2004, at 12:54 PM, John W. Holmes wrote: From: Chris Bruce [EMAIL PROTECTED] Mysql 3.23.54. My first thought was to load the output from the tables into an array and they use a foreach and in_array to create a list of dups, but I wanted to see if there was an easier way. Ah, in that case, my other query won't work. :) This should: ?php $query = SELECT list1.email FROM master_list, list1 WHERE master_list.email = list1.email; $result = mysql_query($query) or die(mysql_error()); while($r = mysql_fetch_assoc($result)) { $email_list .= '{$row['email']}',; } $email_list = substr($email_list,0,-1); //remove last comma $query = DELETE FROM list1 WHERE email IN ($email_list); $result = mysql_query($query) or die(mysql_error()); ? Repeat for other tables. ---John Holmes... -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing multiple Mysql tables to find duplicates
Did you mention cofee John? now why did i suggest subselects when good old joins seem to do the tricks. Yikes! John W. Holmes wrote: From: Chris Bruce [EMAIL PROTECTED] I am trying to write a function that would compare one table to a number of other tables in Mysql and remove any duplicates found. This is for tables of email addresses where I want to remove any dups found. Example: Master list - compare to list1, list2, list3, and so on and remove matches found from list1, list2, list3 etc. *not* from Master list. Does anyone know of any such beast before I set out to reinvent it? DELETE FROM list1 USING master_list, list1 WHERE list1.email = master_list.email Repeat for other tables. ---John Holmes... -- Raditha Dissanayake. http://www.radinks.com/sftp/ | http://www.raditha.com/megaupload Lean and mean Secure FTP applet with | Mega Upload - PHP file uploader Graphical User Inteface. Just 150 KB | with progress bar. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing 2 strings.
From: Ed Curtis [EMAIL PROTECTED] I currently store text from a MySQL blob field in a string $orig_text. I need to compare that with something someone type in from a form stored in $new_text. How would I go about comparing them to see if they are different or exactly the same? strcmp doesn't look like it will handle this too well. Why would you say that when strcmp() is exactly what you need to use?? ---John Holmes... -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing 2 strings.
I guess I did miss that it says that the comparison is case sensitive and binary safe. Thanks, Ed On Wed, 19 Nov 2003, CPT John W. Holmes wrote: From: Ed Curtis [EMAIL PROTECTED] I currently store text from a MySQL blob field in a string $orig_text. I need to compare that with something someone type in from a form stored in $new_text. How would I go about comparing them to see if they are different or exactly the same? strcmp doesn't look like it will handle this too well. Why would you say that when strcmp() is exactly what you need to use?? ---John Holmes... -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing xml files, removing some html tags
Thanks to all (actually just one) that answered my question. Unfortunatelly I was hoping a more complete answer since the part I asked was not the main goal... bu t anyway... I'd like to ask then if the viewers could validate my new approach or at least point ways of actually implementing it. Suppose I use Xerces and tidy to turn two html files into two xhtml ones. I'd like to remove the data found between the Tags and generate two new files only with the scructure elements (tables, Br, p and so on). Then I could use regular diff from unix and if they differ in more than X% I assume they are different. Assuming that this approach is ok any tips regarding the actual implementation ? Any snippets of code would be great. __ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing xml files, removing some html tags
Hi, Discussion of xerces will take us out of the mandate of this list. Please download xerces from http://xml.apache.org along with the documents and you will see plenty of sample codes. You might also want to look at IBM's developer site (IBM created the bulk of xerces) all the best raditha Robert Mena wrote: Thanks to all (actually just one) that answered my question. Unfortunatelly I was hoping a more complete answer since the part I asked was not the main goal... bu t anyway... I'd like to ask then if the viewers could validate my new approach or at least point ways of actually implementing it. Suppose I use Xerces and tidy to turn two html files into two xhtml ones. I'd like to remove the data found between the Tags and generate two new files only with the scructure elements (tables, Br, p and so on). Then I could use regular diff from unix and if they differ in more than X% I assume they are different. Assuming that this approach is ok any tips regarding the actual implementation ? Any snippets of code would be great. __ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com -- http://www.raditha.com/php/progress.php A progress bar for PHP file uploads. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing two arrays
Michael A Smith wrote: Look at array_diff() (http://php.net/array_diff). That ought to do what you want. Yes! Thank you :) -Michael On Wed, 2003-07-02 at 10:15, Shena Delian O'Brien wrote: Hi - I have two arrays that need to be compared. I need to know if their values match or not. Currently I have: $array1 = array(a, b, c, d); $array2 = array(c, d, e, f, g); $intersect = array_intersect($array1,$array2); $num1 = count($array1); $num2 = count($intersect); Then I can compare $num1 to $num2 to see where I stand on the comparison. Less than, greater than, or equal. Only there's a problem with this if there are identical values in an array: $array1 = array(e, e); $array2 = array(c, d, e, f, g); The intersect for this returns e twice instead of the once that I need for my code. It's true that in array1 there was indeed two matches, but in array2 there was only 1 match, and that is the match that matters in my code. Does this make sense? Is there a way to do this that I'm missing...? -- Give to a good cause! * http://www.modestneeds.org/ Shena Delian O'Brien * http://www.darklock.com/shena/ The Graphics Kitty! * http://www.darklock.com/abstract/ Fantasy Age * http://www.fantasyage.com/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Comparing Data
-Original Message- From: Justin [mailto:[EMAIL PROTECTED]] Sent: Wednesday, 14 August 2002 10:52 AM To: [EMAIL PROTECTED] Subject: [PHP] Comparing Data Hello all, I've run into a problem and there has got to be a way to do this. I'm searching a mysql table and finding all rows that have the same ID. I need to output that ID, but I only want it to print once. Any help would be greatly appreciated! Justin what about something like a simple select statement eg SELECT * FROM table where id = $ID; then do something like echo $ID echo $other values. blah blah blah blah with the echo in a loop so it gets all the values.. just a thought.. Cheers -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Comparing Data
Well, the only problem is, the data will be outputted into a dropdown box, so a loop would cause duplicates of the ID. Guess I should have mentioned that there are approx 50 ID's and they are not unique. The only way I can think of doing it is something like: $foo = mysql_query($whatever) while ( mysql_fetch_row($foo) ) { if ( $id == 1 ) { $id1_count ++; } if ($id == 2) { $id2_count ++; } } if ($id1_count =1) { print This ID; } But something like that on a larger table will cause problems with server load after time (I'm assuming)... Any other possibilities out there? Thanks again. Justin At 11:17 AM 8/14/2002 +1000, you wrote: -Original Message- From: Justin [mailto:[EMAIL PROTECTED]] Sent: Wednesday, 14 August 2002 10:52 AM To: [EMAIL PROTECTED] Subject: [PHP] Comparing Data Hello all, I've run into a problem and there has got to be a way to do this. I'm searching a mysql table and finding all rows that have the same ID. I need to output that ID, but I only want it to print once. Any help would be greatly appreciated! Justin what about something like a simple select statement eg SELECT * FROM table where id = $ID; then do something like echo $ID echo $other values. blah blah blah blah with the echo in a loop so it gets all the values.. just a thought.. Cheers -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Comparing Data
On Tue, 13 Aug 2002 21:31:22 -0400, you wrote: Well, the only problem is, the data will be outputted into a dropdown box, so a loop would cause duplicates of the ID. Guess I should have mentioned that there are approx 50 ID's and they are not unique. The only way I can think of doing it is something like: [...] Any other possibilities out there? Are you just looking for duplicate ID's? If so, put the work on the SQL server, not PHP: select id,count(*) as cnt from table group by id having cnt 1 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] comparing a variable to value in DB
No trust me you're on the right track. You don't need the double == operator in the SQL query. Try something like this... $query = SELECT * FROM membersWHERE username = '$username'; $result = mysql_query($query, $db); if (mysql_num_rows($result) == 0) { echo The username i$username/u does not exist.; exit; } To check for blank fields simply ask ... WHERE username = ''. -Kevin - Original Message - From: Tyler Durdin [EMAIL PROTECTED] To: [EMAIL PROTECTED] Sent: Monday, July 29, 2002 12:46 PM Subject: [PHP] comparing a variable to value in DB I have a column in my DB named username and i am trying to compare a session ID called $username to the field in my DB called username. The way i had done it before was SELECT * from tablename WHERE Tablename.username == $username, but this does not seem to be working is there a better way to do this? Also, I would like to know how to tell if a field is blank. For example, if my SELECT statement comes back and there is no data in the username column how can i check for this? _ Send and receive Hotmail on your mobile device: http://mobile.msn.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] comparing strings does not work
strcmp returns 0 if the two strings are equal. In any case, why not just do if ($city == $city_new) $error = true; -Original Message- From: andy [mailto:[EMAIL PROTECTED]] Sent: Tuesday, June 11, 2002 9:10 AM To: [EMAIL PROTECTED] Subject: [PHP] comparing strings does not work Hi there, I would like to compare 2 strings. I do always get a 0 return (not equal) but they are difinatelly equal, I double checked it. They are just in two different vars. Here is how I did it: if (strcmp($city, $city_new) != 0) $error = true; Does anybody see the error? Or am I going the wrong way? Andy -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php