- What does a special set of tags <?= and ?> do in PHP? - The output is displayed directly to the browser.
- What’s the difference between include and require? - It’s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.
- I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what’s the problem? - PHP Interpreter treats numbers beginning with 0 as octal.
- Would I use print "$a dollars" or "{$a} dollars" to print out the amount of dollars in this example? - In this example it wouldn’t matter, since the variable is all by itself, but if you were to print something like "{$a},000,000 mln dollars", then you definitely need to use the braces.
- How do you define a constant? - Via define() directive, like define ("MYCONSTANT", 100);
- How do you pass a variable by value? - Just like in C++, put an ampersand in front of it, like $a = &$b
- Will comparison of string "10" and integer 11 work in PHP? - Yes, internally PHP will cast everything to the integer type, so numbers 10 and 11 will be compared.
- When are you supposed to use endif to end the conditional statement? - When the original if was followed by : and then the code block without braces.
- Explain the ternary conditional operator in PHP? - Expression preceding the ? is evaluated, if it’s true, then the expression preceding the : is executed, otherwise, the expression following : is executed.
- How do I find out the number of parameters passed into function? - func_num_args() function returns the number of parameters passed in.
- If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b? - 100, it’s a reference to existing variable.
- What’s the difference between accessing a class method via -> and via ::? - :: is allowed to access methods that can perform static operations, i.e. those, which do not require object initialization.
- Are objects passed by value or by reference? - Everything is passed by value.
- How do you call a constructor for a parent class? - parent::constructor($value)
- What’s the special meaning of __sleep and __wakeup? - __sleep returns the array of all the variables than need to be saved, while __wakeup retrieves them.
- Why doesn’t the following code print the newline properly? <?php
$str = ‘Hello, there.nHow are you?nThanks for visiting TechInterviews’;
print $str;
?>
Because inside the single quotes the n character is not interpreted as newline, just as a sequence of two characters - and n. - Would you initialize your strings with single quotes or double quotes? - Since the data inside the single-quoted string is not parsed for variable substitution, it’s always a better idea speed-wise to initialize a string with single quotes, unless you specifically need variable substitution.
- How come the code <?php print "Contents: $arr[1]"; ?> works, but <?php print "Contents: $arr[1][2]"; ?> doesn’t for two-dimensional array of mine? - Any time you have an array with more than one dimension, complex parsing syntax is required. print "Contents: {$arr[1][2]}" would’ve worked.
- What is the difference between characters 23 and x23? - The first one is octal 23, the second is hex 23.
- With a heredoc syntax, do I get variable substitution inside the heredoc contents? - Yes.
- I want to combine two variables together:
$var1 = 'Welcome to '; $var2 = 'TechInterviews.com';
What will work faster? Code sample 1:
$var 3 = $var1.$var2;
Or code sample 2:
$var3 = "$var1$var2";
Both examples would provide the same result - $var3 equal to "Welcome to TechInterviews.com". However, Code Sample 1 will work significantly faster. Try it out with large sets of data (or via concatenating small sets a million times or so), and you will see that concatenation works significantly faster than variable substitution. - For printing out strings, there are echo, print and printf. Explain the differences. - echo is the most primitive of them, and just outputs the contents following the construct to the screen. print is also a construct (so parentheses are optional when calling it), but it returns TRUE on successful output and FALSE if it was unable to print out the string. However, you can pass multiple parameters to echo, like:
<?php echo 'Welcome ', 'to', ' ', 'TechInterviews!'; ?>
and it will output the string "Welcome to TechInterviews!" print does not take multiple parameters. It is also generally argued that echo is faster, but usually the speed advantage is negligible, and might not be there for future versions of PHP. printf is a function, not a construct, and allows such advantages as formatted output, but it’s the slowest way to print out data out of echo, print and printf. - I am writing an application in PHP that outputs a printable version of driving directions. It contains some long sentences, and I am a neat freak, and would like to make sure that no line exceeds 50 characters. How do I accomplish that with PHP? - On large strings that need to be formatted according to some length specifications, use wordwrap() or chunk_split().
- What’s the output of the ucwords function in this example?
$formatted = ucwords("TECHINTERVIEWS IS COLLECTION OF INTERVIEW QUESTIONS"); print $formatted;What will be printed is TECHINTERVIEWS IS COLLECTION OF INTERVIEW QUESTIONS.
ucwords() makes every first letter of every word capital, but it does not lower-case anything else. To avoid this, and get a properly formatted string, it’s worth using strtolower() first. - What’s the difference between htmlentities() and htmlspecialchars()? - htmlspecialchars only takes care of <, >, single quote ‘, double quote " and ampersand. htmlentities translates all occurrences of character sequences that have different meaning in HTML.
- What’s the difference between md5(), crc32() and sha1() crypto on PHP? - The major difference is the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1() returns a 128 bit value, and md5() returns a 160 bit value. This is important when avoiding collisions.
- So if md5() generates the most secure hash, why would you ever use the less secure crc32() and sha1()? - Crypto usage in PHP is simple, but that doesn’t mean it’s free. First off, depending on the data that you’re encrypting, you might have reasons to store a 32-bit value in the database instead of the 160-bit value to save on space. Second, the more secure the crypto is, the longer is the computation time to deliver the hash value. A high volume site might be significantly slowed down, if frequent md5() generation is required.
Showing posts with label php. Show all posts
Showing posts with label php. Show all posts
Tuesday, December 27, 2011
PHP interview questions and answers
Monday, December 27, 2010
Magento Shopping Cart And Its Demands
Magento Shopping Cart is the ultimate online solution for online merchants for its dramatic features. On one side it has lots of features for online customers with an option to add or remove and on the other hand; its all available for a small amount of money. There are multi language options and currencies updates available to give customers more shopping options. All these features enable Magento to lead the others in the race and the customers have a healthy and fun giving online shopping experience. Though Magento is regarded as the future of the ecommerce business and has left lots of shopping carts solutions
behind, yet its not that simple as it seems. Its suggested by some professionals that a PHP programmer can help integrate shopping cart with Magento, but its not true since it requires more than that.
Its not more than an oversimplification that people regard Magento Shopping Cart as an open source based on PHP programming. The truth is Magento cart is based on Zend frame work that requires a collective knowledge of PHP and one or both object oriented programming languages
like C or C++. Its because of this confusion that people are crying for not proper integration with Magento. Programmers also create problems for not being able to integrate their clients shopping cart with Magento because they are not equipped with the required programming skills. As a result, they either stop working on their clients project when theyre gone just half of the way; or they stop replying their clients phone calls. Whatever the case is, the project doesnt complete and produces problems for clients.
Magneto Shopping Cart is a flexible solution with advance technology. Its called future of ecommerce, therefore, for smooth shopping cart integration;
behind, yet its not that simple as it seems. Its suggested by some professionals that a PHP programmer can help integrate shopping cart with Magento, but its not true since it requires more than that.
Its not more than an oversimplification that people regard Magento Shopping Cart as an open source based on PHP programming. The truth is Magento cart is based on Zend frame work that requires a collective knowledge of PHP and one or both object oriented programming languages
like C or C++. Its because of this confusion that people are crying for not proper integration with Magento. Programmers also create problems for not being able to integrate their clients shopping cart with Magento because they are not equipped with the required programming skills. As a result, they either stop working on their clients project when theyre gone just half of the way; or they stop replying their clients phone calls. Whatever the case is, the project doesnt complete and produces problems for clients.
Magneto Shopping Cart is a flexible solution with advance technology. Its called future of ecommerce, therefore, for smooth shopping cart integration;
Advantages Of Implementing Php Shopping Cart
The making of shopping cart software is amazingly easy and when done with accuracy it could translate in to an exceedingly successful and collectively accepted php shopping cart.
The information of the stocks are unsurprisingly stored in the database
and the only information obligatory from the enduring which would in turn require to be stored is none other than the id of each product that has been added to the php shopping cart.
The php shopping cart is reachable and there are a diversity of ways of accomplishment it - the most popular being the clicking on a link or by clicking on the 'add to cart' option on the product page.
In the occurrence of the php shopping cart being inwards at using the link on the product page - 'add to cart' - the requirement of the hour is unquestionably to update the products in the php shopping cart before the demonstration of an innovative product range.
It is not infrequent for the php shopping cart to have more than one of a kind of any meticulous product, which could be compiled, and it is not desirable to list the number of products of a scrupulous kind in the php shopping cart.
There is an accord between the links to 'delete' or 'add' a product to the php shopping cart. The customer also could have the alternative of updating the products in the php shopping cart via manually.
The php shopping cart is uncommonly unfilled and if it is a suitable message need to be flashed to the consequence. This is one feature of the php shopping cart, which can hardly be negotiated.
The information of the stocks are unsurprisingly stored in the database
and the only information obligatory from the enduring which would in turn require to be stored is none other than the id of each product that has been added to the php shopping cart.
The php shopping cart is reachable and there are a diversity of ways of accomplishment it - the most popular being the clicking on a link or by clicking on the 'add to cart' option on the product page.
In the occurrence of the php shopping cart being inwards at using the link on the product page - 'add to cart' - the requirement of the hour is unquestionably to update the products in the php shopping cart before the demonstration of an innovative product range.
It is not infrequent for the php shopping cart to have more than one of a kind of any meticulous product, which could be compiled, and it is not desirable to list the number of products of a scrupulous kind in the php shopping cart.
There is an accord between the links to 'delete' or 'add' a product to the php shopping cart. The customer also could have the alternative of updating the products in the php shopping cart via manually.
The php shopping cart is uncommonly unfilled and if it is a suitable message need to be flashed to the consequence. This is one feature of the php shopping cart, which can hardly be negotiated.
PHP Shopping Cart Software Integration
PHP ecommerce software integration is frequently something that is overlooked. People simply think that all shopping cart software is easily integrated into a design. However, many shopping carts are not designed in a way that makes it very easy at all, while others make it so easy that a novice programmer could do it without blinking an eye. You should definitely keep an eye out though when purchasing shopping cart software on how easy it will be to get it onto your website.
If you are truly concerned, I would start out by asking the developer to provide the documentation on how to integrate it. This will likely give you a good perspective on what to expect. If the developer will not give you access to that, this could be a red flag that perhaps there is not good documentation or that it could end up being far more difficult than one would hope for.
I have seen some shopping carts that it is just a matter of putting a single line of code into your website.
It will show up, look great, and you will never have a problem. Others will require that you manipulate every page of the shopping cart from beginning to end. You will need to build your website around the shopping cart, change button colors, alter the css file, and make other various HTML changes. These are a pain, and should be avoided when possible if they do not have the proper documentation. A good cart will make it easy to alter the size, structure, and layout of the shopping cart. They might even have different themes available that might help you to match your existing design. When all else fails and you have odd colors, you might even just have to change a little bit of CSS to really get it looking like you would want it to look.
It starts with good documentation though from the developer.
The importance of having an integrated online web cart often goes overlooked. I will even go on to say that it lacks professionalism when it is not done properly. Some companies feel that simply having their banner or logo on the page of the shopping cart is good enough. To be honest though, this is not the extent I consider integration to be. If the buttons and colors of the shopping cart do not match your website, then this is not true integration. This is just something that lacks professionalism in my opinion.
When people are in the ordering process, it is natural for people to frequently back out. They might just be checking the final price on one of your items. However, others will place something in their shopping cart and the ordering process gives them time to ponder. Do they really need the item? Is this the right company to buy from? Is this the cheapest available on the internet? These are all questions that will run through almost every buyers mind. Why do you want to give them a reason to doubt the professionalism of your company? This is something that will cross their mind if you have a poorly done job on integrating your shopping cart. You want to give them every reason to buy from you, not every reason to leave your site. In the end, with good integration you will find that you will be much more pleased with your conversion ratios when people visit your shopping cart if it is integrated properly and matches your website as closely as possible.
If you are truly concerned, I would start out by asking the developer to provide the documentation on how to integrate it. This will likely give you a good perspective on what to expect. If the developer will not give you access to that, this could be a red flag that perhaps there is not good documentation or that it could end up being far more difficult than one would hope for.
I have seen some shopping carts that it is just a matter of putting a single line of code into your website.
It will show up, look great, and you will never have a problem. Others will require that you manipulate every page of the shopping cart from beginning to end. You will need to build your website around the shopping cart, change button colors, alter the css file, and make other various HTML changes. These are a pain, and should be avoided when possible if they do not have the proper documentation. A good cart will make it easy to alter the size, structure, and layout of the shopping cart. They might even have different themes available that might help you to match your existing design. When all else fails and you have odd colors, you might even just have to change a little bit of CSS to really get it looking like you would want it to look.
It starts with good documentation though from the developer.
The importance of having an integrated online web cart often goes overlooked. I will even go on to say that it lacks professionalism when it is not done properly. Some companies feel that simply having their banner or logo on the page of the shopping cart is good enough. To be honest though, this is not the extent I consider integration to be. If the buttons and colors of the shopping cart do not match your website, then this is not true integration. This is just something that lacks professionalism in my opinion.
When people are in the ordering process, it is natural for people to frequently back out. They might just be checking the final price on one of your items. However, others will place something in their shopping cart and the ordering process gives them time to ponder. Do they really need the item? Is this the right company to buy from? Is this the cheapest available on the internet? These are all questions that will run through almost every buyers mind. Why do you want to give them a reason to doubt the professionalism of your company? This is something that will cross their mind if you have a poorly done job on integrating your shopping cart. You want to give them every reason to buy from you, not every reason to leave your site. In the end, with good integration you will find that you will be much more pleased with your conversion ratios when people visit your shopping cart if it is integrated properly and matches your website as closely as possible.
Choosing a PHP Shopping Cart
I could sit here and tell you everything that I look for a shopping cart. It would probably be a laundry list of things. However, that is for my own website, and may not fit yours. Since you are selling different items more than likely, you may have a demand for different things. This is why there are also so many shopping carts on the market. Several of them have good customer service, they all run well, but it's the little things that make their products unique. For this reason, several different shopping carts do sell well online because they are tailored towards different types of business needs. Below though, I have created a few things that should be true for all people who are looking for a good PHP shopping cart. I hope it helps you narrow down your choices.
Must Be Easy to Update Your Website
The most frustrating thing that can happen to anyone is to get their website up and running.
The developer helped you get the products added to the website, you go live, and a few weeks later you realize that there are some missing items. You should be aware of how to update your website, because it is only going to be a matter of time before you have a desire to do so. You will want to tweak wording and change things to hopefully help you improve your sales. Believe it or not, there are some shopping carts on the market that make this process near impossible for anyone who is not familiar with HTML or PHP Programming
. With that said, if I were you, I would make sure that before you purchase a PHP shopping cart
that you understand how to update your products and those types of things. It will save you a headache in the end.
Must Have Good Support from Developers
It is simply natural that anyone who purchases a script is going to have some questions.
They will want to know how to work a specific feature, how to set something up, or if there can be a feature added in a future release. Unfortunately, not all shopping carts are supported well. You essentially buy them "as is" and the minute you make your payment you are left on your own to figure things out or fix problems that might be in the script. The tip I offer to anyone who wants to see how good support is, is to simply ask a few questions to their customer service. Generally, in small businesses the people helping in sales / customer service will be the same people answer technical questions after you purchase the script. You will get a good idea of how helpful they will be, how clear their emails are, and how quick you might get a response. It is safe to say that no response probably means you will not get a response when you purchase the script and ask a question then either.
The Shopping Cart Meets But Does Not Surpass Your Needs
This is a tough line to follow because the first priority is to ensure that the script contains all of the features you might need. However, having one with too many can be almost an equally bad thing. Shopping carts with too many features can quickly become so complex that you will find it hard to manage your website. As well, those shopping carts that will virtually work for any website may have a very complex ordering form. This is not something you want if you really do not need it. The idea with ordering forms online is to have exactly what you need and nothing more. Therefore, even a script with too many features may need to be heavily modified just as if one you purchase that maybe does not have all the features you need. Therefore, both are going to cost you money. It is better to find a shopping cart as close to what you need as possible. It will save you money in the long run.
Must Be Easy to Update Your Website
The most frustrating thing that can happen to anyone is to get their website up and running.
The developer helped you get the products added to the website, you go live, and a few weeks later you realize that there are some missing items. You should be aware of how to update your website, because it is only going to be a matter of time before you have a desire to do so. You will want to tweak wording and change things to hopefully help you improve your sales. Believe it or not, there are some shopping carts on the market that make this process near impossible for anyone who is not familiar with HTML or PHP Programming
. With that said, if I were you, I would make sure that before you purchase a PHP shopping cart
that you understand how to update your products and those types of things. It will save you a headache in the end.
Must Have Good Support from Developers
It is simply natural that anyone who purchases a script is going to have some questions.
They will want to know how to work a specific feature, how to set something up, or if there can be a feature added in a future release. Unfortunately, not all shopping carts are supported well. You essentially buy them "as is" and the minute you make your payment you are left on your own to figure things out or fix problems that might be in the script. The tip I offer to anyone who wants to see how good support is, is to simply ask a few questions to their customer service. Generally, in small businesses the people helping in sales / customer service will be the same people answer technical questions after you purchase the script. You will get a good idea of how helpful they will be, how clear their emails are, and how quick you might get a response. It is safe to say that no response probably means you will not get a response when you purchase the script and ask a question then either.
The Shopping Cart Meets But Does Not Surpass Your Needs
This is a tough line to follow because the first priority is to ensure that the script contains all of the features you might need. However, having one with too many can be almost an equally bad thing. Shopping carts with too many features can quickly become so complex that you will find it hard to manage your website. As well, those shopping carts that will virtually work for any website may have a very complex ordering form. This is not something you want if you really do not need it. The idea with ordering forms online is to have exactly what you need and nothing more. Therefore, even a script with too many features may need to be heavily modified just as if one you purchase that maybe does not have all the features you need. Therefore, both are going to cost you money. It is better to find a shopping cart as close to what you need as possible. It will save you money in the long run.
Thursday, December 23, 2010
Problems with PHP
PHP is a nice language for some tasks. Lots of good software uses it. No other language makes it so convenient to mix code and html, which is great for lone web developers who are also programmers. I've found it pretty useful for running my site, mainly because I can so easily put code in the middle of my content, and keep the overall per-page authoring overhead down. However, from a pure programming or information theory standpoint, it's got some serious problems:
This is waxing philosophical, but in my experience, PHP has an uncomfortably low ceiling. Programming isn't just about putting one instruction after another; it's about building abstractions to better represent and solve problems. The more complex the problem, the higher the level of abstraction needed to solve it cleanly. With PHP, I often hit my head on its low ceiling of abstraction, and it seems to require a great deal more effort and discipline (than in other languages) to avoid ducking down into the details of implementation when I should be focusing on the upper-level design.
- Namespaces don't exist at all. (this is similar to keeping all your files in one directory) There have been discussions about adding namespaces, but the proposed separator is \? because "there isn't any other character left"...
- Exceptions didn't exist until PHP5, and aren't implemented in a useful "deep" fashion.
- Built-in and library APIs are a disorganized mess.
- There are thousands of symbols in the PHP namespace. Cleaner languages only have a few dozen. "Everything is built in" just means it has way too many functions in its core, especially since many are minor variations of each other.
- No consistent naming convention is used. Some functions are verb_noun() and others are noun_verb(). Some are underscore_separated, while others are CamelCase or runtogether. Some are prefixed_byModuleName, and others use a module_suffix_scheme. Some use "to" and others use "2". And if you take a random set of ten library functions, chances are half a dozen different conventions will be included.
- PHP tends to use a lot of similar functions, instead of just one, powerful one. For example, PHP has
sort(), arsort(), asort(), ksort(), natsort(), natcasesort(), rsort(), usort(), array_multisort(), and uksort(). For comparison, Python covers the functionality of all of those withlist.sort(). - PHP includes lots of cruft or bloat. Do we really need a built-in str_rot13() function? Also, a lot of other built-ins are just trivial combinations of each other. Users don't really need case-insensitive variants of every string function, since there is already a strtolower().
- Many parts of PHP either deviate from standards, or otherwise don't do what users would expect.
For example, exec() returns the last line of text output from a program. Why not return the program's return value, like every other language does? And further, when would it ever be useful to get only the last line of output?
Another example: PHP uses non-standard date format characters.
- The language was generally thrown together without any coherent design, accreted in a messy and complex fashion.
- Functions...
- Functions cannot be redefined. If I want a set of includes which all use the same interface, I can only use one of them per page load -- there's no way to include a then call a.display() then include b and execute b.display(). I also cannot transparently wrap existing functions by renaming/replacing them.
- Functions cannot be nested. (actually, they can, but it has the same effect as if they were not. All functions are global, period.)
- Anonymous functions (lambda) don't exist. create_function() is not the same thing. Given two strings, it compiles them into code, binds the code to a new global function, and returns the new function name as a string.
Note that the number after "\0lambda_" is not predictable. It starts at one and increments each time create_function is called. The number keeps incrementing as long as the web server process is running, and the counter is different in each server process. The memory for these new global functions is not freed, either, so you can easily run out of memory if you try to make lambdas in a loop.$foo = create_function('$x', 'echo "hello $x!";');
$bar = "\0lambda_1";
$bar("bar"); // sometimes prints "hello bar!", sometimes fails - Functions are case insensitive.
- No "doc strings". Documentation must either be maintained separately from the code, or by (rather finicky) 3rd-party code-level documentation interpreters.
- The documentation...
- ... is often incorrect or incomplete, and finding relevant information tends to require reading pages and pages of disorganized user-contributed notes (which are incorrect even more often) to find the details the documentation left out. Sometimes really important details are left out, such as "this function is deprecated -- use foo() instead".
- ... is (as of PHP 5.1.2) not included with the source, nor typically installed along with the binary packages. Downloadable documentation is available, but does not match the docs on PHP.net. Specifically, it leaves out all the user-contributed notes, which are important because of reasons mentioned above.
- ... is not built in. You can't just point an introspection tool at a PHP module and get usage information from it.
- Default to pass-by-value. (php5 now defaults to reference, for objects, though I'm not sure if it's "real" references or reference-by-name)
- Default error behavior is to send cryptic messages to the browser, mid-page, instead of logging a traceback for the developer to investigate.
- Many errors are silent.
For example, accessing a nonexistent variable simply returns nothing. Whether this is a Bad Thing is debatable (I believe it's bad), but it can nevertheless interact badly with some other aspects of PHP -- such as the inconsistent case sensitivity (variables are sensitive, but functions are not):function FUNC() { return 3; }
$VAR = 3;
print func(); // produces "3"
print $var; // produces nothing - The combination list/hash "array" type causes problems by oversimplifying, often resulting in unexpected/unintuitive behavior.
For example, PHP's weak type system interferes with hash keys:
After a little experimentation, I see that hash keys cannot be functions, classes, floats, or strings which look like integers. There are likely other invalid types as well. The only usable key types I've found so far are integers, and strings that do not parse as integers. (note that the parsing used here is different than the automatic str-to-int coercion used for the "+" operator) .Code Result $a = array("1" => "foo", 1 => "bar");
echo $a[1], " ", $a["1"], "<br />\n";
print_r($a);bar bar
Array ( [1] => bar ) - Awkward / overlapping names can exist...
fooand$fooare completely unrelated. - Magic quotes (and related mis-features) make data input needlessly complex and error-prone. Instead of fixing vulnerabilities (such as malformed SQL query exploits), PHP tries to mangle your data to avoid triggering known flaws.
- The server-wide settings in PHP's configuration add a lot of complexity to app code, requiring all sorts of checks and workarounds. Instead of simplifying or shortening code (which the features are supposed to do), they actually make the code longer and more complex, since it must check to make sure each setting has the right value and handle situations when the expected values aren't there.
- PHP's database libraries are among the worst in any language. This is partially due to a lack of any consistent API for different databases, but mostly because the database interaction model in PHP is broken. The SQL injection issues in PHP deserve particular attention.
How can it be that hard for web developers to check data before it is submitted? I wouldn't imagine trusting the data that an anonymous user can enter into my website.. so maybe I'm just trained to check data. Of course, I'm also glad I use MySQL with PHP where a simple mysql_real_escape_string can prevent any popular SQL Injection attempt.
You're glad that you use pretty much the only langauge where this is not done automatically for you, but which instead forces you to use a function with a name like mysql_real_escape_string()? And that actually has a similarly-named function without the "_real_" that doesn't do the job right? Just kidding with that other one, here's the real one! - The performance is crippled for commercial reasons (zend). Free optimizers are available, but aren't default or standard.
- Bad recursion support. Browse bug 1901 for an example and some details. BTW, ever heard of tail recursion? They might have mentioned it in the "Intro to Computer Science" course.
- Not thread safe.
- No unicode support. It's planned for PHP 6 but that could be a long time away.
- Vague and unintuitive automatic coercion; "==" is unpredictable, and "===" does not solve all the problems caused by "==". According to the manual, "==" returns true if the operands are equal, and "===" returns true if the operands are equal and of the same type. But that's not entirely true. For example:
Two different strings are equal... sometimes.
Further, the coercion rules change depending on what you're doing. The behavior for "==" is not the same as used for "+" or for making hash keys.
"1e1" == "10" => True
"1e1.0" == "10" => False
So, they're "equal and of the same type", right?
"1e1" === "10" => False
Unexpected results:
"1 two 3" == 1 => True
1.0 === 1 => False
"11111111111111111117" == "11111111111111111118" => True
Equality is (apparently) not transitive:
$a = "foo"; $b = 0; $c = "bar";
$a == $b => True
$b == $c => True
$a == $c => False
"22 cream puffs" == "22 bullfrogs" => False
Even though math asserts that, if A minus B equals zero, then A must equal B, PHP disagrees:
"12 zombies" + "10 young ladies" + "bourbon" == "22 cream puffs" => True
"bourbon" - "scotch" => 0
"bourbon" == "scotch" => False
- Variable scoping is strange, inconsistent, and inconvenient -- particularly the notably unusual "global" scope which gave rise to kludges like "superglobal" or "autoglobal" as workarounds.
Further, variables cannot be scoped beyond global or function-local. - The mixture of PHP code with HTML markup tends to make code difficult to read. Readability is important.
- Various "features" cause very unusual behavior and add complexity. This tends to cause bugs for programmers who expect it to behave like other languages.
For example, this will fail sporadically: Open a file. Write to it. Close it. Open it. Read from the file. To make this actually work, the programmer must A) know it will fail, B) have some clue why it fails, and C) call the correct function (
clearstatcache()) before re-opening the file. Note that the online docs aren't much help -- searching for "cache" takes the viewer to the docs forcosh(), but returns nothing at all related to files or caches. - It provides no way to log errors verbosely, but only display critical errors to the user. Further, some of the most critical errors (such as running out of memory) give absolutely no response to the user -- not even a blank page.
- Poor security, and poor response to security issues. This is a large and detailed topic, but regardless of whether it's caused by inexperienced programmers or by PHP itself, the amount of PHP-related exploits is rather high. And according to a PHP security insider, the effort is futile.
- Its object model is (still) very lacking, compared to other systems.
- Most of the development since v3 seems to be devoted to damage control, and dealing with earlier mistakes... not a good sign.
- In general, has a tendency to create more problems than it solves.
This is waxing philosophical, but in my experience, PHP has an uncomfortably low ceiling. Programming isn't just about putting one instruction after another; it's about building abstractions to better represent and solve problems. The more complex the problem, the higher the level of abstraction needed to solve it cleanly. With PHP, I often hit my head on its low ceiling of abstraction, and it seems to require a great deal more effort and discipline (than in other languages) to avoid ducking down into the details of implementation when I should be focusing on the upper-level design.
Thursday, September 23, 2010
Working with File System & I/O|Working with Directories
Working with Directories
PHP provides a number of functions that can be used to perform tasks such as identifying and changing the current directory, creating new directories, deleting existing directories and list the contents of a directory.
Creating Directories in PHP
A new directory can be created in PHP using the mkdir() function. This function takes a path to the directory to be created. To create a directory in the same directory as yourPHP script, simply provide the directory name. To create directory in a different directory specify the full path when calling mkdir().
A second, optional argument allows the specification of permissions on the directory (controlling such issues as whether the directory is writable):
$result = mkdir ("test", "0777")or die ("Failed to create Directory");
if($result)
echo "directory created successfully";
?>
Deleting a Directory
Directories are deleted in PHP using the rmdir() function. rmdir() takes a single argument, the name of the directory to be deleted. The deletion will only be successful if the directory is empty. If the directory contains files or other sub-directories the deletion cannot be performed until those files and sub-directories are also deleted.
Finding and Changing the CWD (current working directory)
Do you expect a web application to be able to perform all of its file related tasks in a single directory? The answer is NO, it is possible but it will create a mess. For this reason, it is vital to be able to both find out the current working directory, and change to another directory from within a PHP stript.
The current working directory can be identified using the getCwd() function:
".$cwd."";
?>
save the above script as getCWdir.php and open the page in browser. If your script is fine then you should get the output given below:
The current working directory can be changed using the chdir() function. chdir() takes as the only argument the path of the new directory:
".$cwd."";
chdir ("/e_drive");
$cwd=getCwd();
echo "After Changing the Directory, Current Working Directory is ".$cwd."";
?>
Save the file as chdir.php and open the open the PHP script in browser to view the output:
Listing Files in a Directory
The files in a directory can be read using the PHP scandir() function. scandir() takes two arguments. The first argument is the path the directory to be scanned. The second optional argument specifies how the directory listing is to be sorted. If the argument is 1 the listing is sorted reverse-alphabetically.
If the argument is omitted or set to 0 the list is sorted alphabetically:
".$cwd."";
chdir ("/var");
$cwd=getCwd();
echo "
After Changing the Directory,
Current Working Directory is ".$cwd."
";
$array = scandir(".", 1);
print_r($array);
?>
Save the file and open the page in browser to view the output.
Output:
Try it your self.
PHP provides a number of functions that can be used to perform tasks such as identifying and changing the current directory, creating new directories, deleting existing directories and list the contents of a directory.
Creating Directories in PHP
A new directory can be created in PHP using the mkdir() function. This function takes a path to the directory to be created. To create a directory in the same directory as yourPHP script, simply provide the directory name. To create directory in a different directory specify the full path when calling mkdir().
A second, optional argument allows the specification of permissions on the directory (controlling such issues as whether the directory is writable):
$result = mkdir ("test", "0777")or die ("Failed to create Directory");
if($result)
echo "directory created successfully";
?>
Deleting a Directory
Directories are deleted in PHP using the rmdir() function. rmdir() takes a single argument, the name of the directory to be deleted. The deletion will only be successful if the directory is empty. If the directory contains files or other sub-directories the deletion cannot be performed until those files and sub-directories are also deleted.
Finding and Changing the CWD (current working directory)
Do you expect a web application to be able to perform all of its file related tasks in a single directory? The answer is NO, it is possible but it will create a mess. For this reason, it is vital to be able to both find out the current working directory, and change to another directory from within a PHP stript.
The current working directory can be identified using the getCwd() function:
".$cwd."";
?>
save the above script as getCWdir.php and open the page in browser. If your script is fine then you should get the output given below:
The current working directory can be changed using the chdir() function. chdir() takes as the only argument the path of the new directory:
".$cwd."";
chdir ("/e_drive");
$cwd=getCwd();
echo "After Changing the Directory, Current Working Directory is ".$cwd."";
?>
Save the file as chdir.php and open the open the PHP script in browser to view the output:
Listing Files in a Directory
The files in a directory can be read using the PHP scandir() function. scandir() takes two arguments. The first argument is the path the directory to be scanned. The second optional argument specifies how the directory listing is to be sorted. If the argument is 1 the listing is sorted reverse-alphabetically.
If the argument is omitted or set to 0 the list is sorted alphabetically:
".$cwd."";
chdir ("/var");
$cwd=getCwd();
echo "
After Changing the Directory,
Current Working Directory is ".$cwd."
";
$array = scandir(".", 1);
print_r($array);
?>
Save the file and open the page in browser to view the output.
Output:
Try it your self.
Monday, September 20, 2010
Php -Explode and Implode||Php arrays ,string and variables
The PHP function explode lets you take a string and blow it up into smaller pieces. For example, if you had a sentence, which contains name of 5 persons, you could ask explode to use the sentence’s commas “,” as dynamite and it would blow up the sentence into separate words, which would be stored in an array. The sentence “Ram, Ravish, Rajeev, Rakesh, Ramesh” would look like this after explode got done with it: Explode is a PHP function which let as divide a string into smaller pieces,explode is used to break up a string into chunks, it acts on a string, and returns an array. Ram
Ravish
Rajeev
Rakesh
Ramesh The explode() function breaks a string into an array. Syntax array explode(separator,string,limit)
For example to break a string $str, separated by , the syntax would be: explode (“,”,$str); Example:
You can also use foreach loop to print the content of array. Implode The implode works exactly opposite of explode function. The PHP function implode operates on an array and is known as the “undo” function of explode. If you have used explode to break up a string into chunks or just have an array of stuff you can use implode to put them all into one string. The implode function accepts to arguments: separator and the array Syntax: implode(separator,array)
Example:
Assignment 1. Convert the following String to Array ”Hello, World!; Welcome, to eBIZ Education; Thanks for visiting” first convert the string to Array by using “;” as separator, then using “,” as separator and finally using space “ ”
Ravish
Rajeev
Rakesh
Ramesh The explode() function breaks a string into an array. Syntax array explode(separator,string,limit)
| Parameter | Description | Required/Optional |
| separator | Specifies where to break the string | Required. |
| string | The string to split. | Required. |
| limit | Indicates t he maximum number of array elements to return | Optional |
When executed the above script will display following output:
$str="Ram,Ravish,Rajeev,Rakesh,Ramesh";
$arr=explode(",",$str);
?>
";
echo "Exploded Array\n
";
print_r($arr);
?>
| Parameter | Description |
| separator | Optional. Specifies what to put between the array elements. Default is “” (an empty string) |
| array | Required. The array to join to a string |
$arr=array("Ram","Ravish","Rajeev","Rakesh","Ramesh");
$str=implode(",",$arr);
?>
echo $str;
?>
On execution above script produces the following output: 2. Convert the following Array to String: $my_arr1=array(“Mika”, “Mona”, “Mitali”, “Madhu”, “Megha”, “Meghna”);
Saturday, September 18, 2010
GETTING STARTED WITH PHP:
Testing your Environment
While there’s nothing wrong with getting started writing PHP scripts sing no-frills editors such as Windows Notepad or vi, chances are you’re soon going to want to graduate to a full-fledged PHP-specific development solution. Several open source and commercial solutions are available. The best way to verify your PHP installation is by attempting to execute a PHP script. Open a text editor and add the following lines to a new file: If you’re running Apache, save the file within the htdocs directory as phpinfo.php. Note: from now onwards this tutorial will use XAMPP from Apache Friends for development. You can still use Apache, but if you are having any problem configuring it, just uninstall Apache and install XAMPP. XAMPP is easy to install, no manual configuration required, and all components installed in one go (Apache + MySQL + PHP + phpMyAdmin). If you’re running IIS, save the file within C:\inetpub\wwwroot\. Now open a browser and access this file by entering the following URL:http://localhost/phpinfo.php. If all goes well, you should see output similar to that shown in Figure below:
The page above contains a lot of information related to your environment, such as: PHP core Configuration info, apache2handler info, Apache Environment info etc.
If you’re attempting to run this script on a Web hosting provider’s server, and you receive an error message stating phpinfo() has been disabled for security reasons, you’ll need to try Testing Your Installation executing another script. Try executing this one instead, which should produce some simple output:
Sunday, September 12, 2010
PHP backdoor security surprise uncovered
Everyone loves PHP these days it seems, and that includes the bad guys. So it should come as no surprise to learn that yet another remote access Trojan written using PHP has appeared. However, the fact that this particular bit of PHP backdoor code comes complete with a second, hidden, backdoor within it certainly was surprising to the security researcher who found it. DaniWeb has been talking to that researcher to find out more...
"Is there no honor among thieves anymore?" asks Andrew Brandt, the Lead Threat Analyst for security specialists Webroot, when disclosing the details of his PHP double backdoor discovery. It's a good question, albeit one that just begs an answer of 'was there ever?' to be fair. Being a threat analyst for a leading security vendor, Brandt spends a lot of time picking through exploit code. So it was not unusual for him to find himself examining the internal workings of a PHP remote access Trojan that loads into memory on a target computer when the victim strays upon the iframe which points to the PHP script sitting embedded in a web page. "The code is nicely appointed with such desirable features as the ability to execute shell commands on the host server, send a flood of data packets at another computer, and scan remote computers" Brandt reveals.
In fact, it's fairly standard bad guy stuff, albeit well written bad guy stuff. Until you start to dig a little deeper into the code, as Brandt found himself compelled to do, and find another backdoor embedded within the backdoor itself. "Someone’s bugged this bug with another bug" Brandt says, adding that the second chunk of code looks like a blob of base64-encoded garbage but decoding the base64-encoded text, set into the $dc_source variable, reveals that the bot writes out the commands into a Perl script to execute them. Invoked during the PHP bot's loading routine this commands the original bot to connect to a different control server, operated by another criminal enterprise to the ones that coded the original Trojan. No honor among thieves indeed, using someone else's code and distribution network to spread your own exploit around. You've got to admire the chutzpah of these guys. The 'Data Cha0s Connect Back Backdoor' is not exactly new, it has to be said, as a Google search reveals it first being seen as far back as 2005. The fact that it is still appearing in remote access Trojans being coded and distributed today is, however, rather worrying and suggests the gang behind it are still going strong.
DaniWeb spoke to Andrew Brandt and asked just how dangerous PHP is in the overall security threat landscape scheme of things?
"Many very useful websites or content management systems are built on a PHP framework. That said, PHP can and has been used as a tool for malicious activity, just like Javascript. PHP backdoors, bots, and download code has been part of the threat landscape for some time. There are hundreds of different bots, backdoors, and other malicious server-side PHP code floating around. But this isn't a problem with PHP, inherently, just as Windows malware isn't a C++ or Delphi problem. Malicious people will use whatever tools are at their disposal to engage in malicious activity. PHP happens to be a particularly powerful and useful tool, but whether one uses it for good or evil depends on the human doing the coding at the keyboard" Brandt says.
So what advice does Andrew have for DaniWeb members looking to mitigate the risk?
"There are two people who face risks from this kind of malware: The owners/operators of websites or web hosting companies, and the hapless web surfers who stumble upon these pages" Brandt replies, continuing "Website owners or hosting companies need to enact strict password policies that require users to create passwords of adequate complexity, and to change those passwords regularly. Passwords shouldn't be allowed to persist for longer than 90 days, to mitigate the damage that can be caused when, for example, the admin who normally uploads content to the server finds their computer compromised by the Zbot, Spyeye, or Koobface phishing Trojans. Anyone who uses an FTP client application on Windows needs to be aware of the special level of risks and threats posed by password stealing Trojans. Computers which are used for the purpose of maintaining websites or web content need to be protected with extra care, and not used for casual surfing, checking personal email, logging in to Facebook, or "letting the kids play games."
What about the web surfers? "Web surfers should protect themselves by using current, up-to-date antivirus, as well as some sort of scripting controls on their browser" Brandt insists, concluding "businesses can use filtering solutions to protect company computers from various attack scripts employees might stumble upon. Firefox has a great third-party add-on called NoScript which, by default, prevents scripts from running in a web page unless the user has selectively chosen to enable a particular site's scripts to run. This can, for example, prevent a rogue script hosted on an advertising server from running, while permitting you to use your favorite news or information website the way you normally would."
"Is there no honor among thieves anymore?" asks Andrew Brandt, the Lead Threat Analyst for security specialists Webroot, when disclosing the details of his PHP double backdoor discovery. It's a good question, albeit one that just begs an answer of 'was there ever?' to be fair. Being a threat analyst for a leading security vendor, Brandt spends a lot of time picking through exploit code. So it was not unusual for him to find himself examining the internal workings of a PHP remote access Trojan that loads into memory on a target computer when the victim strays upon the iframe which points to the PHP script sitting embedded in a web page. "The code is nicely appointed with such desirable features as the ability to execute shell commands on the host server, send a flood of data packets at another computer, and scan remote computers" Brandt reveals.
In fact, it's fairly standard bad guy stuff, albeit well written bad guy stuff. Until you start to dig a little deeper into the code, as Brandt found himself compelled to do, and find another backdoor embedded within the backdoor itself. "Someone’s bugged this bug with another bug" Brandt says, adding that the second chunk of code looks like a blob of base64-encoded garbage but decoding the base64-encoded text, set into the $dc_source variable, reveals that the bot writes out the commands into a Perl script to execute them. Invoked during the PHP bot's loading routine this commands the original bot to connect to a different control server, operated by another criminal enterprise to the ones that coded the original Trojan. No honor among thieves indeed, using someone else's code and distribution network to spread your own exploit around. You've got to admire the chutzpah of these guys. The 'Data Cha0s Connect Back Backdoor' is not exactly new, it has to be said, as a Google search reveals it first being seen as far back as 2005. The fact that it is still appearing in remote access Trojans being coded and distributed today is, however, rather worrying and suggests the gang behind it are still going strong.
DaniWeb spoke to Andrew Brandt and asked just how dangerous PHP is in the overall security threat landscape scheme of things?
"Many very useful websites or content management systems are built on a PHP framework. That said, PHP can and has been used as a tool for malicious activity, just like Javascript. PHP backdoors, bots, and download code has been part of the threat landscape for some time. There are hundreds of different bots, backdoors, and other malicious server-side PHP code floating around. But this isn't a problem with PHP, inherently, just as Windows malware isn't a C++ or Delphi problem. Malicious people will use whatever tools are at their disposal to engage in malicious activity. PHP happens to be a particularly powerful and useful tool, but whether one uses it for good or evil depends on the human doing the coding at the keyboard" Brandt says.
So what advice does Andrew have for DaniWeb members looking to mitigate the risk?
"There are two people who face risks from this kind of malware: The owners/operators of websites or web hosting companies, and the hapless web surfers who stumble upon these pages" Brandt replies, continuing "Website owners or hosting companies need to enact strict password policies that require users to create passwords of adequate complexity, and to change those passwords regularly. Passwords shouldn't be allowed to persist for longer than 90 days, to mitigate the damage that can be caused when, for example, the admin who normally uploads content to the server finds their computer compromised by the Zbot, Spyeye, or Koobface phishing Trojans. Anyone who uses an FTP client application on Windows needs to be aware of the special level of risks and threats posed by password stealing Trojans. Computers which are used for the purpose of maintaining websites or web content need to be protected with extra care, and not used for casual surfing, checking personal email, logging in to Facebook, or "letting the kids play games."
What about the web surfers? "Web surfers should protect themselves by using current, up-to-date antivirus, as well as some sort of scripting controls on their browser" Brandt insists, concluding "businesses can use filtering solutions to protect company computers from various attack scripts employees might stumble upon. Firefox has a great third-party add-on called NoScript which, by default, prevents scripts from running in a web page unless the user has selectively chosen to enable a particular site's scripts to run. This can, for example, prevent a rogue script hosted on an advertising server from running, while permitting you to use your favorite news or information website the way you normally would."
Subscribe to:
Posts (Atom)