Skip to content

9. PHP Network Functions

We will now discuss PHP’s network functions, which allow us to perform TCP/IP (Transmission Control Protocol/Internet Protocol) programming.

9.1. Retrieving the name or IP address of a machine on the Internet (inet_01)


<?php

// Machine name <--> machine IP address functions
ini_set("display_errors", "off");
// constants
$HOSTS = array("istia.univ-angers.fr", "www.univ-angers.fr", "www.ibm.com", "localhost", "", "xx");
// IP addresses of the machines in $HOTES
for ($i = 0; $i < count($HOTES); $i++) {
  getIPandName($HOTES[$i]);
}
// end
exit;

//------------------------------------------------
function getIPandName($machineName) {
//$machineName: name of the machine whose IP address is wanted
// machineName --> IP address
  $ip = gethostbyname($machineName);
  if ($ip != $machineName) {
    print "ip[$machineName]=$ip\n";
// IP address --> machineName
    $name = gethostbyaddr($ip);
    if ($name != $ip) {
      print "name[$ip]=$name\n";
    } else {
      print "Error, machine[$ip] not found\n";
    }
  } else {
    print "Error, machine[$machineName] not found\n";
  }
}

Results:

ip[istia.univ-angers.fr]=193.49.146.171
name[193.49.146.171]=istia.istia.univ-angers.fr
ip[www.univ-angers.fr]=193.49.144.40
name[193.49.144.40]=ametys-fo.univ-angers.fr
ip[www.ibm.com]=129.42.56.216
Error, machine[129.42.56.216] not found
ip[localhost]=127.0.0.1
name[127.0.0.1]=localhost127.0.0.1
ip[]=192.168.1.11
name[192.168.1.11]=st-PC.home
Error, machine [xx] not found

Comments

  • Line 4: We instruct the system not to display runtime errors.

PHP's network functions are used in the getIpandName function on line 15.

  • Line 18: The gethostbyname($name) function retrieves the IP address "ip3.ip2.ip1.ip0" of the machine named $name. If the machine $name does not exist, the function returns $name as the result.
  • Line 22: The gethostbyaddr($ip) function retrieves the hostname of the machine with the IP address $ip in the format "ip3.ip2.ip1.ip0". If the machine $ip does not exist, the function returns $ip as the result.

9.2. A web client ( inet_02)

A script to retrieve the content of a website's index page.


<?php

// error handling
ini_set("display_errors","off");
// retrieve the HTML text from the URL
// list of websites
$SITES = array("istia.univ-angers.fr", "www.univ-angers.fr", "www.ibm.com", "xx");
// read the index pages of the sites in the $SITES array
for ($i = 0; $i < count($SITES); $i++) {
// read the index page of the site $SITES[$i]
  $result = getIndex($SITES[$i]);
// display result
  print "$result\n";
}//for
// end
exit;

//-----------------------------------------------------------------------
function getIndex($site) {
// reads the URL $site/ and stores it in the file $site.html
// create the $site.html file
  $html = fopen("$site.html", "w");
  if (!$html)
    return "Error creating the $site.html file";

// Open a connection on port 80 of $site
  $connection = fsockopen($site, 80);
// return if error
  if (!$connection)
    return "Failed to connect to the site ($site,80): $error";
// $connection represents a bidirectional communication stream
// between the client (this program) and the contacted web server
// this channel is used for exchanging commands and information
// The communication protocol is HTTP
// the client sends the GET request to retrieve the URL /
// get URL syntax: HTTP/1.0
// HTTP protocol headers must end with a blank line
  fputs($connection, "GET / HTTP/1.0\n\n");
// The server will now respond on the $connexion channel. It will send all
// this data and then close the channel. The client therefore reads everything coming from $connexion
// until the channel is closed
  while ($line = fgets($connection, 1000))
    fputs($html, $line);
// The client closes the connection in turn
  fclose($connection);
// close the $html file
  fclose($html);
// return
  return "Successful transfer of the index page of the $site website";
}

Results: for example, the file received for the site [www.ibm.com]:

