PHP Tutorial : E-mail With PHP

Wednesday, September 12, 2012

Introduction

One of the major uses of a server side scripting language is to provide a way of sending e-mail from the server and, in particular, to take form input and output it to an e-mail address. In this part I will show you how to send e-mail messages using PHP.

The Mail Command

Mail is extremely easy to send from PHP, unlike using scripting languages which require special setup (like CGI). There is actually just one command, mail() for sending mail. It is used as follows:

mail($to,$subject,$body,$headers);

In this example I have used variables as they have descriptive names but you could also just place text in the mail command. Firstly, $to. This variable (or section of the command) contains the e-mail address to which the mail will be sent. $subject is the section for the subject of the e-mail and $body is the actual text of the e-mail.

The section $headers is used for any additional e-mail headers you may want to add. The most common use of this is for the From field of an e-mai but you can also include other headers like cc and bcc.

Sending An E-mail

Before sending your mail, if you are using variables, you must, of course, set up the variable content beforehand. Here is some simple code for sending a message:

$to = "php@gowansnet.com";
$subject = "PHP Is Great";
$body = "PHP is one of the best scripting languages around";
$headers = "From: webmaster@gowansnet.com\n";
mail($to,$subject,$body,$headers);
echo "Mail sent to $to";

This code will acutally do two things. Firstly it will send a message to php@gowansnet.com with the subject 'PHP Is Great' and the text:

PHP is one of the best scripting languages around

and the e-mail will be from webmaster@gowansnet.com. It will also output the text:

Mail sent to php@gowansnet.com

to the browser.

Formatting E-mail

Something you may have noticed from the example is that the From line ended with \n. This is acutally a very important character when sending e-mail. It is the new line character and tells PHP to take a new line in an e-mail. It is very important that this is put in after each header you add so that your e-mail will follow the international standards and will be delivered.

The \n code can also be used in the body section of the e-mail to put line breaks in but should not be used in the subject or the To field.

Mail Without Variables

The e-mail above could have been sent using different variable names (it is the position of the variables in relation to the commas, not the name of them which decides on their use). It could also have been done on one line using text like this:

mail("php@gowansnet.com","PHP Is Great","PHP is one of the best scripting languages around","From: webmaster@gowansnet.com\n");

But that would make your code slightly harder to read.

Error Control

As anyone who has been scripting for a while will know, it is extremely easy to make mistakes in your code and it is also very easy to input an invalid e-mail address (especially if you are using your script for form to mail). Because of this, you can add in a small piece of code which will check if the e-mail is sent:

if(mail($to,$subject,$body,$headers)) {
echo "An e-mail was sent to $to with the subject: $subject";
} else {
echo "There was a problem sending the mail. Check your code and make sure that the e-mail address $to is valid";
}

This code is quite self explanitory. If the mail is sent successfully it will output a message to the browser telling the user, if not, it will display an error message with some suggestions for correcting the problem.

PHP Tutorial : Loops and Arrays

Introduction

In the last parts of this tutorial I have showed you how to deal with text and variables in PHP and how you can use IF statements to compare them and to make decisions. In this part I am going to show you how to use another important part of PHP, loops.

The WHILE Loop

The WHILE loop is one of the most useful commands in PHP. It is also quite easy to set up and use. A WHILE loop will, as the name suggests, execute a piece of code until a certain condition is met.

Repeating A Set Number Of Times

If you have a piece of code which you want to repeat several times without retyping it, you can use a while loop. For instance if you wanted to print out the words "Hello World" 5 times you could use the following code:

$times = 5;
$x = 0;
while ($x < $times) {
echo "Hello World";
++$x;
}

I will now explain this code. The first two lines are just setting the variables. The $times variable holds the number of times you want to repeat the code. The $x variable is the one which will count the number of times the code has been executed. After these is the WHILE line. This tells the computer to repeat the code while $i is less than $times (or to repeat it until $i is equal to $times). This is followed by the code to be executed which is enclosed in { }.

After the echo line which prints out the text, there is another very important line:

++$x;

What this does is exactly the same as writing:

$x = $x + 1;

It adds one to the value of $x. This code is then repeated (as $x now equals 1). It continues being repeated until $x equals 5 (the value of times) when the computer will then move on to the next part of the code.

Using $x

The variable counting the number of repeats ($x in the above example) can be used for much more than just counting. For example if you wanted to create a web page with all the numbers from 1 to 1000 on it, you could either type out every single one or you could use the following code:

