query_string

topic posted Fri, May 26, 2006 - 12:04 PM by  Linda
Share/Save/Bookmark
Advertisement
I am trying to program cgi with c++ and having a hard time
filtering text data for specific patterns( field names and data)
from the 'query_string' .
string s(getenv("QUERY_STRING"));
i recieve my string from html forms and the string will look something like
first=Fred&last=Chimp&color=Blue
assuming i the forms in the html document ask the user for their first name, last name and favorite color.
I need to go through this string and get user information and then send it back to the user for display. Any ideas on how i can accomplish this? A nudge in the right direction would be great! Huge thanks in advance!
posted by:
Linda
SF Bay Area
Advertisement
Advertisement
  • Re: query_string

    Fri, May 26, 2006 - 12:29 PM
    May I suggest simple C instead? As in char *parse_me = getenv(...

    As long as the case of keywords like first and last is always constant you can use strstr() to scan for them e.g "first=", then += the size of the keyword to point to the user input. You can use strchr() to scan for '&' to find the delimeter or know it's the remainder of the string if it's not found. This is assuming that there's no reason for error checking on the source it should be okay.

    If you can't count on the case of your keyphrase you can simply do a strnicmp(parse_me, "first=", strlen("first=")) on the input string advancing in a loop 1 char at a time until you find the keypharase.


    • Re: query_string

      Fri, May 26, 2006 - 1:27 PM

      Hypno, Linda ...

      No offense is intended, but the more I do development, the less likely I am to do string parsing in straight C unless I have no choice -- between strtok(), the non-n versions of the string APIs (strcat(), strstr(), strcmp(), etc.), it's hard to write code that isn't asking for a buffer exploit. I think using the C++ std::string class is much safer (though i'm open to other thoughts) -- you can use the std::string.find() method to help tokenize a string into component strings.

      Regards,

      John, just expressing his opinion

      Falling You - exploring the beauty of voice and sound
      www.fallingyou.com
      • Re: query_string

        Fri, May 26, 2006 - 3:35 PM
        No offense taken. It's simple, easy to implement and understand what you are doing. It's not as tidy as having everything including the kitchen sink wrapped up into a single class but I think ideal to someone learning. However, I must admit to a bias against C++ bloat. I don't really want an auto malloc(strlen(foo)) and generic magic bounds checking on every single thing and the reason for my code running fast is because somebody made a faster processor. It's possibly an excessive bias on my part. In this case, I think whatever Linda finds works best for her and you do make a valid case.
        • Re: query_string

          Fri, May 26, 2006 - 10:23 PM

          Hypno,

          I know what you mean regarding C++ bloat -- it can and sometimes does happen, though there are ways to limit it. Some intelligent buffer management classes can really help e.g. only malloc() when they really, really need to, but they're not really part of the C++ STL (the Boost ones seem pretty nice, though ... a project i'm due to start working on next week is using Boost, so i'm reading up on it).

          You also make a good point about speed, though this is actually one of the reasons I really like C++ over things like Java and C# -- C++ lets you abstract away, build templates, and do fairly high level stuff (at the cost of some CPU cycles), but when you really need to be fast, you can easily eschew the C++ STL stuff and go straight C or assembly at the lowest levels. The syntax of Java and C# may sometimes be clearer, but you pay for that -- sometimes with slow / bloaty code, almost always with the overhead of the VM, and no easy door into low-level, quick code.

          Regards,

          John

          Falling You - exploring the beauty of voice and sound
          www.fallingyou.com
          • Re: query_string

            Sat, May 27, 2006 - 10:55 AM
            Don't get me wrong. I use C++ almost exclusively. But I often see and have to deal with programs based on poorly designed classes built one on top of another. I also have to deal with memory fragmentation which doesn't really affect PC programmers. And not knowing when a malloc may be triggered from some overly intricate spaghetti code at the lowest level is a mine field.

            Most people never have to deal with how inefficient the stdlib malloc is. I recently had to work on a project where 7000+ mallocs occured every frame. And while they mostly got away with it on a "PC" and kept a 60Hz framerate that number of mallocs took more than 1/60th of a sec on the console I was working on. That meant framerate instantly went to 1/2 and had absolutely no work accomplished to show for it. Most of it doing trivial 4 byte new's. Rewriting malloc tailored to the app helped but the entire project was riddled with poor C++ design.

            People don't realize how poor their code runs unless they are forced to face the consequences of it an are too often clueless how to fix it or have progressed to the point where it's too late to fix it.

            It's extremely hard to write good assembly code on virtually any system these days. Often you end up simply optimizing what the compiler put out so you don't have to spend volumes of your time trying wrap your head around re-ordering instructions and the like. And then there's PCs where you can often give no rhyme or reason as to why one piece of code runs faster than another. You can have one piece of code, smaller, aligned and with a smaller "cycle count" that runs slower than another seemingly slower piece of code. And then you have only really optimized for one particular brand and stepping of processor.
            • Re: query_string

              Sat, May 27, 2006 - 12:10 PM

              Hypno,

              I trust from your descriptions that you're mainly an embedded systems developer? I've done a bit of that, though yes, most of the work I do is Windows / Linux / Mac OSX e.g. close to the wire, but still mainly in userland.

              Regards,

              John

              Falling You - exploring the beauty of voice and sound
              www.fallingyou.com
              • Re: query_string

                Sat, May 27, 2006 - 1:21 PM
                John,

                Actually, I work on game consoles, PS2/3/P, XBox, etc. writng the low level layers that abstracts the hardware to the app programmer and various tools on the PC. So, I'm pretty well versed on limitations when moving code from one to the other and must constantly be concerned with how efficient it is. I've worked on games pretty much exclusively since 1980 starting in assembler then moving to C/C++. I generally don't speak directly on what I do since I find myself getting bombarded with questions regarding the game industry which I'd prefer not to talk about. It's probably a good thing since I'm even more opinionated on that. :)

                I also respect your opinion and hope I haven't given a different impression. It's welcome to have a discussion on anything here.
                • Re: query_string

                  Mon, May 29, 2006 - 12:03 PM
                  thanks hypno and john for your suggestions... i will do a little experimenting and let you know wether c or c++ is going to be the best for me. There are no comprehensive books on c++ and cgi and no really good sites to learn from. will keep you guys updated and will post any questions or problems i run into. Thanks!!!!
                  linda
                  • This is the maximum depth. Additional responses will not be threaded.

                    Re: query_string

                    Mon, May 29, 2006 - 12:43 PM
                    Stop wasting your time.

                    Use something like this: www.geocities.com/SiliconVa...yacgi.html

                    Or just use PERL!
                    • Re: query_string

                      Mon, May 29, 2006 - 1:14 PM
                      is it really that difficult to program cgi with c++ ?
                      i know what i want to accomplish can be done using perl and this would save me alot of frustration but the whole point is to experimant and see how it can be done using C++...
                      you have me wondering now scott.
                      • Re: query_string

                        Mon, May 29, 2006 - 1:47 PM
                        No of course it's not difficult, as a self-proclaimed c++ guru (lol), I know enough about c++ that I would never use it for CGI. PHP or Perl is appropriate at the web server level.

                        Since it's just an experiment, then great. If I had to do this in five minutes it would look something like this:

                        class NameValuePairs {

                        std::map<std::string, std::string> values_;

                        public:

                        NameValuePairs(std::string InputString);
                        std::string GetValue(std::string Name) { return values_.find(Name) == values_.end() ? "" : values_[Name]; }
                        };

                        then your main would be

                        main() {

                        NameValuePairs nvp(argv[1]);
                        // now you've encapsulated all the named arguments and you can
                        // access them by nvp.GetValue("first") etc.
                        }

                        void Explode(std::string s, char c, std::vector<std::string>& exploded) {

                        std::string cur;
                        for(int i = 0; i < s.size(); ++i) {
                        if(s[i] == c) {
                        exploded.push_back(cur);
                        cur.clear();
                        }
                        else {
                        cur += s[i];
                        }

                        }

                        NameValuePairs::NameValuePairs(std::string Input) {

                        std::vector<std::string> args;
                        Explode(Input, '&', args);
                        for(int i = 0; i < args.size(); ++i) {
                        std::vector<std::string> np;
                        Explode(args[i], '=', np);
                        if(np.size() == 2) {
                        pairs_[arg[0]] = arg[1];
                        }
                        }
                        }





                        Done.