HTTP/1.1 302 Found
Date: Wed, 08 Jun 2011 15:43:56 GMT
Server: IBM_HTTP_Server
Content-Type: text/html
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Pragma: no-cache
Cache-Control: no-cache, must-revalidate
Location: http://www.ibm.com/us/en/
Content-Length: 209
Kp-eeAlive: timeout=10, max=14
Connection: Keep-Alive

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>302 Found</title>
</head><body>
<h1>Found</h1>
<p>The document has moved <a href="http://www.ibm.com/us/en/">here</a>.</p>
</body></html>
  • Lines 1–11 are the HTTP headers of the server’s response
  • line 1: the server instructs the client to redirect to the URL specified in line 8
  • line 2: date and time of the response
  • line 3: web server identity
  • Line 4: Content sent by the server. Here, an HTML page that begins on line 13
  • Line 12: The empty line that ends the HTTP headers
  • Lines 13–19: The HTML page sent by the web server.

Code comments:

  • line 7: the list of URLs for the websites whose index pages we want. These will be stored in the text file [sitename.html].
  • Line 11: The getIndex function does the work
  • line 19: the getIndex($site) function downloads the root page (or index page) of the $site website and stores it in the text file $site.html.
  • line 27: the fsockopen($site,$port) function creates a connection with a TCP/IP service running on port $port of the $site machine. Once the client/server connection is open, many TCP/IP services exchange lines of text. This is the case here with the HTTP (HyperText Transfer Protocol). The data stream from the server to the client can then be treated as a text file. The same applies to the data stream from the client to the server.
  • Line 38: The fputs function allows the client to send data to the server. Here, the text line sent has the following meaning: "I want (GET) the root page (/) of the website I am connected to. I am using HTTP version 1.0." The current version of this protocol is 1.1.
  • Line 42: The text lines of the server’s response can be read line by line using a while loop and saved to the text file [$site.html]. Once the web server has sent the requested page, it closes its connection with the client. On the client side, this will be detected as an end-of-file.

9.3. An SMTP client (inet_03)

Among TCP/IP protocols, SMTP (Simple Mail Transfer Protocol) is the communication protocol for the mail delivery service.

Notes:

  • On a Windows machine with antivirus software, the antivirus will likely prevent the PHP script from connecting to port 25 of an SMTP server. You must therefore disable the antivirus. For McAfee, for example, you can do this:
  • In [1], open the VirusScan console
  • In [2], stop the [On-Access Protection] service
  • in [3], it is stopped

The script:


<?php

// SMTP (Simple Mail Transfer Protocol) client for sending a message
// the information is taken from a file named $INFOS containing the following lines
// line 1: smtp, sender, recipient
// subsequent lines: the message text
// sender: sender's email
// recipient: recipient's email
// smtp: name of the SMTP server to use
// SMTP client-server communication protocol
// -> client connects to port 25 of the SMTP server
// <- server sends a welcome message
// -> client sends the EHLO command: its hostname
// <- server responds with OK or not
// -> client sends the mail from command: <sender>
// <- server responds with OK or not
// -> client sends the rcpt to command: <recipient>
// <- server responds OK or not
// -> client sends the data command
// <- server responds OK or not
// -> client sends all lines of its message and ends with a line containing the
// single character .
// <- server responds OK or not
// -> client sends the quit command
// <- server responds OK or not
// Server responses are in the form xxx text, where xxx is a 3-digit number. Any number xxx >=500
// indicates an error. The response may contain multiple lines, all starting with xxx except the last one
// in the form xxx(space)
// exchanged text lines must end with the characters RC(#13) and LF(#10)

// data
$INFOS = "mail.txt"; // email sending parameters
// retrieve the email parameters
list($error, $smtpServer, $sender, $recipient, $message) = getInfo($INFO);
// error?
if ($error) {
  print "$error\n";
  exit;
}
print "Sending message [$smtpServer,$sender,$recipient]\n";
// send email in verbose mode
$result = sendmail($smtpServer, $sender, $recipient, $message, 1);
print "Result of sending: $result\n";
// end
exit;

