Se afișează postările cu eticheta Beginners. Afișați toate postările
Se afișează postările cu eticheta Beginners. Afișați toate postările

luni, 6 decembrie 2010

PHP for Beginners: Part 4 – PHP With Forms and Final Notes

In the last part, I showed you how to use PHP to send e-mail messages. In this part I will continue this and also show you how to use PHP and forms together to make your PHP scripts more useful.

Setting up a form for use with a PHP script is exactly the same as normal in HTML. As this is a PHP tutorial I will not go into depth in how to write your form but I will show you three of the main pieces of code you must know:


This will display a text input box with Your Name written in it as default. The value section of this code is optional. The information defined by name will be the name of this text box and should be unique.


Will display a large scrolling text box with the text ‘Please write your message here.’ as default. Again, the name is defined and should be unique.


This will create a submit button for your form. You can change what it says on the button by changing the button’s value.


All the elements for your form must be enclosed in the


Form elements and formatting etc.

The form’s action tells it what script to send its data to (in this case its process_script.php). This can also be a full URL (e.g. http://www.mysite.com/scripts/process_script.php). The method tells the form how to submit its data. POST will send the data in a data stream to the script when it is requested. GET is the other option. GET will send the form data in the form of the url so it would appear after a question mark e.g. http://www.mysite.com/process_script.php?name=nick


It really makes no difference which system you use but it is normally better to use POST if you are using passwords or sensitive information as they should not be shown in the browser’s address bar.


The next step is to get the data the form has submitted into your script so that you can do something with it. There are basically two different methods of getting the data into PHP, which depend on how they were submitted. There are two submission methods, GET and POST, which can both be used by forms. The difference between the two is that using GET, the variables and data will be shown in the page address, but using POST it is invisible. The benefit of GET, though is that you can submit information to the script without a form, by simply editing the URL.


This works the same as submitting a form using GET. The advantage of this is that you can create links to your scripts which do different things depending on the link clicked. For example you could create a script which will show different pages depending on the link clicked:

yourpage.php?user=nick

could show Nick’s page and:

yourpage.php?user=laura

could show Laura’s page, using the same script.


It is also possible to pass more than one piece of information to the script using this system by separating them with the & symbol:

yourpage.php?user=nick&referrer=1stwebdesigner&area=6

These could all be accessed separately using the GET variables user, referrer and area.


To get a variable which has been sent to a script using the POST method you use the following code:

$variableName=$_POST['variable'];

which basically takes the variable from the POST (the name of a form field) and assigns it to the variable $variableName.


Similarly, if you are using the GET method you should use the following:

$variableName=$_GET['variable'];

This should be done for each variable you wish to use from your form (or URL).


To finish off this section, I will show you how to use what you have learnt in this part and the last to create a system which will e-mail a user’s comments to you.


Firstly, create this form for your HTML page:


Your Name:
E-mail:
Comments:


This will make a simple form where the user can enter their e-mail address, their name and their comments. You can, of course, add extra parts to this form but remember to update the script too. Now create the PHP script:


Remember to replace phpadmin@example.com with your own e-mail address. This script should be saved as mail.php and both should be uploaded. Now, all you need to do is to fill in your comments form.


The first part of that script may look a bit strange:

function checkOK($field) {if (eregi("\r",$field) || eregi("\n",$field)){die("Invalid Input!");}

You don’t really need to worry about what this is doing, but basically, it stops spammers from using your form to send their spam messages by checking special characters are not present in the input which can be used to trick the computer into sending messages to other addresses. It is a function which checks for these characters, and if they are found, stops running the script.


The lines like:

checkOK($name);[etc..]

run this check on each input to ensure it is valid.


As you can see, using forms with PHP can be very effective. Now it’s time to share with you some final small things you should know about PHP (which as i think, should go in the very first part :) But i placed them where they are).


As with any programming language, it is quite important to comment in your script. If you are working on a script with someone else you must let them know what you code does and if you are distributing your script you will need to show people how to edit it. Even if you are the only one who will use your script it is useful to comment so that you can edit it at a later date.


In PHP there are two ways you can comment. One way is used for single line comments and the other is used mainly for comments that go over one line. A single line comment is written as follows:

// Your comment can go in here

Everything after the // will be ignored when the script is executed. You can even place these on the end of another line e.g.

print "Hello $name"; // Welcome to the user

Another way of commenting is by using multi-line comments:

/* The following piece of code will take the inputthe user gave and will check that it is valid beforeadding it to the database */

Anything between the /* and the */ will be ignored. It is important that you always close this type of comment as not doing so could make your script not work.


As you may have noticed during this tutorial I have actually used 4 different ways of outputting information to the browser:

echo ("Text here");echo "Text here";print ("Text here");print "Text here";

To clarify, all of these do the same thing and you can use any or all of them in a script. There is no reason to even use the same type all through a script. The only problem you may find is that all the ” in the HTML code must be replaced with \” which, if you have a lot of code, could take a very long time. This brings me to a very useful part of PHP. If, for example, you created the header of a page dynamically in PHP, then had the static page and finally a dynamic footer you can do the following:

HTML Code

This gets even better as the PHP code will just continue from where it was left off so you could do the following:

HTML For IF Being CorrectHTML For IF Being Wrong

You must always remember to close IF statements and loops, though, as it is very easy to forget.


Being able to place HTML code into your PHP is very useful, but what happens if you want to put the value of a variable into the code. Unlike when using an echo or print statement, you can’t just put in the variable name as this section is not actually part of the PHP code. Instead you must just put in a little PHP.


For example, if you wanted to print someone’s name from a script with HTML formatting you would do the following:


* – As again, Never Do Inline Styling!


In the above code you have just added in the following PHP:


Which is exactly the same as the following PHP code:


But all put onto one line.


This tutorial has given you some of the basics of PHP and should allow you to do most things you will want to. For a much more in depth look you should visit PHP.net, the official homepage of PHP. One major omission of this tutorial, you may have noticed, is using PHP with a database. Happily, 1stWebDesigner already have one tut on it: Getting Started With MySQL DB and PHP with PHPMyAdmin. You should know this, as this is one of the major reasons that people use PHP and because there are many options.


Hope I helped you in learning such wonderful and powerful language as PHP. What would you like to learn more about PHP? Next articles ideas… I’d love to hear your thoughts in the comments below!


View the original article here

sâmbătă, 27 noiembrie 2010

PHP for Beginners: Part 3 – Email with PHP

Today We are continuing our PHP series. 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.


E-mails in PHP can be easily sent using the library function ‘mail’. This function takes four arguments to send E-mails from a PHP web page and returns ‘true’ upon successful delivery of Email. The parameters of this function are as follows:

Recipient E-mail addressE-mail SubjectE-mail message (body)Headers and additional parameters

Syntax:

mail( string to, string subject, string message [, string additional_headers [, string additional_parameters]] );

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-mail ( Sender E-mail address ) but you can also include other headers like cc and bcc.


This function returns the boolean value ‘True’ if the mail is sent successfully, otherwise it returns ‘False’.


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 = "demo@example.com";$subject = "PHP Rock";$body = "PHP is one of the best scripting languages around";$headers = "From: phpcoder@example1st.com\n";mail($to,$subject,$body,$headers);echo "Mail successfully sent to $to";

This code will actually do two things. Firstly it will send a message to demo@example.com with the subject ‘PHP Rock’ and the text:
PHP is one of the best scripting languages around
and the e-mail will be from phpcoder@example1st.com. It will also output the text:
Mail successfully sent to demo@example.com
to the browser.


Something you may have noticed from the example is that the From line ended with \n. This is actually 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.


PHP validate email script is an easy way to validate an email address. Use this quick and simple PHP regular expression for email validation. This is also case-insensitive, so it will treat all characters as lower case. It is a really easy way to check the syntax and format of an email address. Function will return TRUE if address is valid and FALSE if not.

function isValidEmail($email){return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);}

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("demo@example.com","PHP Rock","PHP is one of the best scripting languages around","From: phpcoder@example1st.com\n");

