Archive for the ‘PHP’ CategoryOne of my friends who has used PHP in the past, but hasn’t touched it in a while, recently asked me what the best was to handle mass edits and deletions on a page. To understand more what he’s talking about, he has a form with a table of data, each containing checkboxes in a column labeled as Delete? He wants to know how he should handle the deleting multiple rows in a fast and efficient way. How it may have been done (and you may be doing it right now) might look like this: <form action="deleteCategories.php" method="post"> <input type="checkbox" name="deleteCategory1" /> Category 1<br /> <input type="checkbox" name="deleteCategory2" /> Category 2<br /> <input type="checkbox" name="deleteCategory3" /> Category 3<br /> </form>
The above code is highly inefficient, and if you’re dealing with database records, I honestly don’t see how your application would survive. You would have to add lines to deal with other records, which would make your application severely crippled, or extremely difficult to maintain - one of the two. The solution to this is simple: use an “HTML Array”. When I say this, some people who have spent their lives working in HTML are going to say that HTML doesn’t have arrays. Of course they don’t. It’s PHP, though, that does. However, you have to pass to PHP the “array” in a certain fashion so that when it loads up it’s scripts, it knows its an array. Here’s how it works. In PHP, arrays are usually written to and read from like this:
So, in HTML, how on earth do you do arrays? You don’t have an <form action="deleteCategories.php" method="post"> <input type="checkbox" name="delete[category][]" value="1" />Category 1<br /> <input type="checkbox" name="delete[category][]" value="2" />Category 2<br /> <input type="checkbox" name="delete[category][]" value="3" />Category 3<br /> </form> What you see is I’ve named the checkbox fields the same name. In normal HTML land, this would be a no-no, and there’s a way to get around it if it doesn’t validate. That is, you simply switch to the following: <form action="deleteCategories.php" method="post"> <input type="checkbox" name="delete[category][1]" />Category 1<br /> <input type="checkbox" name="delete[category][2]" />Category 2<br /> <input type="checkbox" name="delete[category][3]" />Category 3<br /> </form> Now each checkbox has it’s own name and doesn’t overlap with others. We’ll consider the first HTML set case 1 and the second case 2. Here’s where the true PHP “magic” takes over and makes this a really powerful solution. You don’t have to then check and delete with the following code:
The above code is horrible. If you’re currently writing code like that above, slap yourself in the face with a nice wet fish. You’re about to get a rude awakening. Here’s how you’re actually going to use it:
In either case, only the checkboxes that are selected come through as the array, but in either case, PHP converts what looks like a name with special characters in HTML to an actual PHP array. It’s very powerful and you can script code to handle what you need to and not have to worry about adding or changing it as your database grows. It never ceases to amaze me how many outside dependencies there are for PHP. When trying to get a PHP application to connect to an LDAP server over SSL, you have to have the following:
Yes, but once you have all that done, then you need to hope and pray that it will connect successfully. On a Linux server, this is definitely a possibility (but a treacherous task at that). On a Windows machine: forget it. You might as well count your losses and start coding your application in .Net before you try connecting to an LDAP server via SSL with a Windows box (that or you need to be really good at compiling opensource software on Windows machines). The ErrorSo, here’s the error message I’m getting in my PHP app: Warning: ldap_bind(): Unable to bind to server: Can't contact LDAP server. Pretty generic error message right? It can be anything. I’m guessing, though, that it’s something with OpenLDAP. That’s why it comes with the wonderful tool `ldapsearch`. This _should_ help me figure out if it’s an application problem or a OpenLDAP problem. neraath:~/> ldapsearch -b ou=people,dc=example,dc=com -H ldaps://host.example.com searchMailbox=neraath ldap_sasl_interactive_bind_s: Can't contact LDAP server (-1) Once again, a pretty generic error message. If you try to Google that error message, you’re not gonna get anywhere. This is where OpenLDAP’s debugging switch turns out to be quite handy. My favorite: `-d 7`. Watch it in action: neraath:~/> ldapsearch -b ou=people,dc=example,dc=com -d 7 -H ldaps://host.example.com searchMailbox=neraath ldap_create ldap_url_parse_ext(ldaps://host.example.com) ldap_pvt_sasl_getmech ldap_search put_filter: "(objectclass=*)" put_filter: simple put_simple_filter: "objectclass=*" ldap_send_initial_request ldap_new_connection ldap_int_open_connection ldap_connect_to_host: TCP host.example.com:636 ldap_new_socket: 3 ldap_prepare_socket: 3 ldap_connect_to_host: Trying IP.ADDRESS.HIDDEN.HERE:636 ldap_connect_timeout: fd: 3 tm: -1 async: 0 ldap_ndelay_on: 3 ldap_is_sock_ready: 3 ldap_ndelay_off: 3 TLS: could not load client CA list (file:`',dir:`/etc/apache2/ssl.crt'). TLS: error:0906D06C:PEM routines:PEM_read_bio:no start line pem_lib.c:642 TLS: error:0906D06C:PEM routines:PEM_read_bio:no start line pem_lib.c:642 TLS: error:0200100D:system library:fopen:Permission denied bss_file.c:278 TLS: error:20074002:BIO routines:FILE_CTRL:system lib bss_file.c:280 ldap_perror ldap_sasl_interactive_bind_s: Can't contact LDAP server (-1) Lo-and-behold the answer becomes evident: TLS: could not load client CA list (file:`',dir:`/etc/apache2/ssl.crt'). I change the /etc/openldap/ldap.conf file line ‘TLS_CACERTDIR /etc/apache2/ssl.crt’ from what it is to ‘TLS_CACERTDIR /etc/ssl/certs’. I re-run the above command and it prompts me for a password. This is definitely a good sign. Running it again in my PHP code? Of course not. Step 2: Google Some MoreAfter more wonderful Googling for the most generic PHP error possible, I find that the problem may potentially be the certificate (view the thread). So, I decide to try to figure out how to actually view the certificate that’s on the server (in case it is self-signed or not trusted, somehow). This takes me the better part of half an hour, but I finally figure out the openssl command necessary to view the public key / certificate of a service: openssl s_client -connect host.example.com:ldaps This gave me the public key necessary to save and then place in at /etc/ssl/certs/host.example.com.pem. After doing so, I ran `c_rehash` and then modified my /etc/openldap/ldap.conf file. I added the following lines to the config: URI: ldap://host.example.com TLS_CACERT /etc/ssl/certs/host.example.com.pem After restarting Apache and testing the PHP file, things seem to be going a little smoother. No more connect errors. I will update if something goes awry, though. I’m here in Austin, TX today at the SANS: Web Application Security Workshop (I was also here yesterday, too). I hope to be able to provide an accurate review for this nearly worthless workshop that many of us from CIS Customer Applications are attending. There are a couple of individuals who believe that the information being taught here is somewhat worthwhile, but most of us from the group either know everything that’s been taught so far, or find some of the information being taught doesn’t relate to us. For a quick synopsis, here’s what I would have to say: If you are a intermediate or experienced developer, you will be absolutely bored with this workshop. If you are an executive who has not much technical know-how, but want to learn about security for your web applications, this is a worthwhile program for you to attend. Be aware, however, because there are some things that executives don’t need to (or don’t care to) learn about in this. Regardless, this is the most watered down version of a so-called technical workshop I’ve ever been through. Read on to find out how ridiculous some of the things we learned were. Okay, so now that I have a chance to blog about what I thought of the conference overall, I figured that I would do it and get it out of the way before I forget and/or run out of time during the week to do it. I attended a session today on PHPUnit, the PHP framework for testing your code. I felt as though this was a significant software solution that must be talked about, considering I’d never heard of it before. Before I begin though, and so others are aware of the general gist of stuff that was talked about at the conference, I want to go over the main “Themes” that the conference talked about. The overall theme was “Creating Modern Web Applications with PHP”. Within that, the sessions and tutorials were broken into 3 different tracks. They were:
A track that was frequented by many was the PHP and Web Services track. Web Services are nothing new, but they certainly are becoming a big thing. If not used for a greater good (ie: Flickr Services, Google Code, etc.), then Web Services are something that are necessary in AJAX based programming. For AJAX based websites, small XML datafeeds are sent with requests to the server, and the server responds with a small XML datafeed - thus, we have a Web Service, only on a smaller scale. But that’s not the point of this blog post. I wanted to go into the PHP Development and PHP Management tracks. As I put on my first blog post about the “PHP Development Best Practices” tutorial, there were several important things that were mentioned in that lecture. One was documentation - something that has been fronted as long as I have been doing programming. The other, however, was properly testing your code. Now, at OSCON, this was hardly mentioned at all. Speakers either assumed you were testing or just decided not to mention it. Nevertheless, testing was a key component in the development and management aspect of the Zend/PHP Con. So, what is meant by testing? Do we just type some code, hit refresh, and expect it to work? No. The PHP5 coding methodology is going in the way of OOP. Thus, making a change to a page which is strictly OOP and no spaghetti code will simply make your debugger scratch it’s head because it doesn’t know where to begin. This is where Unit Testing is coming in. Unit Testing (though seemingly been around for a while) will test each specific function and class to verify the output came out as expected. So, this is cool, but does this mean you have to write extensive code to test your already massive bits of code? The answer is No. This is what PHPUnit is for. PHPUnit is, again, a framework which you build on top of to run the Unit Tests on your PHP5 code. When you tell PHPUnit to do it’s thing, it will run through the tests as you have set them up and will tell you if any fail. My opinionsThis is a truly marvelous idea. Although I’ve been doing PHP coding for ~3 years now, I had never known something like this existed, but now with all of the new knowledge gained about PHP5 and coding styles, I’m certain to go straight to implementing this in our code. I’m very excited as I can look forward to decreased testing times and more productivity. Now if I could only convince my boss that we need to start moving the OOP way… Well, I’ve been at the Zend/PHP conference in San Jose, CA since Sunday. The tutorials began on Monday, and with the beginning, I recognized a HUGE diversity gap. There were plenty of Americans, Canadians and Britans who were speaking English, but as I sit here typing this there are 3 individuals speaking French (could be Canadian and not French individuals, don’t know specifically). Additionally, there is a lot of Hebrew floating around. I had forgotten on the first day that the Zend company is headquartered in Israel, so this would explain the Hebrew. It’s different - OSCON was nothing like this. The conference is going well thus far. The two tutorials I attended were “PHP Development Best Practices” and “Extending PHP”. I think when I first signed up to take Extending PHP, I was thinking it was something other than writing extensions. I had attended a seminar at OSCON about writing extensions, and I was thoroughly unimpressed. It was quick and didn’t really catch my interest. However, the speakers giving it this time really caught my attention, despite their assumption that everyone in the classroom knew C. Nevertheless, although I was not understanding half of the lecture, it does make me want to learn C so that I can go through and create PHP extensions for my business (and possibly TAMU). I got to network with several individuals at a ZCE & Speaker only party on Monday evening, and it was quite intriguing. I learned about ExtremeBlue (a very unique programming challenge for students) from 3 IBM representatives (2 from the UK one from Canada), and finally met Paul Reinheimer - the individual who trained me online for the PHP ZCE Certification. Additionally, I got to talk to several individuals with superior cameras (D200 and SP-D800 flashes) and I’m totally envious and know what I’m going to upgrade to. I also got to talk with Chris Shifflet who seems like a real laid-back individual, but quite intelligent when it comes to PHP. In any case, the first Keynote of the day is about to begin. Gotta run. Well, yesterday was the dreaded changed day for my Zend PHP certification, and I could put in no more study time for it - I had already spent several days taking training courses, then several days reviewing the materials taught there, followed by Wednesday and Thursday (practically all-day), so anymore would have done nothing but possibly confuse me and/or just be a waste. I had been over the material presented to me through the Zend PHP Certification training AND I purchased a book 2 days before the Certification, the Zend PHP Certification Practice Test Book, available through php | architect. After thoroughy going over the materials from the Zend PHP Certification Training Course, I felt reasonably assured that there would be materials on the test that covered functions, OOP, and other things that I hadn’t touched in PHP. As a result, a lot of things I had to go play with to experience on my own so I could at least know how to answer the questions… This regex command I determined and figure I would share with everyone trying to verify the authenticity of an IP address. ^([0-9]{1,3}\.){3}[0-9]{1,3}$If you have a better regex, certainly entertain me. I’m always willing to listen. This came about as a result of realizing that a contact form on my business’s website fell subject to XSS (Cross-Site Scripting) attacks. Essentially, what the person (script, computer, hacker, evil sons of b*tches) was using my form and figured out a way to use it to spam others. This came about by checking my mail log and trying to figure out why I had such a large queue of messages, and why my email count had been ridiculously high going to different outbound accounts. What happens is people can inject a statement as follows into a text field (textarea input, or any other input field): bcc: email@email.com\r\n bcc: email2@anotherdomain.com\r\n bcc: email3@imgonnascrewyou.net\r\n\r\n Howdy! This is SPAM. Have a crabby day! Note: This can be all on one line, but needs to contain line break characters \r and \n. So, what happens is if the script isn’t written correctly, those bcc headers get stuck into the email message, resulting in multiple people getting the email, besides just you. What I’ve been doing is going back through and validating all input (because that’s what I’ve learned to do through my PHP training sessions as of late) so that this will stop. I hopefully will be catching all invalid input and will be notifying myself when it happens, so that I can immediately ban that IP address. So, if you are reading this and are any type of PHP developer (beginner to advanced) and don’t care about security - either stop coding or start concerning yourself with security. Follow Chris Shiflett’s advice: FIEO (Filter Input Escape Output).
Day 3 ended the tutorials and began the sessions - the events that the majority of people showed up for. Keystones also precluded the days events, and the first Keynotes were rather intriguing. I heard talks from one of the leads and founders of SixApart, the company responsible for such things as LiveJournal, etc. In addition, Mr. O’Reilly gave a talk on how opensource licenses are out of date. With lack of further explanation of why he believed this, there were many members of the audience (including the other Keynote speakers) who were questioning that statement. The sessions, left much to be desired. They were approximately 45 minutes each (some actually spanned an hour and a half - though those were rare). As such, 45 minutes hardly gave enough time to thoroughly explain the concepts being presented, but for some of the sessions it was just enough time. For example, the first session I attended was on how this developer used Ruby on Rails to create an MMO in about 45 minutes. The game, is called Unroll - found at llor.nu. It’s a rather simple game, but he explained the concepts behind the creation of his game, rather than explaining some of the methods he used - such as showing code examples, tips and tricks, etc. As such, I left with hardly an understanding of how to use Rails to create a game of my own, but his game is at least open source, so I can download the source code and figure out what I need to then. The other sessions, which included a combination of PHP, Ruby, and Rails were rather uninteresting for the most part. I took notes in some sessions, but many I’ll have to find the slides in order to benefit from attending them. However, despite how uninteresting some of these sessions were, I admit that I did take out a lot of ideas that I plan to integrate for my business and CIS. Such things include code caches, such as APC, using IDE’s for development and then running traces on the code to further be able to determine where slow-downs in code occur. I also found a couple of other interesting software items people were using on Macs that I have found quite awesome. BTW, the Exhibit hall resulted in me getting lots of goodies.
Day 2 of OSCON training was rather sluggish and disappointing. There were several things that I found out that I already knew, but many things I wasn’t expecting from one of the talks, the High Performance PHP. Going into this, I was expecting to see some code examples and talks about certain functions or stylistic coding techniques that would result in improved PHP code. This was definitely not the case, as the majority of the talk was about improving applications that run PHP, or co-exist with PHP. There were also other things to avoid (such as SOAP, but for obvious reasons), but hardly any talks about how to improve your code to improve it’s performance. The one thing I did learn through this tutorial was how to go through and trace the code, and use things like kcachegrind to make graphs and help you figure out where the slow parts of your code are laying. Percentage breakdowns of the time spent inside certain functions, classes, and objects help to show where your code is “slow”. I plan on using this on my many different projects, just as soon as I figure out how to use the damn program. The Security tutorial was also nice, but at the same time going over many of the things I learned in my online PHP training that Paul Reinheimer gave last month. |