Ok, it's 4am, and I'm sitting here drinking my Code Red (what an appropriate name, on so many levels!), and I just finished coding a page that displays my tables for a sample application I am writing for a project (you can play with the app here if you want).

I thought I'd start a little thread where you can share some cool code you've written or found. Doesn't matter if it's pretty or ugly, complex or simple. Feel free to spread the love. I'll start out with my table display app...


I have seen a few questions in various areas on PHPB about using PHP with the SHOW command, and since I had to use it for my tables, I thought I'd share it (in the true spirit of open source, and because I occasionally like to give back to the PHPB community).

In a nutshell, I use the SHOW command to create arrays of table attributes, then iterate through the arrays to build tables. I am using it so that I visually see all of my tables, to spot any potential problems I might have with relationships.

If you'd like to see it in action, click here. There is a link on the page to view the source if you like -- feel free to steal and use any code you see there.

Anyway... it's time for bed. Please feel free to share your code with the community.

Good night.

    I think the topic should be called
    Share and Enjoy.

    I'll dig around. Pretty sure I'll turn something up...

      cool I'm currently writting a generic script to place a single integrated forum on a site maybe I'll put that up here when I'm done with it.

        Buzz, I should have called you since I was awake then too LOL.

        Hey, what happened to "Hemorrhoid Man?" 🙂 (And to prove that it was my hub's idea- he's the only one in the house that can spell "hemorrhoid" correctly.

        -Elizabeth

          I created a new function called "Prep H." As soon as I did, he disappeared! 😃

          An interesting sidenote on my project, and something that some may not know. When adding the ability to sort on different columns, I discovered an interesting thing about ENUM columns. It seems that when you sort an ENUM column, it sorts your rows according to the options defined in your column.

          For example: Let's say you have a column defined: weekday, which is ENUM('Sun':'Mon':'Tue':'Wed':'Thu':'Fri':'Sat'). In your SELECT query, you specify "ORDER BY weekday ASC". You might think the sort order was "Fri, Mon, Sat, Sun, Thu, Tue, Wed." In fact, it's ordered the same exact way the choices are presented: "Sun, Mon, Tue, Wed, Thu, Fri, Sat." Yes, this behavior is in the manual, but it's not intuitive, and not something you would think to look up.

            I have a calculator script...I'll post the code later...

            I made it from scratch and it was pain the in the a** but now it's done...at least I think it's done...maybe I should make it open-source (winking smiley).

            It has a range of different functions, from simple addition to logarithms (but the server I use only has PHP 4.1.2 so with the log() function I couldn't supply the base argument and so there's only natural log and log of 10).

            Check it out here.

            Warning: cosine and tangent take a very long time to load (partly because the PHP cosine and tangent functions are slightly flawed).

            If you like the calculator, I'll post the code and you can edit it and do whatever the hell you want to do with it (including trading it for gummi worms).

              Attributed to Solomon W. Golomb; a method for swapping the values of two integer variables without using an intermediate variable (you can tell this dates from the Elder Days, when variables were expensive!). Thanks to PHP's syntax it's also a one-liner.

              $a^=$b^=$a^=$b;
              

              Okay, here's how it goes (yeah, like I need to make content-free posts just for the sake of an increment...🙂).

              First, simplify the line; noting that = is right-associative, which means that in that line the rightmost operator is evaluated first, that the assignment operators also return the value that they assign to their lvalue, and that foo=bar is shorthand for foo=foobar:

              $a^=$b^=$a^=$b;
              
              $a^=($b^=($a^=$b));
              
              $a=$a^b;
              $a^=($b^=$a);
              
              $a=$a^$b;
              $b=$b^$a;
              $a=$a^$b;
              

              Recall what ^ does. Takes each pair of corresponding bits from its arguments (the internal binary representation of its arguments, that is), and xors them together to produce the corresponding bit of the result ("corresponding" means that the first bits of both arguments produce the first bit of the result, the second bits of both arguments produce the second bit of the result, and so on. This is why, as BuzzLY noted, it's important that both variables are the same size - demons probably start flying out of your nose if one of them runs out of bits to xor before the other. So to figure out what ^ does to a pair of variables, we only need to recap what it does to single bits

              x  y  | x^y
              ------+----
              0  0  | 0
              0  1  | 1
              1  0  | 1
              1  1  | 0
              

              Basically, xy is true if x and y are different, and is false otherwise. In other words, x is true or y is true, but they're not both true. Hence, "exclusive-or".

              Now, taking those three lines, we see what happens when $a and $b start out with initial values $s and $t.

              $a = $s;
              $b = $t;
              $a=$a^$b;
              $b=$b^$a;
              $a=$a^$b;
              
              // Since $b==$t, we substitute $t for $b for as long as $b doesn't change
              $a = $s;
              $a=$a^$t;
              $b=$t^$a;
              $a=$a^$b;
              
              // And likewise for $a
              $a=$s^$t;
              $b=$t^$a;
              $a=$a^$b;
              
              // But don't stop there!
              $b=$t^($s^$t);
              $a=($s^$t)^$b;
              
              $b=$t^($s^$t);
              $a=($s^$t)^($t^($s^$t));
              

              From the table above, it's obvious that $a$b=$b$a (if $a is different from $b, then $b must be different from $a), and that $a$a=0 ($a is not different from itself). Using those two facts, that the fact that $a0 = $a and $a($b$c) = ($a$b)$c (which I leave as exercises for the reader), we can simplify those two rather long expressions.

              $b=$t^($s^$t);
              $a=($s^$t)^($t^($s^$t));
              
              $b=$t^($t^$s);
              $a=($t^$s)^($t^($t^$s));
              
              $b=($t^$t)^$s;
              $a=($t^$s)^(($t^$t)^$s);
              
              $b=0^$s;
              $a=($t^$s)^(0^$s);
              
              $b=$s;
              $a=($t^$s)^$s;
              
              $b=$s;
              $a=$t^($s^$s);
              
              $b=$s;
              $a=$t^0;
              
              $b=$s;
              $a=$t;
              

              So after starting out with $a=$s and $b=$t, we end up with $a=$t and $b=$s. In other words, ^ swapped the each pair of bits of $a and $b with each other. Do that for all the bits and the result is one of $a and $b being swapped.

              And after all that is it any mystery why (a) XOR is such a useful operation in cryptography, and (b) learning a bit of maths (boolean algebra in this case) can be useful in programming?

              Needs pretty colours
              Nah, just shorten it.

                That's actually pretty cool... I've used that before, as you said, in the Elder Era, or as I like to call it, The Days When MS Word was a 20 Floppy Install. The dawn of CD's really was a boon to software distributors, but it sure made programmers sloppy, didn't it? Why tighten up your code if you have plenty of room on the CD?

                It's important to note that your trick really only applies to numbers. It will work with strings, too, but only if the strings are the same length. Of course, you could pad the shorter string to be the same length as the longer one, run it through your code, then trim the end variables, but that kind of defeats the purpose of minimal code. In that case, you might as well use an intermediate variable.

                It might be useful to explain what a bitwise operator is, and explain how XOR works. There are a few here that probably could use the primer. I would, but you are ever so much more eloquent than I when it comes to explaining code :p Perhaps you could do so by editing your post? Unless you are trying to pad your post count, that is 😃

                  i'll post my old newb-mistake-laden template class if you guys want it... or are you just looking for good interesting code?

                    Anything you think people might find useful or interesting. There are no egos here in this thread. Show off all you want, and we'll all ooh and ahh 🙂

                      Well I'd really like to keep this thread going, and while I prolly have nothing in PHP of any real interest (yet), here's a lil Javascript clock...

                      <body onLoad="clock()">
                      <span id="theClock" style="position:absolute;left:300;top:20;"></span>
                      <script language="JavaScript">
                      function clock() {
                      	if (!document.layers && !document.all) return;
                      	var digital = new Date();
                      	var hours = digital.getHours();
                      	var minutes = digital.getMinutes();
                      	var seconds = digital.getSeconds();
                      	var amOrPm = "AM";
                      	if (hours > 11) amOrPm = "PM";
                      	if (hours > 12) hours = hours - 12;
                      	if (hours == 0) hours = 12;
                      	if (minutes <= 9) minutes = "0" + minutes;
                      	if (seconds <= 9) seconds = "0" + seconds;
                      	dispTime = hours + ":" + minutes + ":" + seconds + " " + amOrPm;
                      	if (document.layers) {
                      		document.layers.theClock.document.write(dispTime);
                      		document.layers.theClock.document.close();
                      	}
                      	else
                      		if (document.all)
                      			theClock.innerHTML = dispTime;
                      	setTimeout("clock()", 1000);
                      }
                      </script>

                      BTW...I know the feelin Buzz...it's about 1:30 AM right now, and I'm bored and drinking my Mountain Dew 🙂

                        Occasionally one wants to alter some text - except for parts that match some sort of pattern, e.g., URLs. Rather than faff around with regexps that try to figure out whether a certain piece of the text is part of the pattern or not and blahblahblah, it's probably easier to take the bits that shouldn't be changed out of the text, then put them back after the alterations.

                        Here's a wee function that does the taking-out part of the job.

                        function protect_from_borking($find, &$contents, &$placeholders, &$text)
                        {	static $n=0;
                        	$count=0;
                        	while(preg_match($find, $text, $matches))
                        	{	$contents[$count]=$matches[0];
                        		$placeholders[$count]="@@".$n."_".$count."@@";
                        		$text = preg_replace($find, $placeholders[$count], $text, 1);
                        		++$count;
                        	}
                        	++$n;
                        }
                        

                        The name is what it is because I lifted this bodily from my Børkinator ][ script, in which it is used to protect various pieces of vBulletin posts of various types from having their vowels børked (e.g., the 'o' and 'a' of &oslash;, or the 'o' and 'e' of

                        , or all the vowels within [noparse][code=php][/noparse] blocks).
                        
                        Now, for it to be used, note that four parameters ought to be supplied: [list][*][b]$find[/b] contains a regexp pattern that matches the sort of text one wants to protect. If, for example, you don't want to touch anything between <b>...</b> tags, the pattern would be #<b>.*?</b>#. Note that the entire match is stored, so in this example, the b tags themselves would be protected.[*][b]&$contents[/b] is a reference to an array that should be empty when the function is called. After the function is completed, it will contain all the protected text that has been taken out.[*][b]&$placeholders[/b] is also initially empty, and afterwards contains copies of all the text that the corresponding entries in $contents have been replaced by.[*][b]&$text[/b] is of course a reference to the text being worked on.[/list]
                        
                        To Use:
                        Well, the linked thread above shows an example of its use. First thing to note is that before using it, I did a little something to make sure that the string "@@" could never appear within the text. That is because I use "@@" to mark the beginning and end of the placeholders used to protect text. Afterwards of course, the "@" signs are all unescaped again.
                        
                        The function above takes text [i]out[/i] - after altering the remainder we want to put those protected bits back in. That's easy. PHP has a function for it:
                        [code=php]
                        $text = str_replace($placeholders, $contents, $text);
                        

                        The function may be used to protect several different classes of thing: this helps simplify the task of determining appropriate regexps, because you don't need to write one regexp to do everything. It automatically makes sure that each call to the function produces different placeholders by using a static variable $n which in effect counts how many times the function has run, and using that number in the placeholders it generates.

                        Needless to say, this code is not limited to børking. I actually got the kernel of the idea from reading the Bugzilla source, to which I added a couple of refinements of my own.

                          Well....to get completely ouside the norm here.....here's a little code snippet I have to make an ascii chart in mIRC. Promise when I make some cool PHP I'll post it here too 🙂

                          //ascii chart dialog for mIRC
                          on *:load: echo -s $colour *** ASCII Chart loaded
                          alias ascii dialog -m ascii ascii
                          dialog ascii {
                            title "ASCII Chart"
                            size -1 -1 300 400
                            option pixels
                            tab "32-127", 501, 10 10 280 350
                            tab "128-255", 502
                            list 503, 20 40 260 300, tab 501
                            list 504, 20 40 260 300, tab 502
                            text "Doubleclick on an item to copy to clipboard", 505, 10 375 210 20
                            button "Close", 605, 225 375 50 20, ok 
                          }
                          alias -l _asciimake {
                            var %a = 32, %b = 128
                            while (%a < 128) { did -a ascii 503 %a $+ : $chr(%a) | inc %a }
                            while (%b < 256) { did -a ascii 504 %b $+ ; $chr(%b) | inc %b }
                          }
                          on *:dialog:ascii:init:0: _asciimake
                          on *:dialog:ascii:dclick:503: var %a = $did(ascii,503,$did(ascii,503).sel) | clipboard $gettok(%a,2,32)
                          on *:dialog:ascii:sclick:504: var %a = $did(ascii,504,$did(ascii,504).sel) | clipboard $gettok(%a,2,32)
                          

                            Those are great snippets, LordShryku, but yes, I meant this thread to be related to PHP.

                            Here is another tool some of you may remember from another thread:

                            Color Picker &bull; View Source

                            There is room for improvement (like using GD library to make images instead of using a Windows-only font). If you do modify it, let me know -- I'd love to see it!

                              Just trying to keep the thread going. This is a great idea, so I'll go come up with something in PHP I can bring to the table 🙂

                                here ya go...... goog god this is old, from like may. i'd almost forgotten about it.......

                                  Urm...

                                  <?php
                                  echo phpinfo();
                                  ?>

                                  Does that count ??

                                  But in addition to that... the attached displays an e-mail message of (almost) any variety, and also includes inline images...

                                    Okay, this one is only useful if you don't want to do any error checking, but you can make it a bit more robust with a bit of work. It's mainly a silly little bauble to show off preg_replace()'s /e modifier.

                                    It's a recursive template-evaluation function: file inclusions are specified by the syntax [%filename%], and the included files may of course themselves include files in the same way (Like I said: No Error Checking. I've never actually used it). You kick it off with some text that already contains some inclusions. It might be amusing to work out which order the substitutions are made in. Then again, it might not. Depends on what turns you on, I guess.

                                    function file_inclusions($text)
                                    {	return preg_replace
                                    		("/\[%(.+?)%\]/e",
                                    		"file_inclusions(file_get_contents('$1'))",
                                    		$text);
                                    }

                                    [Edit: Good grief, I just tried it and it actually works!]

                                    [Edit: Ten Years Later... the /e modifier is deprecated as of PHP 5.5 in favour of [man]preg_replace_callback[/man] - like eval(), it's way too powerful and dangerous and evil to be allowed out (it's all too easy to inject arbitrary code that will be evaluated).]

                                    [Edit: Later still... the /e modifier is gone.

                                    function file_inclusions($text)
                                    {
                                    	return preg_replace_callback("/\[%(.+?)%\]/", function($m)
                                    	{
                                    		return file_inclusions(file_get_contents($m[1]));
                                    	}, $text);
                                    }
                                    

                                    ]

                                    [Edit: even later than that... Arrow functions exist

                                    function file_inclusions($text)
                                    {
                                    	return preg_replace_callback("/\[%(.+?)%\]/",
                                    		fn($m) => file_inclusions(file_get_contents($m[1])),
                                    		$text);
                                    }
                                    

                                    ]

                                      Here's a little script that returns the highest common denominator (think that's what it's called) handy for making nice to display ratios eg "The uploaded image mus have a ratio of 4:6"

                                      <?
                                      function get_divisor($x, $y) 
                                      { 
                                        if($x%1!=0 || $y%1!=0) 
                                          return false; 
                                        for($i=($x>$y?$y:$x);$i>0;$i--) 
                                        {
                                          if($x%$i==0 && $y%$i==0)
                                            return $i;
                                        }
                                      }
                                      ?>

                                      Also here's a little class from the Wrox Pro PHP4 book which I find very handy for profiling scripts

                                      <?
                                      class timer
                                      {
                                          var $timers = array();
                                      
                                      function timer()
                                      {
                                          // Nothing
                                      }
                                      
                                      function timerStart($name = 'default')
                                      {
                                          $time_portions = explode(' ',microtime());
                                          $actual_time = $time_portions[1].substr($time_portions[0],1);
                                          $this->timers["$name"] = $actual_time;
                                      }
                                      
                                      function timerStop($name = 'default')
                                      {
                                          $time_portions = explode(' ',microtime());
                                          $actual_time = $time_portions[1].substr($time_portions[0],1);
                                          $elapsed_time = bcsub($actual_time, $this->timers["$name"], 6);
                                          return $elapsed_time;
                                      }
                                      }
                                      ?>

                                      Cheers
                                      Rob

                                      [Edit] Changed for loop to work down to first match. Fewer iterations required. I haven't tested this version though

                                        A little counter I made up...easy stuff...uses an external file...
                                        counter.txt holds the number of hits to the site...extremely simple stuff. This also uses a cookie so that you can't make the hits increment by just hitting the 'refresh' button over and over again.

                                        <?php
                                        $countercookie=$_COOKIE["countercookie"];
                                        $filename="counter.txt";
                                        $resource_handle=fopen($filename, 'r+');
                                        $size_of_file=filesize($filename);
                                        $number_of_hits=fread($resource_handle, $size_of_file);
                                        if (!isset($countercookie)) {
                                             @setcookie("countercookie","cookiefromme",time()+60*60*24,"/");
                                             $number_of_hits++;
                                        }
                                        ftruncate($resource_handle, 0);
                                        fwrite($resource_handle, $number_of_hits);
                                        print "This webpage currently has ".$number_of_hits." hits.";
                                        fclose($resource_handle);
                                        ?>
                                        

                                        Pretty simple eh? Use at will.

                                        [edit] made a correction...should truncate file to zero bytes [/edit]
                                        [edit2] made another correction...indenting and $number_of_hits++; [/edit2]