//-----------------------------------------------------------------------
function getInfo($file) {
// returns the information ($smtp, $sender, $recipient, $message) from the text file $file
// line 1: smtp, sender, recipient
// following lines: the message text

// open $file
  $info = fopen($file, "r");
// does the file $file exist
  if (!$info)
    return array("The file $file could not be opened for reading");
// read the first line
  $line = fgets($info, 1000);
// Remove the end-of-line character
  $line = cutNewLineChar($line);
// retrieve the smtp, sender, and recipient fields
  $fields = explode(",", $line);
// Do we have the correct number of fields?
  if (count($fields) != 3)
    return "Line 1 of the file $file (SMTP server, sender, recipient) has an
incorrect number of fields";
// "Processing" the retrieved information
  for ($i = 0; $i < count($fields); $i++)
    $fields[$i] = trim($fields[$i]);
// retrieve the fields
  list($smtpServer, $sender, $recipient) = $fields;
// read message
  $message = "";
  while ($line = fgets($info, 1000))
    $message.=$line;
  fclose($info);
// return
  return array("", $smtpServer, $sender, $recipient, $message);
}

//-----------------------------------------------------------------------

function sendmail($smtpServer, $sender, $recipient, $message, $verbose) {
// sends $message to the $smtpServer SMTP server on behalf of $sender
// to $recipient. If $verbose=1, logs client-server exchanges
// retrieve the client's name
  $client = gethostbyaddr(gethostbyname(""));
// Open a connection on port 25 of $smtpServer
  $connection = fsockopen($smtpServer, 25);
// return if error
  if (!$connection)
    return "Failed to connect to the server ($smtpServer,25)";
// $connection represents a bidirectional communication channel
// between the client (this program) and the contacted SMTP server
// this channel is used for exchanging commands and information

// After the connection, the server sends a welcome message that we read
  $error = sendCommand($connection, "", $verbose, 1);
  if ($error) {
    fclose($connection);
    return $error;
  }

// "hello" command:
  $error = sendCommand($connection, "EHLO $client", $verbose, 1);
  if ($error) {
    fclose($connection);
    return $error;
  }

// mail command from:
  $error = sendCommand($connection, "MAIL FROM: <$sender>", $verbose, 1);
  if ($error) {
    fclose($connection);
    return $error;
  }

// RCPT TO command:
  $error = sendCommand($connection, "RCPT TO: <$recipient>", $verbose, 1);
  if ($error) {
    fclose($connection);
    return $error;
  }

// data command
  $error = sendCommand($connection, "DATA", $verbose, 1);
  if ($error) {
    fclose($connection);
    return $error;
  }

// prepare message to send
  // it must contain the following lines
  // From: sender
  // To: recipient
  // blank line
  // Message
  // .
  $data = "From: $sender\r\nTo: $recipient\r\n$message\r\n.\r\n";
  $error = sendCommand($connection, $data, $verbose, 0);
  if ($error) {
    fclose($connection);
    return $error;
  }

// quit command
  $error = sendCommand($connection, "QUIT", $verbose, 1);
  if ($error) {
    fclose($connection);
    return $error;
  }

// end
  fclose($connection);
  return "Message sent";
}

// --------------------------------------------------------------------------

function sendCommand($connection, $command, $verbose, $withRCLF) {
// sends $command to the $connection channel
// verbose mode if $verbose=1
// if $withRCLF=1, add the RCLF sequence to the exchange

// data
  if ($withRCLF)
    $RCLF = "\r\n"; else
    $RCLF="";

// send command if $command is not empty
  if ($command) {
    fputs($connection, "$command$RCLF");

// print message if applicable
    if ($verbose)
      display($command, 1);
  }//if

// read response
  $response = fgets($connection, 1000);

// print if necessary
  if ($verbose)
    display($response, 2);

// retrieve error code
  $errorCode = substr($response, 0, 3);

// last line of the response?
  while (substr($response, 3, 1) == "-") {

    // read response
    $response = fgets($connection, 1000);

    // print if necessary
    if ($verbose)
      print($response, 2);
  }//while
// response completed

// Error returned by the server?
  if ($errorCode >= 500)
    return substr($response, 4);

// return without error
  return "";
}

// --------------------------------------------------------------------------

function display($exchange, $direction) {
// display $exchange on the screen
// if $direction=1, display -->$exchange
// if $direction=2, display <-- $exchange without the last 2 RCLF characters
  switch ($direction) {
    case 1:
      print "--> [$exchange]\n";
      return;
    case 2:
      $L = strlen($exchange);
      print "<-- [" . substr($exchange, 0, $L - 2) . "]\n";
      return;
  }//switch
}