$number = 1000;
$current = 0;
while ($current < $number) {
++$current;
echo "$current<br>";
}

There are a few things to notice about this code. Firstly, you will notice that I have placed the ++$current; before the echo statement. This is because, if I didn't do this it would start printing numbers from 0, which is not what we want. The ++$current; line can be placed anywhere in your WHILE loop, it does not matter. It can, of course, add, subtract, multiply, divide or do anthing else to the number as well.

The other reason for this is that, if the ++$current; line was after the echo line, the loop would also stop when the number showed 999 because it would check $current which would equal 1000 (set in the last loop) and would stop, even though 1000 had not yet been printed.

Arrays

Arrays are common to many programing languages. They are special variables which can hold more than one value, each stored in its own numbered 'space' in the array. Arrays are extremely useful, especially when using WHILE loops.

Setting Up An Array

Setting up an array is slightly different to setting up a normal variable. In this example I will set up an array with 5 names in it:

$names[0] = 'John';
$names[1] = 'Paul';
$names[2] = 'Steven';
$names[3] = 'George';
$names[4] = 'David';

As you can see, the parts of an array are all numbered, starting from 0. To add a value to an array you must specify the location in the array by putting a number in [ ].

Reading From An Array

Reading from an array is just the same as putting information in. All you have to do is to refer to the array and the number of the piece of data in the array. So if I wanted to print out the third name I could use the code:

n
echo "The third name is $names[2]";

Which would output:

The third name is Steven

Using Arrays And Loops

One of the best uses of a loop is to output the information in an array. For instance if I wanted to print out the following list of names:

Name 1 is John
Name 2 is Paul
Name 3 is Steven
Name 4 is George
Name 5 is David

I could use the following code:

$number = 5;
$x = 0;
while ($x < $number) {
$namenumber = $x + 1;
echo "Name $namenumber is $names[$x]<br>";
++$x;
}

As you can see, I can use the variable $x from my loop to print out the names in the array. You may have noticed I am also using the variable $namenumber which is always 1 greater than $x. This is because the array numbering starts from 0, so to number the names correctly in the output I must add one to the actual value.

PHP Tutorial : IF Statements

Introduction

Over the past two parts I have shown you the basics of text in PHP and how to store it as variables. In this part of the tutorial I will show you how to use IF statements to make decisions in your scripts.

The Basics Of IF

If statements are used to compare two values and carry out different actions based on the results of the test. If statements take the form IF, THEN, ELSE. Basically the IF part checks for a condition. If it is true, the then statement is executed. If not, the else statement is executed.

IF Strucure

The structure of an IF statement is as follows:

IF (something == something else)
{
THEN Statement
} else {
ELSE Statement
}

Variables

The most common use of an IF statement is to compare a variable to another piece of text, a number, or another variable. For example:

if ($username == "webmaster")

which would compare the contents of the variable to the text string. The THEN section of code will only be executed if the variable is exactly the same as the contents of the quotation marks so if the variable contained 'Webmaster' or 'WEBMASTER' it will be false.

Constructing The THEN Statment

To add to your script, you can now add a THEN statement:

if ($username == "webmaster") {
echo "Please enter your password below";
}

This will only display this text if the username is webmaster. If not, nothing will be displayed. You can actually leave an IF statement like this, as there is no actual requirement to have an ELSE part. This is especially useful if you are using multiple IF statements.

Constructing The ELSE Statement

Adding The ELSE statement is as easy as the THEN statement. Just add some extra code:

if ($username == "webmaster") {
echo "Please enter your password below";
} else {
echo "We are sorry but you are not a recognised user";
}

Of course, you are not limited to just one line of code. You can add any PHP commands in between the curly brackets. You can even include other IF statments (nested statements).

Other Comparisons

There are other ways you can use your IF statement to compare values. Firstly, you can compare two different variables to see if their values match e.g.

if ($enteredpass == $password)

You can also use the standard comparision symbols to check to see if one variable is greater than or less than another:

if ($age < "13")

Or :

if ($date > $finished)

You can also check for multiple tests in one IF statement. For instance, if you have a form and you want to check if any of the fields were left blank you could use:

if ($name == "" || $email == "" || $password == "") {
echo "Please fill in all the fields";
}

PHP Tutorial : Displaying Information & Variables

Introduction

In the last part of the tutorial I explained some of the advantages of PHP as a scripting language and showed you how to test your server for PHP. In this part I will show you the basics of showing information in the browser and how you can use variables to hold information.

Printing Text

