• D. T. North (unregistered)

    Okay, so I realize I'm not a PHP Pro. But I consider myself somewhere around the top of the bell curve, if not slightly in front based on experience alone. So when I was trying to trace those functions, I going nuts. I was really having trouble understanding the purpose.

    Then I read the last line about using $_GET, $_POST, etc, and realized why I was having trouble. With globals like $_GET and so on, I never once considered doing it any differently.

    So I learned two things from this article:

    1. When trying to trace another person's script, it's best to ignore all logic and reason (a lesson easily learned from any WTF here).

    2. Thought it's really useless to know in practice, I now know an alternative to $_GET and $_POST. But I'm going to make a conscious effort to forget the alternative as soon as I'm done this post.

    Yay for learning.

    (PS - this is the first time I've read CodeSOD because PHP and Perl are the only languages I know. There should be sub-categories for CodeSOD so that I can see what the language is at a glance).

  • Harry (unregistered) in reply to Chucara
    Chucara:
    You're laughing now, but all your code will break when they change the syntax of '<', '>' etc. With this code, you'll only have to replace it in one function.

    Brillant!

    With operator overloading catching on, this function seems like a good idea.

  • mab (unregistered)

    the truth function is buggy should have been :

    function truth($fieldValue)
    {
        if ($fieldValue == "no" || $fieldValue == "false" || $fieldValue == "off" || $fieldValue == "FileNotFound") {
            return false;
        } else {
            return $fieldValue;
        }
    }
    
    
  • Felix (unregistered)

    In principle the queryStringToArray() is not such a horrible thing. The crime is not using prarse_str() for this. Although sometimes you may want your own function to behave slightly differently or do less with better performance.

  • Edward Royce (unregistered)

    Hmmmm.

    Shit. I knew this was a bad time to start programming in PHP.

  • Trevor (unregistered)

    The == and >= operators are used far too often. Here is an "Enhancement":

    function MatchField($field, $cond, $value) { if ($cond == '==') return $field == $value;

    if (MatchField($cond, '==', '<'))
        return $field < $value;
    if (MatchField($cond, '==', '<='))
        return $field <= $value;
    if (MatchField($cond, '==', '!='))
        return $field != $value;
    if (MatchField($cond, '==', '>='))
        return $field >= $value;
    if (MatchField($cond, '==', '>'))
        return $field > $value;
    
    if (MatchField($cond, '==', 'like'))
        return MatchField(indexof("$field", "$value"), '>=', 0);
    if (MatchField($cond, '==', 'in'))
        return MatchField(indexof("$value", "$field"), '>=', 0);
    
    return false;
    

    }

  • Andrew (unregistered) in reply to ParkinT
    ParkinT:
    snoofle:
    Forgive me as I am PHP challenged:

    so: truth('Absolutely No Fucking Way') and: truth('FALSE')

    both yield true?

    That is correct. Actually, his function only tests for FALSEHOOD. Of course, specific cases of falsehood ("no", "false", "off").

    I think it's optimistic that he finds truth in everything but no, false, & off. That's very open-minded.

  • Just Some Guy (unregistered) in reply to real_aardvark
    real_aardvark:
    But that's hardly enterprisey at all, is it? I mean, the operator is a literal, for gawd's sake.

    Real Enterprisey (c) would be as follows:

    if (MatchField($login->Value("admin"),
                         $db->getOperator (__FILE__, __LINE__),
                         "1")) {

    This allows for instant configurability via a database, and has the added benefit that you can add distributed grid networking by ensuring that $db refers to an object encapsulating some sort of RPC.

    I'm still a little concerned about the "1" though.

    "1" is a macro that uses a SOAP call to GetCurrentConstantValues() on the Sunfire.

  • iulian (unregistered) in reply to Chucara

    Of course, i started immediately to search whole my code about logic like these. Of course, I will not show here the search result :D, it's a shame for me, but instead I taken a long vacation to rewrite all my code to be ready for revolutionary changes such as definning function =2+)( when equal meaning adding in reverse mode to the to objects initialization like US$ = old Eur(paramsurgeon). So hold on forever. The bugs and new crazy ideas it's the most old species from the world.

  • (cs) in reply to Just Some Guy
    Just Some Guy:
    real_aardvark:
    But that's hardly enterprisey at all, is it? I mean, the operator is a literal, for gawd's sake.

    Real Enterprisey (c) would be as follows:

    if (MatchField($login->Value("admin"),
                         $db->getOperator (__FILE__, __LINE__),
                         "1")) {

    This allows for instant configurability via a database, and has the added benefit that you can add distributed grid networking by ensuring that $db refers to an object encapsulating some sort of RPC.

    I'm still a little concerned about the "1" though.

    "1" is a macro that uses a SOAP call to GetCurrentConstantValues() on the Sunfire.

    I'm disillusioned.

    I was rather hoping that it would be expressed through an embedded lisp interpreter, like so:

    (())

    Absolutely no side-effects or assumptions whatsoever. It's magic!

  • AdT (unregistered) in reply to Kuba
    Kuba:
    Disclaimer: I fail to see the sarcasm.

    So, um, this isn't C/C++. In php, there only way to get memory leaks is by doing known (hopefully) no-nos, such as circular references. php is a latent-typed, garbage collected language, you know...

    Thanks for mentioning one way to produce memory leaks in language runtimes with reference-counting pointers - circular references. There are of course many more, and most others also affect runtimes with marking gc algorithms such as keeping too many references in globally scoped containers or forgetting to explicitely unregister observers. I've seen many memory leaks caused by these issues in both Java and .NET. (Java is at least smart enough to use WeakReferences for its own event handling - this can in turn cause objects to be collected prematurely but that's arguably the lesser problem.)

    Garbage collection prevents memory leaks by freeing objects that are no longer needed, right? Wrong, you fscking retard! Garbage collection frees objects that are no longer referenced rsp. reachable from the stack and static variables. Modern filesystems do not keep unreachable data around either, so why's your hard disk always full? Because you are keeping a lot of references to data that you no longer need, that's why.

    There's nothing wrong with garbage collection (although it's rarely necessary in modern C++), but there's something seriously wrong with all the Java/PHP zombies who think gc solves all memory problems and then go on to write the most incredibly resource hogging PoS applications ever to roam the Internet.

    Oh, and by the way, C++ has had reference-counting smart pointers for a long time, e.g. boost::shared_ptr. And those are actually a lot more versatile than anything PHP has come up with so far.

    Kuba:
    As for wastefulness, a good compiler can do compile-time evaluation of certain functions, and this one would be a good candidate. Although such optimizations are more common in languages where the compiler can interpret the code during compilation (Scheme, Lisp, ...), php (just as any other language system) could in principle optimize this function out as follows:

    The word you are looking for is "inlining", something that C and C++ compilers (and even some linkers) have supported for a long time as well. And, by the way, isn't it rather ironic to mention PHP and good compilers in one sentence? I'm not saying that there couldn't be a good compiler for PHP in theory. But in practice, there isn't. PHP is still dog slow compared to "bare metal" languages like C/C++.

  • Sheepy (unregistered) in reply to Chucara

    It'll break earlier then that, namely when when long var is gone.

    So I guess we'll get many other laughters before they change the syntax for '<

  • (cs) in reply to real_aardvark
    Ben:
    You know, because why use $_GET, $_POST, or $_REQUEST? ...This is going to be a long project.
    Because when the PHP script is embedded in HTML using the Apache <!--#include --> directive, where the HTML page has parameters on the URL, it will not give you the data in $_GET or $_REQUEST. I'm not saying he/she did a brilant job - but I do defend the need to sometimes parse a query string.
  • DrSolar (unregistered)

    Quick question from someone who found TDWTF recently, why the railing against PHP? I'm not defending it necessarily, just wondering why.

  • Dave (unregistered) in reply to Renoir
    Renoir:
    ...but you see, my new, improved, wheel's much better. It's only got four sides. And if you leave it on a hill, it doesn't roll away...

    Its a tetrahedron?

  • (cs) in reply to AdT
    AdT:
    There's nothing wrong with garbage collection (although it's rarely necessary in modern C++), but there's something seriously wrong with all the Java/PHP zombies who think gc solves all memory problems and then go on to write the most incredibly resource hogging PoS applications ever to roam the Internet.

    Oh, and by the way, C++ has had reference-counting smart pointers for a long time, e.g. boost::shared_ptr. And those are actually a lot more versatile than anything PHP has come up with so far.

    Kuba:
    As for wastefulness, a good compiler can do compile-time evaluation of certain functions, and this one would be a good candidate. Although such optimizations are more common in languages where the compiler can interpret the code during compilation (Scheme, Lisp, ...), php (just as any other language system) could in principle optimize this function out as follows:

    The word you are looking for is "inlining", something that C and C++ compilers (and even some linkers) have supported for a long time as well. And, by the way, isn't it rather ironic to mention PHP and good compilers in one sentence? I'm not saying that there couldn't be a good compiler for PHP in theory. But in practice, there isn't. PHP is still dog slow compared to "bare metal" languages like C/C++.

    I'm not a huge fan of anonymous posters who appropriate the moniker of a registered poster, but let that pass.

    Kuba is perfectly correct to state that "in principle" (his words) a PHP interpreter/compiler/magic box could optimise/inline this code. That's just the start, in fact; I refer you to Steve Yegge's latest post for other interesting possibilities. "In principle" is good enough. You expect him to go away and rewrite PHP5 just to prove his point? Gee, you're a hard task-master.

    Dog-slow isn't necessarily important. Pig-ugly is, as far as I'm concerned. Many people (not I) would claim that C and C++ fit this description just as well as PHP does.

    I used to get all steamed up about this fetish people have for garbage collection. "What's the big deal?" I cried. "Where's the determinism?" I moaned. "Memory isn't the only resource you can leak," I whined, "and it's not even the most important one."

    Well, I still think I was right, but I'm interested in the second generation of language support for gc. And no, I'm not talking about "generational garbage collectors," because they're not part of the language support. I'm talking about:

    (1) Strong references (2) Weak references (3) Soft references (4) Phantom references

    Excuse me, but wasn't the whole idea of gc that it takes all the pain of thinking about this stuff away from the programmer? What's the point of a promise like that if we're all forced to deal with arbitrary abstractions, rather than something concrete and intelligible like RAII and Boost smart pointers?

    I'm obviously missing something here.

  • Tamahome (unregistered)

    It lacks a FILE_NOT_FOUND statement...

  • Anonymous (unregistered) in reply to DrSolar
    DrSolar:
    Quick question from someone who found TDWTF recently, why the railing against PHP? I'm not defending it necessarily, just wondering why.
    Because I write and maintain PHP for a living, and thus realize that it's one of the ugliest languages imaginable.

    PHP is kind of like a language where someone actually tried to break every convention and standard practice possible.

  • SD (unregistered)

    queryStringToArray... not so weird.

    Yes, there's a built-in function for it, but PHP has so many of the damned things that it's quite easy to miss them.

    That implementation isn't that bad either - pretty typical of newbie PHP developers, using just the basic builtins. He forgot about URL encoding though, and I can't work out what $GL_strlen and $GL_strpos are for.

    Disclaimer: I've written a function similar to that, working on similar principles, except without the $GL_ crap, and passing everything through urldecode after it was split up.

    As for it's use... I only needed it because I was extracting information from URLs which were in turn extracted from HTML files, and replaced that with parse_url once I found out about it.

    I can think of no use for it in a typical web app though.

  • jed (unregistered)
    (*---------------------------------------------------------------------------
      Procedure:   IsTrue
      Author:      jed
      Date:        26-Aug-2003
      Description: useful for determining the boolean result of an expression
    ---------------------------------------------------------------------------:*)
    function IsTrue(Expression: TExpression): Boolean;
    var
      ResultHasBeenSet: Boolean;
    begin
      Result:=(Random(2)=0)=True;
      ResultHasBeenSet:=False;
    
      // if the expression is true then the result will be true, otherwise (since the
      // expression couldn't be true) the result will be false.  There are no other
      // mathematical possibilities
      begin
        if (Expression=True) then
        begin
          Result:=True;
          ResultHasBeenSet:=True;
        end;
    
        if (Expression=False) then
        begin
          Result:=False;
          ResultHasBeenSet:=True;
        end;
      end;
    
      // need to set the result if it hasn't been set yet, we'll randomly decide true or false
      // because there should be no bias.
      if IsTrue(ResultHasBeenSet)=IsTrue(0=1)
        then Result:=((Random(2)=Random(2))=True)
        else Result:=(Result=True);
    
      // P.S.
      //   This function could also be adapted to tell you if some expression is false
      // by prefixing the expression (or the result) with the 'not' operator.  You can
      // find out more about the 'not' operator in the online help.
    end;
  • Ben (submitter) (unregistered) in reply to Coditor
    Coditor:
    Ben:
    You know, because why use $_GET, $_POST, or $_REQUEST? ...This is going to be a long project.
    Because when the PHP script is embedded in HTML using the Apache <!--#include --> directive, where the HTML page has parameters on the URL, it will not give you the data in $_GET or $_REQUEST. I'm not saying he/she did a brilant job - but I do defend the need to sometimes parse a query string.

    Trust me, there were no server-side includes. This is strictly bad coding.

  • Boris Johnson (unregistered) in reply to Mhendren
    Mhendren:
    It is unlikely that PHP would change the meaning of "<", ">", or "==".

    PHP being PHP though,it is easily conceivable that they would deprecate those operators in favor of (respectively) "lessThan", "is_greater_than", and "equals"

    And that, ladies and gentlemen, gets my vote for best comment on this post.

  • Jono (unregistered) in reply to Chucara
    Chucara:
    You're laughing now, but all your code will break when they change the syntax of '<', '>' etc. With this code, you'll only have to replace it in one function.

    Brillant!

    Years later we will look back on the original coder as a visionary. That last function had me in tears (tears of joy, and dismay).

  • anonymous workaholic (unregistered) in reply to AdT

    Googling for PHP compiler reveals that there actually are native PHP compilers. If you used one of those, counting native machine instructions could sometimes be even justified, if you were trying to do something performance critical... in PHP.

  • Andrei Rinea (unregistered)

    You could just as well rewrite the + operator, couldn't you?

    (C# code)

    public int Add(int a, int b) { int result = a; for(int i = 0; i < b; i++) { result = result + 1; } return result; }

  • (cs)

    I have it on good authority that next version of PHP will replace "=" with "CANHAS".

  • Some Jerk (unregistered)

    Further evidence that some people should not be permitted near a computer at any price. You don't suppose that he used some tutorial and recreated methods that were designed to "test" php features so that a noob can figure out wtf (s)he is doing do you?

    CAPTCHA: transverbero => it is the frequent boosts to my vocabulary that prevent me from using my login!

  • Some Jerk (unregistered)
    we:
    ... BUNCH OF URLS ...

    what do you know... a wtf on the wtf site. ...

    DIE SPAMMER!

    Captcha: oppeto ... the sound a VW bug makes in a tunnel... ?

  • (cs) in reply to Samah
    Samah:
    I have it on good authority that next version of PHP will replace "=" with "CANHAS".
    Which is not nearly so exciting as replacing "!=" with "File_mightNotBe_Found."

    Actually, I'm looking forward to PHP7 and the inevitable replacement of "===" with "Its_alreadyStored_inMemory_As_aString_comma_dimwit_WhatPartof_comparison_DontYou_Understand_query"

  • (cs) in reply to Some Jerk
    Some Jerk:
    we:
    ... BUNCH OF URLS ...

    what do you know... a wtf on the wtf site. ...

    DIE SPAMMER!

    Captcha: oppeto ... the sound a VW bug makes in a tunnel... ?

    Was 'st? Sie denken, das "Spamm" neutrum ist? Erscheint mir möglich, aber mit einem Umlaute nur...

  • Jaap (unregistered) in reply to Chucara

    Nevertheless: what if they change the semantics of the function call???????????

  • Dynom (unregistered) in reply to Chucara

    I'm sooooo hoping you are making a joke Chucara...

  • DarkDust (unregistered)

    I have another one: I had to help a customer extend and improve a GUI for an industry robot arm. The stuff was written in C# (luckily my last excursion into MS land) and the developer at the customer site held a degree in CS, as far as I remember, but he couldn't program his way out of a paper bag. My favorite function from him is this (no, I'm not making this up):

    bool isOdd(int num)
    {
    	bool odd = false;
    	for(System.Int32 s = myInteger; s > 0; s--)
    	{
    		if(!odd)
    		{
    			odd = true;
    		}
    		else
    		{
    			odd = false;
    		}
    	}
    	
    	return odd;
    }
    

    There were more of these "gems", and I was quickly able to improve the speed and responsiveness of this application dramatically. What I found really frightening was the fact that this guy was also responsible for the robot arms' firmware !

Leave a comment on “wtflib.php”

Log In or post as a guest

Replying to comment #:

« Return to Article