// --------------------------------------------------------------------------

function cutNewLinechar($line) {
// remove the end-of-line character from $line if it exists
  ...
}

The infos.txt file:

1
2
3
4
5
6
7
smtp.orange.fr, serge.tahe@univ-angers.fr, serge.tahe@istia.univ-angers.fr
Subject: test

line1
line2

line3
  • line 1: [smtp.orange.fr] the server used to send the email, [serge.tahe@univ-angers.fr] the sender's address, [serge.tahe@istia.univ-angers.fr] the recipient's address
  • line 2: message headers. Here there is only one, the message subject.
  • line 3: the blank line ends the message headers
  • lines 4–7: the message body

Screen results:

Sending message [smtp.orange.fr,serge.tahe@univ-angers.fr,serge.tahe@univ-angers.fr]
<-- [220 mwinf5d05 ME ESMTP server ready]
--> [EHLO st-PC.home]
<-- [250-mwinf5d05 hello [2.1.22.82], pleased to meet you]
<-- [250-HELP]
<-- [250-AUTH LOGIN PLAIN]
<-- [250-SIZE 44000000]
<-- [250-ENHANCEDSTATUSCODES]
<-- [250-8BITMIME]
<-- [250 OK]
--> [MAIL FROM: <serge.tahe@univ-angers.fr>]
<-- [250 2.1.0 <serge.tahe@univ-angers.fr> sender ok]
--> [RCPT TO: <serge.tahe@univ-angers.fr>]
<-- [250 2.1.5 <serge.tahe@univ-angers.fr> recipient ok]
--> [DATA]
<-- [354 enter mail, end with "." on a line by itself]
--> [From: serge.tahe@univ-angers.fr
To: serge.tahe@univ-angers.fr
Subject: test

line1
line2
line3
.
]
<-- [250 2.0.0 Ag3i1h0051mFoG203g3ip1 mail accepted for delivery]
--> [QUIT]
<-- [221 2.0.0 mwinf5d05 ME closing connection]
Send result: Message sent
  • line 1: script execution tracking message
  • line 2: first response from the SMTP server. This follows the client's connection to port 25 of the SMTP server. Server responses are lines in the form [xxx message] or [xxx-message]. The first syntax indicates that the response is complete. xxx is a status code. A value greater than or equal to 500 indicates an error. The second syntax indicates that the response is not complete and that another line will follow.
  • Line 2: The SMTP server indicates that it is ready to receive commands
  • line 3: the client sends the command [EHLO machineName], where machineName is the hostname of the machine on which the client is running
  • Lines 4–10: Response from the SMTP server
  • line 11: the client sends the command [MAIL FROM: <sender>], which specifies the sender’s email address.
  • Line 12: The SMTP server indicates that it accepts this address. It could have rejected it if the syntax had been incorrect. That said, it does not verify that the email address actually exists.
  • line 13: the client sends the command [RCPT TO: <recipient>], which specifies the email address of the message’s recipient.
  • Line 14: The SMTP server responds that it accepts this address. Again, a syntax check is performed.
  • Line 15: The client sends the [DATA] command, which indicates to the user that the lines that follow are the body of the message.
  • Line 16: The server responds that the message can be sent. The message is a sequence of text lines that must end with a single-character line: a period.
  • Lines 17–25: The message sent by the client
  • Lines 17–19: The message headers [From:, To:, Subject:] indicate the sender, recipient, and subject of the message, respectively.
  • Line 20: An empty line indicating the end of the headers
  • Lines 21–23: the body of the message
  • line 24: the line consisting of a single period that signals the end of the message.
  • Line 26: The SMTP server responds that it accepts the message
  • line 27: the client sends the [QUIT] command to indicate that it is finished
  • Line 28: The SMTP server responds that it will close the connection to the client

Code Comments

We will not go into much detail about the script code since it has been extensively commented.

  • Lines 48–80: The function that processes the [infos.txt] file, which contains the message to be sent along with the necessary information for sending it. It returns an array ($error, $smtpServer, $sender, $recipient, $message) with:
    • $error: a possible error message; empty otherwise.
    • $smtpServer: the name of the SMTP server to connect to
    • $sender: the sender's email address
    • $recipient: the recipient's email address
    • $message: the message to be sent. In addition to the message body, there may be headers.
  • lines 84-157: the sendMail function is responsible for sending the message. Its parameters are as follows:
    • $smtpServer: the name of the SMTP server to connect to
    • $sender: the sender's email address
    • $recipient: the recipient's email address
    • $message: the message to be sent.
    • $verbose: set to 1 indicates that communication with the SMTP server should be logged to the console.