But that would make your code slightly harder to read.


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 explanatory. 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.


In addition to my previous Zend Framework tutorials, in this section i will introduce you another cool feature of that amazing framework, working with emails.


The Zend Framework’s Zend_Mail component, when coupled with the Zend Framework’s approach to minimizing redundancy and maximizing portability, offers the ideal solution for configuring and transmitting email through PHP-driven webpages. In this section, we will be using the Zend_Mail component.


First, within the application’s config.ini file, I define various parameters used to configure the transmission solution:

; emailemail.smtpserver = smtp.gmail.comemail.username = demo@example.comemail.password = strong_passwordemail.support = support@example.com

Within the bootstrap.php file, I configure Zend_Mail’s transport mechanism, drawing upon the parameters defined in config.ini:

$mailConfigs = array('auth' => 'login','username' => $config->email->username,'password' => $config->email->password,'ssl' => 'tls');$tr = new Zend_Mail_Transport_Smtp($config->email->smtpserver,$mailConfigs);Zend_Mail::setDefaultTransport($tr);

Although this executes with each request, the overhead required to do so is minimal and will not affect performance. Finally, I invoke code similar to the following from within the appropriate controllers:

try {// Create a new mail object$mail = new Zend_Mail();$mail->setFrom($this->config->email->from_admin);$mail->addTo("user@example.com");$mail->setSubject("Your account has been created");$email = "Thank you for registering!";$mail->setBodyText($email);$mail->send();$this->view->success = 1;} catch (Exception $e) {$this->view->errors[] = "We were unable to send yourconfirmation email. Please contact{$this->config->email->support}.";}

If you’d like to add an attachment, all you need to do is invoke the $mail object’s createAttachment() method:

$mail->createAttachment("file.pdf");

If you want to send HTML-formatted email, just use the setBodyHtml() method instead of setBodyText():

$mail->sendBodyHTML("Thank <b>you</b> for registering!");

Sending email from your PHP-powered websites is easy once you’ve been provided with the necessary background, so hopefully this tutorial helped alleviate any initial confusion you had in this regard. For further information, check out the following resources for more information about sending email using PHP:


In part 4 I will continue covering mail by showing you how to build a simple form to mail program in PHP. And will tell you some final notes :) So, see you in next part.


View the original article here