To output text in your PHP script is actually very simple. As with most other things in PHP, you can do it in a variety of different ways. The main one you will be using, though, is print. Print will allow you to output text, variables or a combination of the two so that they display on the screen.

The print statement is used in the following way:

print("Hello world!");

I will explain the above line:

print is the command and tells the script what to do. This is followed by the information to be printed, which is contained in the brackets. Because you are outputting text, the text is also enclosed instide quotation marks. Finally, as with nearly every line in a PHP script, it must end in a semicolon. You would, of course, have to enclose this in your standard PHP tags, making the following code:

<?
print("Hello world!");
?>

Which will display:

Hello world!

on the screen.

Variables

As with other programming languages, PHP allows you to define variables. In PHP there are several variable types, but the most common is called a String. It can hold text and numbers. All strings begin with a $ sign. To assign some text to a string you would use the following code:

$welcome_text = "Hello and welcome to my website.";

This is quite a simple line to understand, everything inside the quotation marks will be assigned to the string. You must remember a few rules about strings though:

Strings are case sensetive so $Welcome_Text is not the same as $welcome_text
String names can contain letters, numbers and underscores but cannot begin with a number or underscore
When assigning numbers to strings you do not need to include the quotes so:

$user_id = 987

would be allowed.

Outputting Variables

To display a variable on the screen uses exactly the same code as to display text but in a slightly different form. The following code would display your welcome text:

<?
$welcome_text = "Hello and welcome to my website.";
print($welcome_text);
?>

As you can see, the only major difference is that you do not need the quotation marks if you are printing a variable.

Formatting Your Text

Unfortunately, the output from your PHP programs is quite boring. Everything is just output in the browser's default font. It is very easy, though, to format your text using HTML. This is because, as PHP is a server side language, the code is executed before the page is sent to the browser. This means that only the resulting information from the script is sent, so in the example above the browser would just be sent the text:

Hello and welcome to my website.

This means, though, that you can include standard HTML markup in your scripts and strings. The only problem with this is that many HTML tags require the " sign. You may notice that this will clash with the quotation marks used to print your text. This means that you must tell the script which quotes should be used (the ones at the beginning and end of the output) and which ones should be ignored (the ones in the HTML code).

For this example I will change the text to the Arial font in red. The normal code for this would be:

<font face="Arial" color="#FF0000">
</font>

As you can see this code contains 4 quotation marks so would confuse the script. Because of this you must add a backslash before each quotation mark to make the PHP script ignore it. The code would chang
e to:

<font face=\"Arial\" color=\"#FF0000\">
</font>

You can now include this in your print statement:

print("<font face=\"Arial\" color\"#FF0000\">Hello and welcome to my website.</font>");

which will make the browser display:

Hello and welcome to my website.

because it has only been sent the code:

<font face="Arial" color="#FF0000">Hello and welcome to my website.</font>

This does make it quite difficult to output HTML code into the browser but later in this tutorial I will show you another way of doing this which can make it a bit easier.

PHP Tutorial - Learn PHP

If you want to learn the basics of PHP, then you've come to the right place. The goal of this tutorial is to teach you the basics of PHP so that you can:

  • Customize PHP scripts that you download, so that they better fit your needs.
  • Begin to understand the working model of PHP, so you may begin to design your own PHP projects.
  • Give you a solid base in PHP, so as to make you more valuable in the eyes of future employers.
PHP stands for PHP Hypertext Preprocessor.

PHP - What is it?

Taken directly from PHP's home, PHP.net, "PHP is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly."
This is generally a good definition of PHP. However, it does contain a lot of terms you may not be used to. Another way to think of PHP is a powerful, behind the scenes scripting language that your visitors won't see!
When someone visits your PHP webpage, your web server processes the PHP code. It then sees which parts it needs to show to visitors(content and pictures) and hides the other stuff(file operations, math calculations, etc.) then translates your PHP into HTML. After the translation into HTML, it sends the webpage to your visitor's web browser.

PHP - What's it do?

It is also helpful to think of PHP in terms of what it can do for you. PHP will allow you to:
  • Reduce the time to create large websites.
  • Create a customized user experience for visitors based on information that you have gathered from them.
  • Open up thousands of possibilities for online tools. Check out PHP - HotScripts for examples of the great things that are possible with PHP.
  • Allow creation of shopping carts for e-commerce websites.

What You Should Know

Before starting this tutorial it is important that you have a basic understanding and experience in the following:
  • HTML - Know the syntax and especially HTML Forms.
  • Basic programming knowledge - This isn't required, but if you have any traditional programming experience it will make learning PHP a great deal easier.

