Employing PHP operators
function make_thumb($img_name,$filename,$new_w,$new_h)
{
//get image extension.
$ext=getExtension($img_name);
//creates the new image using the appropriate function from gd library
if (!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
{
$src_img = imagecreatefromjpeg($img_name);
}
if (!strcmp("png",$ext))
{
$src_img = imagecreatefrompng($img_name);
}
if (!strcmp("gif",$ext))
{
$src_img = imagecreatefromgif($img_name);
}
PHP operators are symbols and sometimes text that we can use to manipulate variables and their respective values. Using the operator in this way is called using operators in operations.
The item that the operator acts upon is called the operand. There are several types of operators in PHP below is a listing of all of the specific types of them and examples.
- String Operators
- Arithmetic Operators
- Assignment Operators
- Combined Operators
- Reference Operators
- Comparison Operators
- Logical Operators
- Bitwise Operators
- Bonus Operators (bonus meaning "more")
String Operators
Operators that act upon strings
Usually referred to concatenation operators. This type of operator is used to connect two strings together.
- . (period) like connecting strings
- .= (period equal) like addition for strings
Arithmetic Operators
Operators that act upon integers
These operators are used in conditional statements acting upon integers.
- + (addition)
- - (subtraction)
- * (multiplication)
- / (division)
- % (modulus)
Assignment Operators
Operators that assign
Assignment operators assign something to something else, like a value to a variable.
- = (equal)
Combined Operators
Operators that use two operators to do one job
These operators are used as shorthand for doing more complex operations.
- += ($a = $a + $b)
- -= ($a = $a - $b)
- *= ($a = $a * $b)
- /= ($a = $a / $b)
- %= ($a = $a % $b)
- .= ($a = $a . $b)
Reference Operators
Operators that create a reference from one item to another
- &
Basically, $b = &$a means, that $b references the value of $a from this point forward in your script, so if $a changes below your reference, then the value of the referenced variable changes with the new assignment of $a as long as it happens below the referenced call in your script.
There is expanded explanation in the, "Avoid Replication with the PHP Reference Operator" post
Comparison Operators
Operators that compare two or more things
You can use these operators to compare two values.
- == (equivalent too)
- === (identical, including data type)
- != (NOT equivalent too)
- <> (NOT equivalent too)
- < (less than)
- > (greater than)
- >= (greater than and equivalent too)
- <= (less than and equivalent too)
- instanceof (used to determine if an instance of an object is of a specific type, inherits from a specific type, or implements a specific interface)
Logical Operators
Operators that combine the results of logical conditions
You will use these operators in conditional statements like in the IF statement
- ! (not)
- && (AND)
- ¦¦ (OR)
- AND (AND)
- OR (OR)
Bitwise Operators
Operators that treat integers as a series of bits
- & (bitwise AND)
- ¦ (bitwise OR) bits set in $ OR $b are set in the result $C
- ˜ (bitwise NOT)any BITS contained in $a are not set in the result $C
- ˆ (bitwise XOR)compares $A and $B, any bits not set in both are returned as the value of $C
- << (left shift) SHIFTS a variable $a LEFT $b bits
- >> (right shift)SHIFTS a variable $a RIGHT $b bits
bits set in $ AND $b are set in the result $C
Bonus Operators (bonus meaning "more")
A variety of uncategorized operators
- Ternary Operator
- Error Suppression Operator
- Execution Operator
Ternary Operators: act like an expression version of an IF else statement. the following in an example situation where using the Ternary Operator will be of great service to us as PHP programmers.
- ?: (question mark colon
- $a = condition ? value IF condition is true : value IF condition is false
<!--?php $sentence = $value == 1 //variable that recieves the assignment and the condition ? 'You have one egg.' // what $sentance equals if the condition is TRUE : 'You have '.$value.' eggs.'; // what $sentance equals if the condition is FALSE this is the default value ?-->
Error Suppression Control Operator: You will use this symbol to prepended to an expression in PHP, then any error messages that could be generated by said expression will be ignored by PHP and your script will continue.
- @ (AT)
<!--?php @require_once("file.php") //would negate the reason to require a file ?-->
Execution Operator: These are NOT single quotes rather the stroke combined with the tilde(˜) key on many keyboards. REMEMBER: The backtick operator is disabled when safe mode is enabled or shell_exec() is disabled. Use of the backtick operator is identical to shell_exec() function.
- `` (backticks) must use two in conjunction
- if you have a problem with your script and you cannot seem to locate it, use dreamweaver to search for the backtick, you might have fat fingered it accidentally.
<!--?php $output = shell_exec('ls -lart'); echo "$output"; //wrap in pre tags ?-->
PHP Variable Type Strength
Setting Explicit Variable Type in PHP
In PHP the variable types are not explicitly set the majority of the time since PHP is not a strongly typed programming language. "Strongly typed" means that you explicitly define the variable type when defining a variables values.
With PHP you can however specify a specific type for your variable with PHP variable type casting, or type juggling. There are several ways that you can stipulate the type of variable you want. They are as follows:
- Type casting:
- settype() Function:
Type Casting
When using Type Casting the following cast values are accepted.
- (int), (integer) - cast to integer
- (bool), (boolean) - cast to boolean
- (float), (double), (real) - cast to float
- (string) - cast to string
- (array) - cast to array
- (object) - cast to object
- (unset) - cast to NULL (PHP 5+)
Example of Type Casting
$myVar = 100; // $myVar is an integer $anotherVar = (boolean) $myVar; // $anotherVar is a boolean
settype() Function
When using the settype() Function the following values are accepted.
- "boolean" (or, since PHP 4.2.0, "bool")
- "integer" (or, since PHP 4.2.0, "int")
- "float" (only possible since PHP 4.2.0, for older versions use the deprecated variant "double")
- "string"
- "array"
- "object"
- "null" (since PHP 4.2.0)
Example of settype()
$myVar = "50var"; // type is auto set to string $anotherVar = true; // type is auto set to boolean settype($myVar, "integer"); // $myVar is now set to 50 type:integer settype($anotherVar, "string"); // $anotherVar is now set to "1" type:string
Increment and Decrement Operator
As you have probably thought prior to coming here, "I wish there was a way to increase or decrease a number without the need to use plus and minus operators over and over." Well if that was what your were thinking, then your idea has been realized with PHP "++"Increment and "--"Decrement.
This works the same in PHP and in JavaScript!
The way all this works is that normally to increase or decrease a number by one, you would need to do the following:
++/- - Pre-Increment / Decrement
<?php $a = 10; //we need to increase $a by 1, normally we would do the following... $a = $a + 1; // $a is now 11 //we need to decrease $a by 1, normally we would do the following... $a = $a - 1; // $a is now 9 //There is a better way $b = 10; ++$b //$b = 11 because we Incremented it by 1 first, by using the Increment operator "--" then returned its value --$b //$b is 10 again because we first decremented it by 1 using the decrement operator "--" then returned its value //The value of $b has literally changed, since the operator appeared prior to our variable ?>
With the above example showing how to increment and decrement a number by one, there is a little bit of a tricky situation happening behind the scenes. Since we placed the increment and decrement operator prior to the variable, in actuality behind the scenes PHP parser see the following :
PHP sees ++$a or --$a and literally, what takes place is that the PHP parser takes the value of $a and increments or decrements it by one, and then returns the value of $a incremented or decremented. The value of $b has literally changed, since the operator appeared prior to our variable, and that altered variable is then applied immediatly
However, in the following example something a little different takes place... Consider the following example where we move the increment/decrement operator after the variable we are working with.
Post-Increment / Decrement ++/- -
<?php $a = 10; //we need to increase $a by 1, normally we would do the following... $a = $a + 1; // $a is now 11 //we need to decrease $a by 1, normally we would do the following... $a = $a - 1; // $a is now 9 //There is a different way with different results than the prior example $b = 10; echo $b++; //what will echo is 10, however if we echo it again it will show 11 echo $b //will be 11 because it was echoed after it was incremented echo $b--; //what will echo is 10, however if we echo it again it will show 9 echo $b //will be 9 because it was echoed after it was decremented ?>
The returned value for $b remains as it was prior to the operator acting upon it because the variable $b appears prior to the operator. Since the operator is after the variable it then makes the value chang, and when we use it a second time, it has the altered value because the operator took place after the variable.
Therefore, to make it clear; placing the operator prior to the number makes PHP act upon the variable prior to returning it. Otherwise, if the operator is placed after the variable, PHP acts upon the variable after its value is returned, meaning it returns the initial value first, and is then acted upon. Therefore, the second usage of the variable is where the alteration is noticed when the operator is placed after the variable.
Avoid Replication with the PHP Reference Operator
Since PHP version 4+ PHP has offered us a way to reduce memory usage in our programs when assigning a variable to another variable. Normally when you assign the value of one variable to another separate variable, the variable that is getting assigned to another is then duplicated by PHP in memory to be used in the operation.
What this means for us as programmers is that if we want to take the value of one variable and assign it to another, we must fist allow PHP to duplicate the variable so that it may be assigned to another.
The reference operator must be used in conjunction with the assignment operator.
We can circumvent this activity by using what is called the reference operator "&". Here is an example:
<?php $a = 10; $b = $a; //$a is duplicated in the background by PHP so that it can be assigned to $b // $b is no 10 //avoid duplicating the assigned variable using the reference operator "&" $a = 10; $b = &$a; //& used in conjunction with the assignment operator $a = 15; //$a and $b = 15 and there is only one $a ?>
The way this works is that even after $b is assigned "&$a" later in the script when $a changes so does $b because the variable that was assigned to $b is not a copy, but the value of $a no matter where is its as long as it is after the assignment using the reference operator.
Basically, $b = &$a means, that $b references the value of $a from this point forward in your script, so if $a changes below your reference, then the value of the referenced variable changes with the new assignment of $a as long as it happens below the referenced call in your script.
Connecting the Dots with Concatenation
Within PHP there is a consistent need to connect things together to create a new entity. Such as taking two strings and creating one string. This is usually done with variables that have a string value. The most common type of concatenation is done with strings, however you can do this with numbers but the results are not what you might expect, which would be addition of the two numbers. Instead if you concatenate the number 5 and the number 6, you do not get 11, instead you get the string "56".
When you have two variables such a one for a first name and one for a last name which is most common in form input. You may want to display a welcome message to your visitor based on their login session. To do so, you might think you would have to use either their first name or last name individually, however this would be incorrect.
There are two operators that can be used to concatenate items. They are the period "." and the period/equal operator ".=".
The "." will temporarily attach one item to the next for your current operation. The ".=" will create one item out of two instead of just temporarily attaching it to the other item.
Lets take a look at the following code:
<?php $first_name = 'Shaded'; $last_name = 'Pixel'; echo 'Hello '; //echo hello with a space after it echo $first_name; //the first name echo ' '; //echo a space echo $last_name; //the last name //the result would be: Hello Shaded Pixel //OR we could use the "period" concatenation operator echo 'Hello ' . $first_name . ' ' . $last_name; //the result would be the same as above: Hello Shaded Pixel //This way you only need one echo statement instead of four //The second way is to create a new variable using the ".=" $hello = 'Hello'; $hello .= ' '; //a space $hello .= $first_name; $hello .= ' '; //a space $hello .= $last_name; echo $hello; //result is Hello Shaded Pixel /* notice in the second example that each operator after the first assignment to $hello uses the ".=" meaning that the variable $hello, continues to obtain more and more information as the statements persist, the end result is one variable that holds the entire greeting */ //FYI: $a .= $b // is the same as $a = $a . $b; ?>
The first example of the greeting using the "." is the correct choice for this example. However, the second example using the ".=" will work. The most common use for this type of concatenation is for error messages. You can create messages throughout your script, concatenating them together using the ".=" and in the end echo out one variable that contains your error messages.
An upgrade to this idea would be to use an array of messages, and then echo out the messages from your array instead, which is a more common practice.
Zooming in on PHP Variable Scope
Variables within php have a property that is called "scope". Scope refers to places within your php script that you can use your variable, and where you cannot.
Within PHP there are four specific types of scope.
- SuperGlobal Scope
- This type of scope are available everywhere within your scripts.
- Global Scope
- This type of scope are visible throughout your script however they are not visible inside of a function (this can be overcome by using Function Global Scope)
- Function Scope
- This type of scope relates to variables created within functions. Meaning that any variable created within a function is only visible to your script within the function.
- Function Global Scope
- This type of scope relates to variables created outside of your functions. If you declare a variable inside your function as "global", this "global" variable is not global to your entire script, however this definition of "global" inside of a function points to the value of a variable outside of your function that has been defined as global as previously defined. you would tend to think that defining a variable "global" inside of a function would make that variable available to your entire script, however this is wrong. this definition points your local function variable to the counterparts value defined outside your function (example follows)
<?php //define a variable outside of our function $var_two = 2; //global scope, meaning it is global to your current script function your_function($variable_one) { $var = "one"; $var_two = 4; //function scope variable, local to inside the function only $var_three = global $var_two //$var_two is equivalent to "2" set outside the function //$var_three is now set to "2" } ?>
Constantly Remaining Constant
Constants are special types of variables that recieve a value and from then on can no longer be changed. this type of variable has a special place in PHP. It is normailly used when you have something that needs to be contained in a variable that iwll never change in your script, or has the potential of bing overwritten accidentially, and you wish to prevent aht from happening.
Many of the programmers in the PHP community borrow a syntax from the "C" programming language when defining a constant. That syntax is to name the constant variable in all capital letters like so.
- A constant with a string value:
- A constant with a number value:
<?php define('YOURCONSTANT', 'your_string_value') ?>
<?php define('YOURNUMBERCONSTANT', 100000) ?>
Naming your constants with this naming convention will help you and other programmers distinguish your constants from other variables and text. When you call your constant, like in an echo statement you do not call it with a dollar sign in front of it like you do with other variable types. This is another significant difference between constants and other types of variables within PHP.
<?php echo YOURCONSTANT ?>
The output for this echo statement will be, "your_string_value" depending on what you placed as your value. Remember that strings need to be within quotes, and numbers need not be.
Calling all PHP “SUPERGLOBALS”
In PHP there are a set of variables called "SuperGlobals". These variables are of a special type and they carry along with them their own set of rules that define when and where they are available, called their scope.
The only difference between SuperGlobals and normal variables is; they can be seen everywhere in your scripts.
A list of these are as follows :
- $GLOBALS
- Holds an array of all global variables.
- $_SERVER
- Holds an array of all server enviroment variables.
- $_GET
- Holds an array of all the varialbes passed to the script through the GET method.
- $_POST
- Holds an array of all the varialbes passed to the script through the POST method.
- $_REQUEST
- Holds an array of all the varialbes passed to the script through the GET and POST methods, otherwise called user input variables.
- $_COOKIE
- Holds an array of all the cookie variables.
- $SESSION
- Holds an array of all the session variables.
- $_FILES
- Holds an array of all the variables associated to file uploads.
- $_ENV
- Holds an array of all the enviroment variables.
PHP Code Survival Guide “Rules to Live by”
Throughout my learning of PHP I have gained a few outstanding ideas as to how to make your PHP code survive the test of time. First of all read as many books and articles as time permits. If you truly want to be a proficient programmer of any type, you will never stop reading. Nor will you say, "I am the expert of all experts" no matter what stage your career is in.
Words to live by: One thing I have learned, that is now engrained into my soul is, "Every day I do not learn PHP. I learn how much PHP I do not know."
"Rules to Live by" while programming PHP:
- Never assume you know anything. If you have a doubt about the interaction of any function no matter if you created it or not, or whether it is a built in PHP function. Assume you know nothing about it, and research it to the best of your ability prior to using it for the first time, or the one hundredth time.
- Always use the XML style PHP open and closing tags:
- Or use the Script style tags, to defeat hiccups with older style tags:
- I suggest you never use the short stye PHP tags, as it will make all your code far less portable.
- One other major concern when using scripts created during the rein of PHP 4 I see far too often is the use of the PHP environment configuration setting of register_globals to be turned on. This prior to PHP 5 was nativly turned on, in PHP 5+ is is nativly off. The environment variable register_globals can cause your scripts to be breached due to security holes. The setting register_globals when on creates a variable automatically for any form field using the name of the field itself as a variable name. For instance if we had a form field as follows:
- The PHP register_globals would automatically create a variable using the form field name of "fieldOne". That would look like "$fieldOne" in your PHP code. The ability to use this might seem advantageous, however it could allow your users or a hacker to inject their own variables into your script at will unless you take the necessary steps to prevent this from happening. The easiest way to ensure that your scripts are not vulnerable through this type of attack is to turn register_globals off when using a PHP version below version 5, or just use the default setting that come with PHP version 5 or higher.
<?php /*your code*/ ?>
<?script language='php'> /*your code*/ </script>
<? /*your code*/ ?>
<input type="text" name="fieldOne" />PHP Email Form Script
This is a PHP script that you can use to place a form on any webpage that can parse PHP code. This PHP code snippet will allow you're users to email you from your web page. All you need to do is place the following XHTML and PHP code onto a page with the ".php" extension; otherwise it will not work as intended.
Paste the PHP code onto your page first. Then paste the XHTML onto your page below the PHP. You will need to change all instances of the email address to your own email; otherwise you will never see any email arrive into your inbox.
If you have any questions please post them and I will gladly point you into the right direction.
The PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | <?php date_default_timezone_set('America/Kentucky/Louisville'); // you may want to change this to your own timezone if you do not live in the EST timezone // Check for form submission: if (isset($_POST['submitted'])) { // Minimal form validation: if (!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['comments']) ) { // Create the body: $body = "Name: {$_POST['name']}\n\nComments: {$_POST['comments']}"; // Make it no longer than 70 characters long: $body = wordwrap($body, 70); // Send the email: mail('your.email@yourdomain.com', 'Website Email Form Submission', $body, "From: {$_POST['email']}"); // Print a message: echo '<p><strong><em>Thank you for contacting me at ' . date('g:i a') . ' ' . 'EST' . ' ' . 'on ' . date('l F j, Y') .'. I will reply ASAP.</em></strong></p>'; // Clear $_POST (so that the form's not sticky): $_POST = array(); } else { echo '<p style="font-weight: bold; color: #C00">Please fill out the form completely.</p>'; } } // End of main isset() IF. // Create the HTML form: ?> |
The XHTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <div id="email_page"> <!-- Fill in the action inside the quotes if you would like to use a seperate file to parse your file output. By default this is blank because the PHP code that handles the form output and response back to your visitors is in built into this code... --> <form action=" " method="post"> <p>Please fill out and submit this form to contact <em>Your Name</em> via e-mail at <a href="mailto:your.email@yourdomain.com" title="Email Me" title="Email Me">your.email@yourdomain.com</a></p> <p>Name: <input type="text" name="name" size="42" maxlength="60" value="<?php if (isset($_POST['name'])) echo $_POST['name']; ?>" /> </p> <p>Email Address: <input type="text" name="email" size="34" maxlength="80" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>" /></p> <p>Comments: <textarea name="comments" rows="5" cols="30"><?php if (isset($_POST['comments'])) echo $_POST['comments']; ?></textarea></p> <p><input type="submit" name="submit" value=" Submit E–mail " title="Click Here to Submit Your E-mail to Me"/></p> <p><input type="hidden" name="submitted" value="TRUE" /></p> </form> </div> |