Monday, November 17, 2008
Add Days to a Date
By using this function you can easily Add days into date and as well as subtract days from date.
//Example
$date = "2008-11-10";
$fdate = adddays($date,5);
echo fdate; //result : 2008-11-15
$date = "2008-11-10";
$fdate = adddays($date,-5);
echo fdate; //result : 2008-11-05
function adddays($date,$days){
$rs = $this->execute("select DATE_FORMAT(DATE_ADD('$date',INTERVAL $days DAY),'%Y-%m-%d') as newdate");
if($row = $this->row($rs)){
return $row["newdate"];
}else{
return "0000-00-00";
}
}
?>
Convert Date into SQL Date Format
this 00/00/0000 to 0000-00-00
Example:
$date = "15/11/2008";
$query = "INSERT INTO TB VALUES('".tosqldate($date)."')";
// result: 2008-11-15
function tosqldate($strdata){
$strdata = trim($strdata);
if($strdata==""){
return "";
}
$arrdate = explode("/",$strdata);
if(count($arrdate) < 3){
return "";
}else{
return $arrdate[2]."-".$arrdate[1]."-".$arrdate[0];
}
}
?>
Chage Date Format
// calling function
$date = "2008-11-15";
$fdate = formatdae($date);
echo $fdate; // Result: 15/11/2008
function formatdate($mysql_stamp,$type=1)
{
//$type = 1 date + time
//$type = 2 date
//$type = 3 time
// split mysql DATETIME stamp into date and time
if($mysql_stamp==""){
return "";
}
@list($date, $time) = split ('[ ]', $mysql_stamp);
@list($year, $month, $day) = split ('[-]', $date);
if( isset($time) && $time != "" )
{
list($hour, $minute, $second) = split ('[:]', $time);
if($hour>=12)
{
$ext = "PM";
$hour = $hour - 12;
}
else
{
$ext = "AM";
}
$time = " ".$hour.":".$minute." ".$ext;
}
else
{
$hour="";
$minute= "" ;
$ext = "";
$time = "";
}
if($type == 1)
$formatted_stamp = "$day/$month/$year".$time;
elseif($type==2)
{
$formatted_stamp = "$day/$month/$year";
}
elseif($type==3)
$formatted_stamp = $time;
return $formatted_stamp;
}
?>
Thursday, November 13, 2008
PHP interview Question
- How can we repair a MySQL table?
- What are the advantages of stored procedures, triggers, indexes?
- What is the maximum length of a table name, database name, and fieldname in MySQL?
- How many values can the SET function of MySQL take?
- What are the other commands to know the structure of table using MySQL commands except explain command?
PHP interview Preperation
2. 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.
3. 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. Look at the similar PHP interview questions for more numeric problems.
4. 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.
5. How do you define a constant? - Via define() directive, like define ("MYCONSTANT", 100);
6. How do you pass a variable by value? - Just like in C++, put an ampersand in front of it, like $a = &$b
7. 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.
8. 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.
9. 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.
10. How do I find out the number of parameters passed into function? - func_num_args() function returns the number of parameters passed in.
11. 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.
12. 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.
13. Are objects passed by value or by reference? - Everything is passed by value.
14. How do you call a constructor for a parent class? - parent::constructor($value)
15. 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.
16. Why doesn’t the following code print the newline properly?
$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.
17. 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.
18. How come the code works, but 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.
19. What is the difference between characters \023 and \x23? - The first one is octal 23, the second is hex 23.
20. With a heredoc syntax, do I get variable substitution inside the heredoc contents? - Yes.
21. 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.
22. 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:
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.
23. 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().
24. 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.
25. 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.
26. 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.
27. 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.
The Difference Between require() and include()
The key difference between require() and include() is that if you require() a file that can't be loaded (eg if it isn't there) then it generates a fatal error which will halt the execution of the page completely, and no more output will be generated. On the other hand, if you include() a file that can't be loaded, then this will merely generate a warning and continue building the page.
What one you should use depends on the situation; require() is best suited for loading files that are essential to the rest of the page - for example if you have a database driven website then using require() to include a file containing the database login and password is clearly preferred over using include(). If you used include() in this situation, then you may end up generating more warnings and errors than you had intended.
include() should be used when it isn't essential for that file to be loaded to execute the page. This is best used in situations where the file isn't essential to the processing of the page (for example a footer file), so if the file isn't present then the user can still view the site. You should, of course, make sure that all files you include() and require() are going to be available.
In PHP versions prior to 4.0.2. there was slightly different behaviour of require(). If you used a require() statement in an if block then the require() statement will always make sure that the file you're require()ing is readable, regardless of whether the condition was true for that if block to be processed. This is best illustrated with the following code example:
$a = 1;
if($a == 2) {
require("header.php");
}
?>
In this example, PHP versions before 4.0.2. will always make sure that header.php is available, but it will only actually execute the contents of it if $a is equal to 2.
More Explanation:
The principle differences between include() & require() are :
(1).When “Include()”ed file is not found,only warnings will be displayed& the script will continue to execute further.
But,when “require()”ed file is not found,fatal errors will be displayed & the script will halt execution.
When we are dealing with non-confedintial data,
inlude()is preffered.
e.g. When we are dealing with a form which posts Sachin Tendulkar’s age & no. of centuries ,after posting the form,
the variables age & no.centuries will be displayed on the URL of the opened active file.
If “include()” ed file doesn’t exist ,only waning will be given & the script will follow its execution afterwatds.
with including “require()” in our file ,we can safely process over confidential data ,such as user login form. Here both login ID & passwords are checked & script will continue only when “require()” function gets required file,otherwise,it will halt the script showing fatal error.
Friday, September 12, 2008
PHP htmlentities Function
HP - Converting HTML into Entities
The htmlentities function takes a string and returns the same string with HTML converted into HTML entities. For example, the string
"'";
//Lets make it safer before we use it
$userInputEntities = htmlentities($userInput);
//Now we can display it
echo $userInputEntities;
The HTML output of the above script would be as follows:
Safe Raw HTML Code:
I am going to hax0r your site, hahaha!
< script type='text/javascript' >
window.location = 'http://www.example.com/'
< /script >'
If we had not used htmlentities to convert any HTML code into safe entities, this is what the raw HTML code would be and it would have redirect a visitor to example.com.
Dangerous Raw HTML Code:
I am going to hax0r your site, hahaha!
window.location = 'http://www.example.com/'
'
Those two HTML code examples are what you would see if you were to view source on the web page. However, if you were just viewing the output normally in your browser you would see the following.
Safe Display:
I am going to hax0r your site, hahaha! '
Dangerous Display:
You'd see whatever spammer site that the malicious user had sent you to. Probably some herbal supplement site or weight loss pills would be displayed.
When Would You Use htmlentities?
Anytime you allow users to submit content to your website, that other visitors can see, you should consider removing the ability to let them use HTML. Although this will remove a lot of cool things that your users can do, like making heavily customized content, it will prevent your site from a lot of common attacks. With some custom coding you can just remove specific tags from running, but that is beyond the scope of this lesson.
Just remember, that when allowing users to submit content to your site you are also giving them access to your website. Be sure you take the proper precautions.
PHP - Filing
This section of the PHP tutorial is completely dedicated to how PHP can interact with files. After completing this section you should have a solid understanding of all types of file manipulation in PHP!
PHP - Files: Be Careful
When you are manipulating files you must be very careful because you can do a lot of damage if you do something wrong. Common errors include editing the wrong file, filling a hard-drive with garbage data, and accidentally deleting a file's contents.
It is our hope that you will be able to avoid these and other slipups after reading this tutorial. However, we know that there are so many places where code can take a wrong turn, so we urge you to take extra care when dealing with files in PHP.
PHP - Files: Overview
The presentation of the file lessons will begin with how to create, open, and close a file. After establishing those basics, we will then cover other important file tasks, such as: read, write, append, truncate, and uploading files with PHP.
PHP - File Create##########
Before you can do anything with a file it has to exist! In this lesson you will learn how to create a file using PHP.
PHP - Creating Confusion
In PHP, a file is created using a command that is also used to open files. It may seem a little confusing, but we'll try to clarify this conundrum.
In PHP the fopen function is used to open files. However, it can also create a file if it does not find the file specified in the function call. So if you use fopen on a file that does not exist, it will create it, given that you open the file for writing or appending (more on this later).
PHP - How to Create a File
The fopen function needs two important pieces of information to operate correctly. First, we must supply it with the name of the file that we want it to open. Secondly, we must tell the function what we plan on doing with that file (i.e. read from the file, write information, etc).
Since we want to create a file, we must supply a file name and tell PHP that we want to write to the file. Note: We have to tell PHP we are writing to the file, otherwise it will not create a new file.
PHP Code:
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);
The file "testFile.txt" should be created in the same directory where this PHP code resides. PHP will see that "testFile.txt" does not exist and will create it after running this code. There's a lot of information in those three lines of code, let's make sure you understand it.
1. $ourFileName = "testFile.txt";
Here we create the name of our file, "testFile.txt" and store it into a PHP String variable $ourFileName.
2. $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
This bit of code actually has two parts. First we use the function fopen and give it two arguments: our file name and we inform
PHP that we want to write by passing the character "w".
Second, the fopen function returns what is called a file handle, which will allow us to manipulate the file. We save the file handle into the $ourFileHandle variable. We will talk more about file handles later on.
3. fclose($ourFileHandle);
We close the file that was opened. fclose takes the file handle that is to be closed. We will talk more about this more in the file closing lesson.
PHP - Permissions
If you are trying to get this program to run and you are having errors, you might want to check that you have granted your PHP file access to write information to the hard drive. Setting permissions is most often done with the use of an FTP program to execute a command called CHMOD. Use CHMOD to allow the PHP file to write to disk, thus allowing it to create a file.
In the near future Tizag.com will have a more in-depth tutorial on how to use CHMOD to set file permissions.
PHP - File Open###########
In the previous lesson we used the function fopen to create a new file. In this lesson we will be going into the details of this important
function and see what it has to offer.
PHP - Different Ways to Open a File
For many different technical reasons, PHP requires you to specify your intentions when you open a file. Below are the three basic ways to open a file and the corresponding character that PHP uses.
* Read: 'r'
Open a file for read only use. The file pointer begins at the front of the file.
* Write: 'w'
Open a file for write only use. In addition, the data in the file is erased and you will begin writing data at the beginning of the file. This is also called truncating a file, which we will talk about more in a later lesson. The file pointer begins at the start of the file.
* Append: 'a'
Open a file for write only use. However, the data in the file is preserved and you begin will writing data at the end of the file. The file pointer begins at the end of the file.
A file pointer is PHP's way of remembering its location in a file. When you open a file for reading, the file pointer begins at the start of the file. This makes sense because you will usually be reading data from the front of the file.
However, when you open a file for appending, the file pointer is at the end of the file, as you most likely will be appending data at the end of the file. When you use reading or writing functions they begin at the location specified by the file pointer.
PHP - Explanation of Different Types of fopen
These three basic ways to open a file have distinct purposes. If you want to get information out of a file, like search an e-book for the occurrences of "cheese", then you would open the file for read only.
If you wanted to write a new file, or overwrite an existing file, then you would want to open the file with the "w" option. This would wipe clean all existing data within the file.
If you wanted to add the latest order to your "orders.txt" file, then you would want to open it to append the data on to the end. This would be the "a" option.
PHP - File Open: Advanced
There are additional ways to open a file. Above we stated the standard ways to open a file. However, you can open a file in such a way that reading and writing is allowable! This combination is done by placing a plus sign "+" after the file mode character.
* Read/Write: 'r+'
Opens a file so that it can be read from and written to. The file pointer is at the beginning of the file.
* Write/Read: 'w+'
This is exactly the same as r+, except that it deletes all information in the file when the file is opened.
* Append: 'a+'
This is exactly the same as r+, except that the file pointer is at the end of the file.
PHP - File Open: Cookie Cutter Below is the correct form for opening a file with PHP. Replace the (X) with one of the options above (i.e. r, w, a, etc).
Pseudo PHP Code:
$ourFileName = "testFile.txt";
$fh = fopen($ourFileName, 'X') or die("Can't open file");
fclose($fh);
PHP - File Open: Summary
You can open a file in many different ways. You can delete everything and begin writing on a clean slate, you can add to existing data, and you can simply read information from a file. In later lessons we will go into greater detail on how each of these different ways to open a file is used in the real world and give some helpful examples.
PHP - File Close####################
The next logical step after you have opened a file and finished your business with it is to close that file down. You don't want an open file running around on your server taking up resources and causing mischief!
PHP - File Close Description
In PHP it is not system critical to close all your files after using them because the server will close all files after the PHP code finishes execution. However the programmer is still free to make mistakes (i.e. editing a file that you accidentally forgot to close). You should close all files after you have finished with them because it's a good programming practice and because we told you to!
PHP - File Close Function
In a previous tutorial, we had a call to the function fclose to close down a file after we were done with it. Here we will repeat that example and discuss the importance of closing a file.
PHP Code:
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);
The function fclose requires the file handle that we want to close down. In our example we set our variable "$fileHandle" equal to the file handle returned by the fopen function.
After a file has been closed down with fclose it is impossible to read, write or append to that file unless it is once more opened up with the fopen function. Write, then this function might not work the way you expect it to.
PHP - File Delete##########
You know how to create a file. You know how to open a file in an assortment of different ways. You even know how to read and write data from a file!
Now it's time to learn how to destroy (delete) files. In PHP you delete files by calling the unlink function.
PHP - File Unlink
When you view the contents of a directory you can see all the files that exist in that directory because the operating system or application that you are using displays a list of filenames. You can think of these filenames as links that join the files to the directory you are currently viewing.
If you unlink a file, you are effectively causing the system to forget about it or delete it!
Before you can delete (unlink) a file, you must first be sure that it is not open in your program. Use the fclose function to close down an open file.
PHP - Unlink Function
Remember from the PHP File Create lesson that we created a file named testFile.txt.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fclose($fh);
Now to delete testFile.txt we simply run a PHP script that is located in the same directory. Unlink just needs to know the name of the file to start working its destructive magic.
PHP Code:
$myFile = "testFile.txt";
unlink($myFile);
The testFile.txt should now be removed.PHP - Unlink: Safety First!
With great power comes a slough of potential things you can mess up! When you are performing the unlink function be sure that you are deleting the right file!
PHP - File Append###########
So far we have learned how to open, close, read, and write to a file. However, the ways in which we have written to a file so far have caused the data that was stored in the file to be deleted. If you want to append to a file, that is, add on to the existing data, then you need to open the file in append mode.
PHP - File Open: Append
If we want to add on to a file we need to open it up in append mode. The code below does just that.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a');
If we were to write to the file it would begin writing data at the end of the file.
PHP - File Write: Appending Data
Using the testFile.txt file we created in the File Write lesson , we are going to append on some more data.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "New Stuff 1\n";
fwrite($fh, $stringData);
$stringData = "New Stuff 2\n";
fwrite($fh, $stringData);
fclose($fh);
You should noticed that the way we write data to the file is exactly the same as in the Write lesson. The only thing that is different is that the file pointer is placed at the end of the file in append mode, so all data is added to the end of the file.
The contents of the file testFile.txt would now look like this:
Contents of the testFile.txt File:
Floppy Jalopy
Pointy Pinto
New Stuff 1
New Stuff 2
PHP - Append: Why Use It?
The above example may not seem very useful, but appending data onto a file is actually used everyday. Almost all web servers have a log of some sort. These various logs keep track of all kinds of information, such as: errors, visitors, and even files that are installed on the machine.
A log is basically used to document events that occur over a period of time, rather than all at once. Logs: a perfect use for append!
PHP - File Truncate###########
As we have mentioned before, when you open a file for writing with the paramater 'w' it completely wipes all data from that file. This action is also referred to as "truncating" a file. Truncate literally means to shorten.
PHP - File Open: Truncate
To erase all the data from our testFile.txt file we need to open the file for normal writing. All existing data within testFile.txt will be lost.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
fclose($fh);
PHP - Truncate: Why Use It?
Truncating is most often used on files that contain data that will only be used for a short time, before needing to be replaced. These type of files are most often referred to as temporary files.
For example, you could create an online word processor that automatically saves every thirty seconds. Every time it saves it would take all the data that existed within some HTML form text box and save it to the server. This file, say tempSave.txt, would be truncated and overwritten with new, up-to-date data every thirty seconds.
This might not be the most efficient program, but it is a nice usage of truncate.
PHP substr_replace Function
substr_replace's Four Parameters
There are three required parameters for the substr_replace function (original string, replacement string, starting point) and one that's optional (length).
1. original string - This is your original string that will be operated on.
2. replacement string - This string will be used to replace everything in the string from the starting point to the ending point (specified by length).
3. starting point - This is the place in the original string that will be used to mark the replacement's beginning. A negative value specifies the number of characters from the end of the string.
4. optional length - How many characters from the original string will be replaced. If no length is specified then the end of the string is used. If a value of 0 is used then no characters will be replaced and an insert is performed. A negative value specifies the number of characters from the end of the string.
substr_replace On Your Mark
This example of substr_replace shows what happens when you omit the length parameter at various starting points.
PHP Code:
//string that needs to be customized
$original = "ABC123 Hello Mr. Cow! DEF321";
//starting point 5
$sp5 = substr_replace($original, "Five", 5);
//starting point 12
$sp12 = substr_replace($original, "Twelve", 12);
//starting point 0
$sp0 = substr_replace($original, "Zero", 0);
//starting point -1
$spneg1 = substr_replace($original, "Negative 1", -1);
//Echo each string
echo "Original String: $original
";
echo "Starting Point 5: $sp5
";
echo "Starting Point 12: $sp12
";
echo "Starting Point 0: $sp0
";
echo "Starting Point -1: $spneg1 ";
Display:
Original String: ABC123 Hello Mr. Cow! DEF321
Starting Point 5: ABC12Five
Starting Point 12: ABC123 HelloTwelve
Starting Point 0: Zero
Starting Point -1: ABC123 Hello Mr. Cow! DEF32Negative 1
As you can see, when you don't specify the fourth parameter, length, everything after the starting point is replaced by the second parameter replacement string.
Note: The first replacement occurred at position 5, which in $original was the character 3. This 3 and everything onward was replaced with the replacement string. Remember that you start counting character to begin from zero. The $original string could be labeled as
so:
* Letter A - Position 0
* Letter B - Position 1
* Letter C - Position 2
* Letter 1 - Position 3
* Letter 2 - Position 4
* Letter 3 - Position 5
substr_replace Specifying a Length
If you want to get any sort of precision out of this function you're going to have to get into the nitty gritty of specifying the exact length of characters you want replaced in your original string.
Imagine that you want to get rid of those ugly pseudo references (ABC123, DEF321) at the beginning and end of the string. Since both of those strings are a length of 6 and we know one is at the very beginning of the string and the other is at the very end of the string
we should probably use a starting point of 0 for ABC123 and a value of -6 for DEF321. By having a replacement string of nothing "" we can do something similar to select and delete that we often do in a word processor.
PHP Code:
//string that needs to be customized
$original = "ABC123 Hello Mr. Cow! DEF321";
//remove ABC123 and store in $cleanedstr
$cleanedstr = substr_replace($original, "", 0, 6);
//remove DEF321 from $cleanedstr
$cleanedstr2 = substr_replace($cleanedstr, "", -6, 6);
//Echo each string
echo "Original String: $original
";
echo "Clean #1: $cleanedstr
";
echo "Clean #2: $cleanedstr2";
Display:
Original String: ABC123 Hello Mr. Cow! DEF321
Clean #1: Hello Mr. Cow! DEF321
Clean #2: Hello Mr. Cow!
Make sure that you play around with this function some on your own so you can get a feel for how the starting point and length parameters effect this function.
substr_replace Perform an Insert
By setting the length parameter to zero you can stop substr_replace from removing anything from the original string and just add to it.
If we wanted to add a second and third person to our $original string we would want to do this insert operation. Note: instead of counting the characters we've used a couple other PHP functions to figure out the starting positions for us.
PHP Code:
//string that needs to be customized
$original = "Hello Mr. Cow!";
// Get the position of Mr. Cow
$cowpos = strpos($original, "Mr. Cow");
// Find where Mr. Cow ends by adding the length of Mr. Cow
$cowpos_end = $cowpos + strlen("Mr. Cow");
// Insert Mrs. Bear after Mr. Cow
$mrsbear = substr_replace($original, " and Mrs. Bear", $cowpos_end, 0);
// Insert Sensei Shark before Mr. Cow
$senseishark = substr_replace($mrsbear, "Sensei Shark, ", $cowpos, 0);
//Echo each string
echo "Original String: $original
";
echo "After Mrs. Bear: $mrsbear
";
echo "After Sensei Shark: $senseishark";
Display:
Original String: Hello Mr. Cow!
After Mrs. Bear: Hello Mr. Cow and Mrs. Bear!
After Sensei Shark: Hello Sensei Shark, Mr. Cow and Mrs. Bear!
We snuck a new function strlen into that example, but it isn't that complicated of a function, as it stands for "string length."
* $cowpos_end = $cowpos + strlen("Mr. Cow");
The strlen function takes a string and then counts up how many characters are in it then returns that number. So by calculating the length of "Mr. Cow" and adding that to the position, we find out where the end point is!
PHP - String Explode
explode to use the sentence's spaces " " as dynamite and it would blow up the sentence into separate words, which would be stored
in an array. The sentence "Hello, I would like to lose weight." would look like this after explode got done with it:
1. Hello,
2. I
3. would
4. like
5. to
6. lose
7. weight.
The dynamite (the space character) disappears, but the other stuff remains, but in pieces. With that abstract picture of the explode
function in mind, lets take a look at how it really works.
The explode Function
The first argument that explode takes is the delimiter (our dynamite) which is used to blow up the second argument, the original string.
explode returns an array of string pieces from the original and they are numbered in order, starting from 0. Lets take a phone number
in the form ###-###-#### and use a hyphen "-" as our dynamite to split the string into three separate chunks.
PHP Code:
$rawPhoneNumber = "800-555-5555";
$phoneChunks = explode("-", $rawPhoneNumber);
echo "Raw Phone Number = $rawPhoneNumber
";
echo "First chunk = $phoneChunks[0]
";
echo "Second chunk = $phoneChunks[1]
";
echo "Third Chunk chunk = $phoneChunks[2]";
Display:
Raw Phone Number = 800-555-5555
First chunk = 800
Second chunk = 555
Third Chunk chunk = 5555
explode Function - Setting a Limit
If you want to control the amount of destruction that explode can wreak on your original string, consider using the third (optional)
argument which allows you to set the number of pieces explode can return. This means it will stop exploding once the number of
pieces equals the set limit. Below we've blown up a sentence with no limit and then with a limit of 4.
PHP Code:
$someWords = "Please don't blow me to pieces.";
$wordChunks = explode(" ", $someWords);
for($i = 0; $i <>
echo "Piece $i = $wordChunks[$i]
";
}
$wordChunksLimited = explode(" ", $someWords, 4);
for($i = 0; $i <>
echo "Limited Piece $i = $wordChunksLimited[$i]
";
}
Display:
Piece 0 = Please
Piece 1 = don't
Piece 2 = blow
Piece 3 = me
Piece 4 = to
Piece 5 = pieces.
Limited Piece 0 = Please
Limited Piece 1 = don't
Limited Piece 2 = blow
Limited Piece 3 = me to pieces.
The limited explosion has 4 pieces (starting from 0, ending at 3). If you forgot how a for loop works, check out PHP For Loops.
PHP - Array implode
The first argument of implode is the string of characters you want to use to join the array pieces together. The second argument is the array (pieces).
PHP Code:
$pieces = array("Hello", "World,", "I", "am", "Here!");
$gluedTogetherSpaces = implode(" ", $pieces);
$gluedTogetherDashes = implode("-", $pieces);
for($i = 0; $i <>
echo "Piece #$i = $pieces[$i]
";
}
echo "Glued with Spaces = $gluedTogetherSpaces
";
echo "Glued with Dashes = $gluedTogetherDashes";
Display:
Piece #0 = Hello
Piece #1 = World,
Piece #2 = I
Piece #3 = am
Piece #4 = Here!
Glued with Spaces = Hello World, I am Here!
Glued with Dashes = Hello-World,-I-am-Here!
The implode function will convert the entire array into a string and there is no optional argument to limit this as there was in the explode function.
PHP Pattern
The singleton pattern applies to those situations in which there needs to be a single instance of a class. Implementing this pattern makes this single instance easily accessible by many other objects.
Example
class Example
{
// Hold an instance of the class
private static $instance;
// A private constructor; prevents direct creation of object
private function __construct()
{
echo 'I am constructed';
}
// The singleton method
public static function singleton()
{
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
// Example method
public function bark()
{
echo 'Woof!';
}
// Prevent users to clone the instance
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
}
?>
Magic Methods
The function names _construct, _sleep, _wakeup, _tostring are all magical methods in PHP. There cannot be any functions with these names in the classes. These functions can be had only if we want the magical functionality associated with them.
_sleep
The _sleep magic method is used to close any database connections that the object may have. It is also used to commit pending data and perform similar cleanup tasks. It is also used if there are very large objects which do not have to be saved completely.
_wakeup
The _wakeup magic method is used to reconstruct any resources that the object may have. The basic function of _wakeup is to reestablish any database connections that may have been lost during serialization and perform other initialization tasks.
Example of sleep and wakeup
class Conn {
protected $link;
private $server, $username, $password, $db;
public function __construct($server, $username, $password, $db)
{
$this->server = $server;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$this->connect();
}
private function connect()
{
$this->link = mysql_connect($this->server, $this->username, $this->password);
mysql_select_db($this->db, $this->link);
}
public function __sleep()
{
mysql_close($this->link);
}
tostring
The _tostring magic method allows a class to decide that how it will react when it is converted to string.
Example
// Declare a simple class
class Test
{
public $foo;
public function __construct($foo) {
$this->foo = $foo;
}
public function __toString() {
return $this->foo;
}
}
$class = new Test('Hello');
echo $class;
?>
Cloning
An object copy is created by using the clone keyword. An object's __clone() method cannot be called directly. When an object is cloned, PHP will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references. If a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed.
Example
class SubObject
{
static $instances = 0;
public $instance;
public function __construct() {
$this->instance = ++self::$instances;
}
public function __clone() {
$this->instance = ++self::$instances;
}
}
class MyCloneable
{
public $object1;
public $object2;
function __clone()
{
// Force a copy of this->object, otherwise
// it will point to same object.
$this->object1 = clone($this->object1);
}
}
$obj = new MyCloneable();
$obj->object1 = new SubObject();
$obj->object2 = new SubObject();
$obj2 = clone $obj;
print("Original Object:\n");
print_r($obj);
print("Cloned Object:\n");
print_r($obj2);
?>
PHP OOPS - Classes and Objects
What is a Class?
The Class in PHP is basically the same as in other languages such as Java. The class definition begins with the keyword class, followed by a class name. The form name can be any name except a reserved word or keyword in PHP. The class name is followed by a pair of curly braces which contain the definition of class members and methods.
Example of a Class
Class abc
{
//member functions and variables go here
}
?>
What is an Object?
An Object is an enclosed bundle of variables and functions which is copied from a Class. Objects provide an easy interface and hide a lot of their inner workings. The object sends orders through special functions called methods and they can return information.
While creating a Class, a set of characteristics is laid down. By creating Objects of that type, entities are created that share these characteristics but the Object might initialize them as different values.
Example
Suppose there is a class named building. This class would have a characteristic named floor. All the objects of class building would share the characteristics of floor, but some would initialize it to “one”, some to “two”, others to “three” or “four”, and so on.
The benefit of object oriented code is that it is re-useable. In this the classes can be used to create different objects and classes from one project can be used in other projects as well. Child classes can also be created which inherits the properties of the parent classes.
Creating an Instance
To start with, a class having no member functions and variables is not useful. For a class to be completely useful, member functions and variables have to be added in that class.
Let’s take an example of a class with a variable in it.
Example
Class abc
{
$a = “Hello!”;
}
?>
The class abc is the basis from which many objects can be instantiated. The new keyword is used to create an object. Now any abc object that is created contains a property called $a with the value of “Hello”. This property can be accessed and even be changed with the help of objects.
In this the -> operator is used to access or change the properties of the object.
In the following example $obj1 and $obj2 are the objects of the class abc. In this $obj2 has been assigned the string “Welcome to expertrating!” to its $a property.
Example
Class abc
{
var $a = "Hello";
}
$obj1 = new abc();
$obj2 = new abc();
$obj2->a = "Welcome to expertrating!";
echo "$obj1->a
";
echo "$obj2->a
";
?>
Extends
Another feature of object oriented programming is used in PHP, which is inheritance. In PHP a class a class can inherit methods, functions and members of other class by using the extends keyword in the declaration. In PHP it is not possible to inherit from multiple classes, a class can inherit from only one base class.
The class from which inheritance is done is called the parent class or base class and the class which inherits is called the child class.
The Keyword Final
The final keyword prevents the child classes from overriding a method. This can be done by prefixing the method with the keyword final. If the complete class is being defined as final then that class cannot be extended.
Example
final class test
{
//methods and functions
}
The class defined above i.e. class test cannot be overloaded as it has been finalized by using the keyword final with it.
Abstract
A new concept of abstract classes and methods has been introduced in PHP5. When a class is defined as abstract then it is not allowed to create the instance of that class. A class that contains at least one abstract method must also be abstract. The methods defined as abstract cannot define the implementation; they just declare the method’s signature.
When a child class is inheriting from an abstract parent class, then all the methods marked abstract in parent class declaration must also be additionally defined by the child class. These methods must be defined with the same or weaker access. This means that if an abstract method is declared as protected in the parent class then it must be declared either as protected or public in the child class.
Static Keyword
When class members or methods are declared as static then there is no need to instantiate that class. These members and methods are accessible without the instantiation of the class. If a member is declared as static then it cannot be accessed by an instantiated class object, but a method declared as static can be accessed by an instantiated class object.
The static declaration of a class must be after the visibility declaration (means that after the member or method has been declared as public, protected, or private).
The static method calls are resolved at compile time and static properties cannot be accessed through the object through the arrow operator (->).
Interfaces
Object interfaces allow the creation of a code which specifies that which method a class must implement, without having to define how these methods have to be handled.
Interfaces are defined in the same way as a class is defined. These interfaces are defined with the keyword “interface”. In the interface the contents of the methods do not have to be defined and all the methods declared in the interface must be declared as public.
Implementation of Interfaces
To implement an interface, the implements operator is used. The methods must be defined before implementation and all the methods in the interface must be implemented within a class.
Exceptions
Exception handling in PHP is similar to that of other programming languages. Within a PHP block of code we can throw, try and catch an exception. There must be at least one catch block in a try block. In this multiple catch blocks can be used to catch different class types. In exception handling the execution will continue after the last catch block has been encountered and exceptions can be thrown within catch blocks.
In exception handling when an exception is thrown, the code following the statement will not be executed rather PHP will attempt to find the first matching catch block. If the exception is not caught then it will result in a fatal error with an uncaught exception message.
This chapter will be focusing on some advanced class concepts, which will empower the reader to use classes in a better way and to create dynamic web pages.
Constructor
In PHP 5 developers can declare constructor methods for classes. In this, those classes which have a constructor method call this method for each newly created object. So, it is suitable for any initialization that the object may need before it is used. In this the parent constructors are not called implicitly if the child class defines a constructor.
Example
class ParentClass {
function __construct() {
print "In ParentClass constructor\n";
}
}
class ChildClass extends ParentClass {
function __construct() {
parent::__construct();
print "In ChildClass constructor\n";
}
}
$obj = new ParentClass();
$obj = new ChildClass();
?>
Destructors
The destructor concept is introduced in PHP 5. This destructor concept is similar to other object oriented languages. In this the destructor will be called as soon as all references to a particular object have been removed or when the object has been explicitly destroyed.
Example
class MyClass {
function __construct() {
print "In constructor\n";
$this->name = "MyClass";
}
function __destruct() {
print "Destroying " . $this->name . "\n";
}
}
$obj = new MyClass();
?>
Advanced PHP Topics - Superglobals
PHP Superglobals
* $_COOKIE – It contains values provided to the script via HTTP cookies.
* $_GET – It contains variables submitted to the script using HTTP get method.
* $_POST – It contains variables submitted to the script using HTTP post method.
* $_REQUEST – It is a combined array containing values from the $_GET, $_POST, and $_COOKIES superglobal arrays.
* $_ENV – It contains keys and values set by the script’s shell.
* $_FILES – It contains information about uploaded files.
* $_SERVER – It contains variables made available by the server.
* $GLOBALS – It contains all the global variables associated with the current script.
Instanceof Operator
The instanceof operator in PHP is used to determine whether a given object, the parents of that object, or its implemented interfaces are of a specified object class.
Example
class X { }
class Y { }
$thing = new X;
if ($thing instanceof X) {
echo 'X';
}
if ($thing instanceof Y) {
echo 'Y';
}
?>
Declare
The declare statement is used to set execution directives for a block of code. The syntax of the declare statement is similar to the syntax of other flow control statements.
Syntax
declare (directive)
statement
The directive section allows the behavior of the declare block to be set. In this only one directive is recognized, which is the ticks directive.
[ Ticks - A tick is an event that occurs for every N low level statements, which are executed within the declare block. The value of N is specified using the statement ticks = N in the directive section.]
The statement part of the declare block will be executed according to the directives set in the directive block.
Example
// how to use declare:
// the first way:
declare(ticks=1) {
// entire script here
}
// the second way:
declare(ticks=1);
// entire script here
?>
Sunday, September 7, 2008
Resizing images with PHP
* Author: Simon Jarvis
class SimpleImage {
var $image;
var $image_type;
function load($filename) {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if( $this->image_type == IMAGETYPE_JPEG ) {
$this->image = imagecreatefromjpeg($filename);
} elseif( $this->image_type == IMAGETYPE_GIF ) {
$this->image = imagecreatefromgif($filename);
} elseif( $this->image_type == IMAGETYPE_PNG ) {
$this->image = imagecreatefrompng($filename);
}
}
function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image,$filename,$compression);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image,$filename);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image,$filename);
}
if( $permissions != null) {
chmod($filename,$permissions);
}
}
function output($image_type=IMAGETYPE_JPEG) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image);
}
}
function getWidth() {
return imagesx($this->image);
}
function getHeight() {
return imagesy($this->image);
}
function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
}
function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$height);
}
function scale($scale) {
$width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100;
$this->resize($width,$height);
}
function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
}
?>
-------------------Usage-------------------
Save the above file as SimpleImage.php and take a look at the following examples of how to use the script.The first example below will load a file named picture.jpg resize it to 250 pixels wide and 400 pixels high and resave it as picture2.jpg
include('SimpleImage.php');
$image = new SimpleImage();
$image->load('picture.jpg');
$image->resize(250,400);
$image->save('picture2.jpg');
?>
If you want to resize to a specifed width but keep the dimensions ratio the same then the script can work out the required height for you, just use the resizeToWidth function.
include('SimpleImage.php');
$image = new SimpleImage();
$image->load('picture.jpg');
$image->resizeToWidth(250);
$image->save('picture2.jpg');
?>
You may wish to scale an image to a specified percentage like the following which will resize the image to 50% of its original width and height
include('SimpleImage.php');
$image = new SimpleImage();
$image->load('picture.jpg');
$image->scale(50);
$image->save('picture2.jpg');
?>
You can of course do more than one thing at once. The following example will create two new images with heights of 200 pixels and 500 pixels
include('SimpleImage.php');
$image = new SimpleImage();
$image->load('picture.jpg');
$image->resizeToHeight(500);
$image->save('picture2.jpg');
$image->resizeToHeight(200);
$image->save('picture3.jpg');
?>
The output function lets you output the image straight to the browser without having to save the file. Its useful for on the fly thumbnail generation
header('Content-Type: image/jpeg');
include('SimpleImage.php');
$image = new SimpleImage();
$image->load('picture.jpg');
$image->resizeToWidth(150);
$image->output();
?>
More Information:
for easily sharpening, bluring, cropping, brightening and colouring images.