Tutorial Overview

This tutorial is aimed at the PHP novice and will teach you PHP from the ground up. If you want a drive-through PHP tutorial this probably is not the right tutorial for you.
Remember, you should not try to plow through this tutorial in one sitting. Read a couple lessons, take a break, then do some more after the information has had some time to sink in.

Happy Birthday, Jennifer Hudson









One of the more talented, famous stars in all of Hollywood turns 31 years old today.
And we send our very best wishes to Jennifer Hudson on this special occasion!

The Oscar winner and former American Idol finalist has showed truly incredible strength in the face of incomprehensible personal pain over the last few years, following the murders of her mother, brother and nephew. She even said in an interview this week that she can't totally blame William Balfour for committing the crime.

Set to recur on Smash Season 2 in early 2013, the professional future is bright for this singer/actress. We wish her the absolute best.

Other famous folks celebrating a birthday today include: Ruben Studdard (34), Benjamin McKenzie (34), Paul Walker (39) and George Jones (81).



Lady Gaga. Shaves. Her. Head.





Lady Gaga shaved. her. head. Half of it anyway, in reputation of Terry Richardson's late mother. Seriously. This is a drastic hairstyle change, even by her standards.

"I did it for u Terry," she tweeted. "I'm sorry about ure mommy."

"She has princess die, but were all princess high." Profound.

The photo she posted shows the back of Lady Gaga's dome, hair pulled up into a high bun to reveal a gigantic triangular section of her hair shaven off.

Not sure how this relates to Terry's mom, but nice sentiment.

Famous photographer Richardson, a longtime friend of Gaga, is grieving this week. He posted on Tumblr, "R.I.P. Annie Lomax, My Mom 1938-2012."

In 2011, he released a book titled Lady Gaga X Terry Richardson. If you haven't seen it or guessed, it features all of Terry's Lady Gaga pictures.
 
Too bad this one didn't make it. Maybe Volume II?

George Clooney and Stacy Keibler: Still Together!


Breathe easy, Klooney fans. All is well in beautiful paradise between George Clooney and Stacy Keibler.

A rep for the Oscar-winning star has come out and slammed a report in Great Britain's The Sun that claims the actor and the former WWE Diva have split. Simply put, the statement reads:
"A story published by a London tabloid, The Sun, concerning George Clooney and Stacy Keibler [is] not true... [It is a] total fabrication designed to sell newspapers."


Clooney and his latest gorgeous gal pal went public with their romance almost exactly one year ago, walking the red carpet at the Toronto International Film Festival in 2011.

Despite rumors to the contrary, all appears to be very well between the twosome, with the exception of their anger over THG readers labeling Blake Lively and Ryan Reynolds the Hottest Couple Ever.

Sedition: does it have any place in modern India?




Now that Kanpur-based cartoonist Aseem Trivedi has been charged with sedition for his cartoons that 'mocked' the country's political class, Parliament and the national emblem, one has to bear in mind that the word "sedition" does not actually figure anywhere in the Indian Constitution. It is an offence against the state as enumerated in the Indian Penal Code which is an 1860 Act ratified by the British to rule over Indians. Section 124 A of the IPC was drawn up in 1860, just three years after the British East India Company had weathered the storm of the Sepoy Mutiny. 

So yes, the case against Aseem is registered under Section 124A of the IPC that is an 1860 Act which defines sedition as: "Whoever by words, either spoken or written, or by signs, or by visible representation, or otherwise, brings or attempts to bring into hatred or contempt, or excites or attempts to excite disaffection towards the Government established by law in India, shall be punished with imprisonment for life, to which fine may be added, or with imprisonment which may extend to three years, to which fine may be added, or with fine." 

A member of Repubican Party of India, Amit Katarnayea, had filed a complaint against Trivedi that the latter had put up banners mocking the Indian constitution during the Anna Hazare rally held last year at the Bandra Kurla Complex. 

Before Aseem, Dr Binayak Sen was also charged under the same section, a charge the court threw away after the Chhattisgarh government's attempts to put Sen away drew international rebuke. Many prominent Indians - from Tilak to Gandhi to Jogendra Chandra Bose - have faced sedition charges. 

