Page Content

Tutorials

What Are the PHP Features with code Examples

PHP Features

PHP has a wide range of features that go well beyond just creating HTML content. These include handling network connections like emailing, interacting with structured data like XML, and generating dynamic material like graphics.

Generating Images (using GD)

PHP’s dynamic picture creation capability is one of its strong points. The GD extension library is the main tool used by PHP to create and modify graphics. Many utilities for creating and modifying photos are available in this library.

Although PHP often comes with the GD library, it is frequently not activated by default. In order to enable it on UNIX operating systems, PHP must often be compiled with the –with-gd option. It is often enabled on Windows by uncommenting the line in your php.ini file that corresponds to it and using the supplied php_gd2.dll. Although this particular function check isn’t specifically addressed it’s a standard PHP practice. You can also check GD installation using function_exists(‘imagecreate’) or phpinfo() under the GD section. The included GD library or GD2 library is needed.

The GD library lets PHP produce and manipulate JPEG, PNG, and WBMP images. Versions beyond 1.6 supported PNG but not GIF, while versions before 1.6 supported both. Due to patent concerns with its compression method, GD version 1.6 stopped supporting GIF. In early 2000, GD was updated to support JPEG and WBMP.

The GD library is frequently used to create bar charts, dynamically resize images, graph data, create images with text and distortions for CAPTCHA to protect forms, and draw figures. Images can be rotated, resized, scaled, and text added.
The basic procedure for using PHP to dynamically generate a picture consists of the following steps:

  1. Making the canvas of images.
  2. Designating the colours that will be utilised in the picture.
  3. Adding text, lines, or other shapes to the picture.
  4. Confirming to the client or browser that the output is an image by setting the appropriate HTTP Content-Type header.
  5. Producing the image data in the preferred format (such as JPEG or PNG).
  6. Destroying the picture to free up memory is an optional step.

This code sample to use GD to create a black square on a white background:

<?php
$image = imagecreate(200, 200); // Creating the image
$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF); // Allocating white color
$black = imagecolorallocate($image, 0x00, 0x00, 0x00); // Allocating black color
imagefilledrectangle($image, 50, 50, 150, 150, $black); // Drawing a filled rectangle
header("Content-Type: image/png"); // Setting the header to indicate a PNG image
imagepng($image); // Outputting the image as PNG
// imagedestroy($image); // 
?>


Although it is commented out in the example given, the imagedestroy() function is used to release memory related to the image.

Apart from GD, ImageMagick is another popular PHP image library that may be used through the PECL Imagick extension.
While GD2 and ImageMagick have many functions in common, ImageMagick might have more functionality, such as the ability to create animated GIFs. Digital image metadata can be extracted using the Exif extension.

Working with XML

A number of PHP extensions are available for creating and interpreting XML data. Working with online services and managing structured data require familiarity with XML. SimpleXML, DOM (Document Object Model), XSLT (XSL Transformations), SOAP (Simple Object Access Protocol), and WDDX (Web Distributed Data Exchange) are a few of the pertinent extensions mentioned.
PHP installations frequently come with the SimpleXML and DOM extensions activated by default. Processing node and attribute values, building unique node collections, and comparing XML to DTDs or schemas are some of the activities they are helpful for. XSLT allows XML documents to be transformed using XSLT style sheets. Additionally, these technologies make it easier to integrate with various Web services and create and parse RSS feeds.

The features of various XML extensions, the snippets do not specifically include a comprehensive code example for parsing or converting XML using SimpleXML, DOM, or XSLT. Nonetheless, a WDDX example of working with XML is provided. WDDX is a data sharing standard based on XML. Similar to HTML, WDDX packets use tags to enclose textual data, but they can convey any kind of data. PHP variables can be utilised to construct a WDDX packet using the wddx_serialize_vars() function.

This is an example of code that uses WDDX to serialise variables:

<?php
//create test data
$Name = "Leon Atkinson";
$Email = "corephp@leonatkinson.com";
$Residence = "Martinez";
$Info = array("Email", "Residence");
//print packet
print(wddx_serialize_vars("Name", $Info));
?>


This example shows how variables can be serialised into an XML format for data interchange using PHP and WDDX.

Sending Emails

The built-in mail() function in PHP can be used to send emails. It is said to be the most straightforward method of sending emails from PHP.
Three required arguments are needed for the mail() function:

  • The email address of the addressee.
  • The subject line of the email. There cannot be any newline characters in this parameter.
  • The email’s content, or the message body. Generally, lines should not be more than 70 characters and should be divided by an LF (\n).

This is a basic example with the necessary parameters:

mail('recipient@example.com', 'Email Subject', 'This is the email message body');

For more legitimate email headers, the fourth parameter is utilised. A CRLF (\r\�) or \n characters (or \r\� characters on Windows servers) should be used to separate these headers. Additional headers include things like From, Reply-To, Cc, and Bcc. Unless you provide them yourself, the Date: and From: headers are appended automatically on Windows.

  • An extra parameter can be passed to the software set up to send mail (such as sendmail) using the optional fifth parameter.

The use of variables and the optional headers argument is illustrated in the following example:

<?php
$to      = 'recipient@example.com';
$subject = 'Email Subject';
$message = 'This is the email message body';
$headers = implode("\r\n", [
    'From: webmaster@example.com',
    'Reply-To: webmaster@example.com',
    'X-Mailer: PHP/' . PHP_VERSION
]);
// invoke mail() function to send mail
if (mail($to, $subject, $message, $headers)) {
    echo "Message successfully delivered to mail agent"; // Example success message 
} else {
    echo "Message could not be delivered to mail agent"; // Example failure message 
}
?>

The first option (to) allows you to specify a list of recipients separated by commas. Multiple recipients can also be listed in headers like To:, CC:, and BCC:, with commas between them.

An illustration with extra headers and several recipients:

<?php
$to = "me@myisp.co.uk, recipient-2@someisp.co.uk";
$subject = "My email test.";
$message = "This is the body of the email";
$headers = "From: me@myisp.co.uk\r\n";
$headers .= "Reply-To: me@myisp.co.uk\r\n";
$headers .= "CC: recipient-3@someisp.co.uk\r\n";
$headers .= "BCC: recipient-4@someisp.com\r\n";
if ( mail($to,$subject,$message,$headers) ) { // Example of checking return value 
    echo "The email has been sent!";
} else {
    echo "The e-mail has failed!";
}
?>

Mail() returns true if the email ran successfully, false otherwise. The return result indicates if PHP delivered the email, but it does not guarantee it reached the recipient’s inbox.

Mail() requires MIME-Version, Content-type, and charset headers to send HTML emails.

Sending an HTML email with mail():

<?php
$to      = 'recipent@example.com';
$subject = 'Sending an HTML email using mail() in PHP';
$message = '<html><body><p><b>This paragraph is bold.</b></p><p><i>This text is italic.</i></p></body></html>';
$header  = "From:abc@somedomain.com \r\n";
$header .= "Cc:afgh@somedomain.com \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail ($to,$subject,$message,$header);
if( $retval == true ) {
    echo "Message sent successfully...";
}else {
    echo "Message could not be sent...";
}
?>

To utilise mail(), PHP must be configured in php.ini with email delivery information. For Windows users, this entails setting sendmail_from to your personal email address and the SMTP directive to the email server address. The path to the mailer software is specified by the sendmail_path directive.

Despite its simplicity, mail() might not be appropriate for every task. For instance, because it creates a new socket connection every time it is called, it is ineffective for sending large amounts of emails. Using the mail() function alone to send emails with attachments necessitates exploring MIME specifications (such as RFC 1341). To add more capability, make complicated tasks like delivering MIME multipart messages (containing HTML and attachments) easier, or offer a simpler solution, libraries like PHPMailer or PEAR’s Mail and Mail_Mime packages are available.

Index