The sendMail function returns an error message; it returns an empty string if there were no errors.

  • Line 88: retrieves the Windows name of a computer running the Windows OS.
  • line 99: we have seen that the client/server dialogue follows this pattern:
    • the client sends a command on a single line
    • server response on one or more lines
  • Lines 161–208: The `sendCommand` function accepts the following parameters:
    • $connection: the TCP/IP channel connecting the client to the server
    • $command: the command to be sent over this channel. The server’s response to this command will be read.
    • $verbose: set to 1 indicates that exchanges with the SMTP server should be displayed on the console.
    • $withRCLF: set to 1 indicates that the end-of-line marker "\r\n" must be added to the end of the command
  • line 173: the client sends the command
  • line 181: reading the first line of the SMTP server’s response in the form xxx text or xxx-text. The latter case indicates that the server has another line to send. xxx is the error code sent by the server.
  • line 188 – retrieving the error code from the response
  • lines 191–199: reading the other lines of the response
  • lines 203–204: if the error code is >=500, then the SMTP server is reporting an error.

9.4. A second program for sending email (inet_04)

This script has the same functionality as the previous one: sending an email. We use modules from the PEAR library for this. This library contains dozens of modules covering various fields. We will use the following:

  • Net/SMTP: a module for communicating with an SMTP server
  • Mail: a module for managing email sending using various protocols.
  • Mail/Mime: a module for creating a message that can include attached documents.

To use these modules, you must first install them on the machine running the PHP script. Installing the WampServer software package installed a PHP interpreter. Within its directory structure, you can install PEAR modules.

  • in [1], the PHP interpreter installation directory
  • in [2], the PEAR folder that will contain the PEAR modules to be installed
  • [3] is the [go-pear.bat] batch file that initializes the PEAR library

To initialize the PEAR library, open a DOS window and run the [go-pear.bat] file. This script will connect to the PEAR library website. An internet connection is therefore required.

C:\DBservers\wamp21\bin\PHP\php5.3.5>go-pear.bat

Once connected to the PEAR library website, the script will download a number of items. Among these is a new script [pear.bat]. We will use this script to install the various PEAR modules we need. This script is called with arguments. Among these, the [help] argument provides a list of commands accepted by the script:

C:\DBServers\wamp21\bin\PHP\php5.3.5>pear help
Commands:
build                  Build an Extension From C Source
bundle                 Unpacks a Pecl Package
channel-add            Add a Channel
channel-alias          Specify an alias for a channel name
channel-delete         Remove a Channel From the List
channel-discover       Initialize a Channel from its server
channel-info           Retrieve information about a channel
channel-login          Connects to and authenticates with the remote channel server
channel-logout         Logs out from the remote channel server
channel-update         Update an existing channel
clear-cache            Clear Web Services Cache
config-create          Create a default configuration file
config-get             Show a single setting
config-help            Show Information About a Setting
config-set             Change a setting
config-show            Show All Settings
convert                Convert a package.xml 1.0 file to the package.xml 2.0 format
cvsdiff                Run a "cvs diff" for all files in a package
cvstag                 Set CVS Release Tag
download               Download Package
download-all           Downloads each available package from the default channel

info                   Display information about a package
install                Install Package
list                   List installed packages in the default channel
list-all               List all packages
list-channels          List available channels
list-files             List files in installed package
list-upgrades          List available upgrades
login                  Connects and authenticates to remote server [Deprecated in
favor of channel-login]
logout                 Logs out from the remote server [Deprecated in favor of c
hannel-logout]
makerpm                Builds an RPM spec file from a PEAR package
package                Build Package
package-dependencies   Show package dependencies
package-validate       Validate Package Consistency
pickle                 Build PECL Package
remote-info            Information About Remote Packages
remote-list            List Remote Packages
run-scripts            Run post-install scripts bundled with a package
run-tests              Run Regression Tests
search                 Search remote package database
shell-test             Shell Script Test
sign                   Sign a package distribution file
svntag                 Set SVN Release Tag
uninstall              Uninstall Package
update-channels        Update the Channel List
upgrade                Upgrade Package
upgrade-all            Upgrade All Packages [Deprecated in favor of calling upgr
with no parameters]
Usage: pear [options] command [command-options] <parameters>
Type "pear help options" to list all options.
Type "pear help shortcuts" to list all command shortcuts.
Type "pear help <command>" to get help for the specified command.