In India, where 'ignorance of law is no excuse,' the Constitution however guarantees freedom of speech and expression. Article 19(1)(A) of the Indian Constitution says that all citizens have the right to freedom of speech and expression. The right to freedom of speech and expression incorporates protection for austerely censuring existing government structures, policies and administrative schemes, coupled with protection for suggesting and recommending the development of other system. Article 19 (2) of Indian Constitution says that, every citizen of the country holds the right to air his or her opinion through the printing or the electronic media, with certain restrictions imposed.
The recent cases of Dr Sen and Aseem reveal the archaic nature of sedition charges, something that is not quite in sync with a modern democracy which cherishes the ideals of freedom of expression and speech. It is one of those numerous IPC codes drawn up in British India to help the British Police to lord over native Indians, to crush every small protest against British rule. Police reforms and an overhaul of police laws is the only way to ensure that such regressive and irrelevant sections are relegated to the pages of legal history.

Sedition and treason: the difference between the two



After the arrest of cartoonist Aseem Trivedi under sedition charges, it has become important to understand what is and can be construed as sedition and how it is different from treason.
Sedition is an overt subversive act which leads to incitement against status quo or authority or order. It is a challenge to the establishment. It may be a book, a painting, an idea, a speech, pretty much anything that can act as a vehicle of an anti-establishment idea.

Treason, on the other hand, involves colluding with anti-national forces in terms of providing material support to people or groups who work against the idea of one's nation.

So sedition is against a government in power where as treason is violation of one's allegiance to one's country or sovereign. Sedition threatens a government or individuals in power and treason threatens the entire country with all its people.

However, in many societies the differences between the two have become blurred and sedition has been closely linked to acts of terrorism and public safety violation.

It is to be noted that the Section 124A of IPC which was slapped agaainst Aseem is an 1860 Act that was promulgated by the British Raj to help control its Indian subjects. Where as the anti-sedition law was abolished in the UK in 2010, in India it has been levied twice in the last five years - against Dr Binayak Sen and Aseem Trivedi. There have been calls for charges under Section 124A to be formed against writer Arundhuti Roy for her comments on Kashmir and the Maoist issue.

Emma Watson named most 'dangerous' cyber celebrity



Emma Watson is the favorite celebrity bait for cyber criminals trying to lure Internet users. McAfee said Monday that the 'Harry Potter' star is the "most dangerous" celebrity to search for online. That's because many sites use Watson to trick users into downloading malicious software or to steal personal information. 

When searching for the 22-year-old Watson, there's a one-in-eight chance of landing on a malicious site. 

This is the sixth time the Intel-owned security technology company has conducted the study, which was last year topped by Heidi Klum. Female celebrities are far more likely to be utilized by cyber criminals: late-night host Jimmy Kimmel was the only male in the top 20. 

Others among the riskiest celebrities to search online are Jessica Biel, Eva Mendes, Selena Gomez and Halle Berry.


O.J. Simpson-Khloe Kardashian Bombshell: Alleged Killer Changes Will to Include Rumored Offspring

 
O.J. Simpson believes Khloe Kardashian is his daughter and plans on changing his will to reflect this fact.

According to a new story in The National Enquirer, that is.
The same tabloid that first floated the Kardashian-belongs-to-O.J. rumor in January is now fueling that seemingly absurd allegation by claiming Simpson wants to "do the right thing" and leave a sizable chunk of his estate to the reality star.

Moreover, he wants to do it at older daughter Arnelle's expense, an anonymous insider claims, because Simpsons thinks she has squandered his money on a lavish, drunken lifestyle.

Currently sitting in a prison cell, convicted of armed robbery and kidnapping, O.J. has stashed away a couple million in the Cayman Islands and can expect more over the years due to his NFL pension, which pays him an annual sum of $300,000.

Based on this story, Simpson told his four kids - Arnelle, Jason, Sydney and Justin – that he's changing his will to give a lot of that fortune to Khloe... and their reaction was less than enthusiastic.
“At first they thought he was just making a big joke, but when they realized he was serious, they were flabbergasted,” says a source. “They are furious and wonder why they have to share the wealth with a complete stranger.”

The children should just be thankful they're alive, really. But they don't see it that way.

“By cutting Arnelle out of his will, his kids feel O.J. is being cruel," adds the insider. "And they think that adding Khloe is just plain revenge. I’m sure if O.J. kicks the bucket and leaves Khloe money in his will, she’s not going to turn it down."
We're equally sure. Almost as sure as we are that Khloe Kardashian is not actually O.J. Simpson's daughter.

[Photo: WENN.com/Fayesvision]

 
Support :
Copyright © 2011. All In One Blog - All Rights Reserved
Template Created by Creating Website Inspired by Sportapolis Shape5.com
Proudly powered by Blogger