The [install] command is used to install PEAR modules. You can get help on the [install] command:

C:\DBServers\wamp21\bin\PHP\php5.3.5>pear help install
pear install [options] [channel/]<package> ...
Installs one or more PEAR packages.  You can specify a package to install in four ways:

"Package-1.0.tgz": installs from a local file

"http://example.com/Package-1.0.tgz": installs from anywhere on the net.

"package.xml": installs the package described in package.xml. Useful for testing, or for wrapping a PEAR package in another package manager such as RPM.

"Package[-version/state][.tar]": queries your default channel's server (pear.php.net) and downloads the newest package with the preferred quality/state (stable).

To retrieve Package version 1.1, use "Package-1.1"; to retrieve Package state beta, use "Package-beta."  To retrieve an uncompressed file, append .tar (make sure there is no file with the same name first)

To download a package from another channel, prefix the package name with the channel name, like "channel/Package"

You can specify more than one package at a time. It is okay to mix these four ways of specifying packages.

Options:
  -f, --force
        will overwrite newer installed packages
  -l, --loose
        do not check for recommended dependency versions
  -n, --nodeps
        ignore dependencies, install anyway
  -r, --register-only
        do not install files, only register the package as installed
  -s, --soft
        soft install, fail silently, or upgrade if already installed
  -B, --nobuild
        do not build C extensions
  -Z, --nocompress
        request uncompressed files when downloading
  -R DIR, --installroot=DIR
        root directory used when installing files (similar to PHP's INSTALL_ROOT), use packagingroot for RPM
  -P DIR, --packagingroot=DIR
        root directory used when packaging files, like RPM packaging
  --ignore-errors
        force installation even if errors occurred
  -a, --alldeps
        install all required and optional dependencies
  -o, --onlyreqdeps
        install all required dependencies
  -O, --offline
        do not attempt to download any URLs or contact channels
  -p, --pretend
        Only list the packages that would be downloaded

The PEAR modules to install are: [Mail], [Mail_Mime], [Net_SMTP]. In the Command Prompt window, enter the following commands one after another:

<PHP_installDir>pear install Mail
...
<PHP_installDir>pear install Mail_Mime
<PHP_installDir>pear install Net_SMTP

where <PHP_installDir> is the installation directory of the PHP interpreter (C:\serveursSGBD\wamp21\bin\PHP\php5.3.5 in this example)

You can view the installed modules:

C:\DBServers\wamp21\bin\PHP\php5.3.5>pear list
INSTALLED PACKAGES, CHANNEL PEAR.php.NET:
=========================================
PACKAGE          VERSION STATE
Archive_Tar      1.3.7   stable
Console_Getopt   1.3.1   stable
Mail             1.2.0   stable
Mail_Mime        1.8.1   stable
Net_SMTP         1.6.0   stable
Net_Socket       1.0.10  stable
PEAR             1.9.4   stable
PHPUnit          1.3.2   stable
Structures_Graph 1.0.4   stable
XML_Util         1.2.1   stable

The modules are installed in the <PHP_installDir>/PEAR folder:

With the PEAR modules installed, the PHP script for sending email looks like this:


<?php

// error handling
ini_set("display_errors", "off");
// modules
ini_set("include_path", ".;C:\serveursSGBD\wamp21\bin\PHP\php5.3.5\PEAR");
require_once "Mail.php";
require_once "Mail/Mime.php";
require_once "Net/SMTP.php";


// SMTP (Simple Mail Transfer Protocol) client for sending messages
// the information is taken from a file named $INFOS containing the following lines
// line 1: smtp, sender, recipient, attachment
// subsequent lines: the message text
// sender: sender's email
// recipient: recipient's email
// smtp: name of the SMTP server to use
// attachment: name of the document to attach
// 
// data
$INFOS = "mail2.txt"; // email sending parameters
// retrieve the email parameters
list($error, $smtpServer, $sender, $recipient, $message, $subject, $attachment) = getInfos($INFOS);
// error?
if ($error) {
  print "$error\n";
  exit;
}
print "Sending message [$smtpServer,$sender,$recipient,$subject, $attachment]\n";
// send email in verbose mode
$result = sendmail($smtpServer, $sender, $recipient, $message, $subject, $attachment);
print "Result of sending: $result\n";
// end
exit;

//-----------------------------------------------------------------------
function getInfo($file) {
// returns the information ($smtp, $sender, $recipient, $message, $subject, $attachment) from the text file $file
// line 1: smtp, sender, recipient, subject, attachment
// subsequent lines: the message text
...
// return
  return array("", $smtpServer, $sender, $recipient, $message, $subject, $attachment);
}

//getInfo
//-----------------------------------------------------------------------

function sendmail($smtpServer, $sender, $recipient, $message, $subject, $attachment) {
// sends $message to the $smtpServer SMTP server on behalf of $sender
// to $recipient. The file $attachment is attached to the message
// the message has the subject $subject
// 
  // message
  $msg = new Mail_Mime();
  $msg->setTXTBody($message);
  $msg->addAttachment($attachment);
  $headers = $msg->headers(array("From" => $sender, "To" => $recipient, "Subject" => $subject));
  // send
  $mailer = &Mail::factory("smtp", array("host" => $smtpServer, "port" => 25));
  $send = $mailer->send($sender, $headers, $msg->get());
  if ($send === TRUE) {
    return "Message sent";
  } else {
    return $send;
  }
}

// --------------------------------------------------------------------------

function cutNewLinechar($line) {
// Remove the end-of-line character from $line if it exists
  
}

The [mail2.txt] file:

1
2
3
4
smtp.orange.fr, serge.tahe@univ-angers.fr , serge.tahe@univ-angers.fr, test, document.pdf
line1
line2
line3
  • line 1: in order, the SMTP server, the sender's address, the recipient's address, the message subject, the document to attach.
  • lines 2-4: the message text

Screen results

Sending the message [smtp.orange.fr,serge.tahe@univ-angers.fr,serge.tahe@univ-angers.fr,test, document.pdf]
Send result: Message sent

Comments

This script differs from the previous one only in its use of the sendmail function. We describe this function below:

  • Line 6: The PHP scripts for the PEAR modules have been installed in a directory that the PHP interpreter does not search by default. To ensure that the interpreter can find the PEAR modules, we manually specify the directories it should search. It is possible to modify certain configuration parameters of the PHP interpreter at runtime. This modification is visible only to the script that makes it and only for the duration of its execution. The default configuration of the PHP interpreter can be found in the file <PHP_installdir>/PHP.ini. This file contains lines of the form
key=value

The value of the key can be modified at runtime using the function ini_set(key, new_value). The key used to specify the search path for PHP functions and classes referenced by the script is 'include_path'. Here, we add both the script directory (.) and the PEAR directory within the PHP interpreter installation directory to the search path.

  • Lines 7–9: The PHP scripts for sending email are loaded.
  • line 50: the sendmail function, which handles sending the email. Its parameters are as follows:
    • $smtpServer: the name of the SMTP server to connect to
    • $sender: the sender’s email address
    • $recipient: the recipient's email address
    • $message: the message to be sent.
    • $subject: the subject of the message
    • $attachment: the name of the document to attach to the message

The sendMail function returns an error message; it is empty if no error occurred.

  • Line 56: creation of a Mail_Mime message. This message consists of headers (From, To, Subject) and a body (the message itself)
  • Line 57: The body of the Mail_Mime message is set.
  • line 58: attaching a document to the message
  • line 59: Set the headers (From, To, Subject) of the Mail_Mime message
  • line 61: creates the class responsible for sending the Mail_Mime message. The first parameter of the method is the name of the protocol to use, in this case the SMTP protocol. The second parameter is an array specifying the name and port of the SMTP service to use
  • line 62: sending the message. The send method takes three parameters: the sender’s address, the Mail_Mime message headers, and the Mail_Mime message body. The send function returns the boolean TRUE if the message was sent successfully, or an error message otherwise.