The FTP functions give client access to file servers through the File Transfer Protocol (FTP).
The FTP functions are used to open, login and close connections, as well as upload, download, rename, delete, and get information on files from file servers. Not all of the FTP functions will work with every server or return the same results. The FTP functions became available with PHP 3.
These functions are meant for detailed access to an FTP server. If you only wish to read from or write to a file on an FTP server, consider using the ftp://wrapper with the File system functions.
Installation
The windows version of PHP has built-in support for the FTP extension. So, the FTP functions will work automatically.
However, if you are running the Linux version of PHP, you will have to compile PHP with –enable-ftp (PHP 4+) or –with-ftp (PHP 3) to get the FTP functions to work.
PHP FTP Functions
PHP: indicates the earliest version of PHP that supports the function.
| Function | Description | PHP version |
|---|---|---|
| ftp_alloc() | Allocates space for a file to be uploaded to the FTP server |
5 |
| >ftp_cdup() | Changes the current directory to the parent directory on the FTP server |
3 |
| ftp_chdir() | Changes the current directory on the FTP server | 3 |
| ftp_chmod() | Sets permissions on a file via FTP | 5 |
| ftp_close() | Closes an FTP connection | 4 |
| ftp_connect() | Opens an FTP connection | 3 |
| ftp_delete() | Deletes a file on the FTP server | 3 |
| ftp_exec() | Executes a program/command on the FTP server | 4 |
| ftp_fget() | Downloads a file from the FTP server and saves it to an open file |
3 |
| ftp_fput() | Uploads from an open file and saves it to a file on the FTP server |
3 |
| ftp_get_option() | Returns runtime behaviors of the FTP connection | 4 |
| ftp_get() | Downloads a file from the FTP server | 3 |
| ftp_login() | Logs on to an FTP connection | 3 |
| ftp_mdtm() | Returns the last modified time of a specified file | 3 |
| ftp_mkdir() | Creates a new directory on the FTP server | 3 |
| ftp_nb_continue() | Continues retrieving/sending a file (non-blocking) | 4 |
| ftp_nb_fget() | Downloads a file from the FTP server and saves it to an open file (non-blocking) |
4 |
| ftp_nb_fput() | Uploads from an open file and saves it to a file on the FTP server (non-blocking) |
4 |
| ftp_nb_get() | Downloads a file from the FTP server (non-blocking) | 4 |
| ftp_nb_put() | Uploads a file to the FTP server (non-blocking) | 4 |
| ftp_nlist() | Lists the files in a specified directory on the FTP server |
3 |
| ftp_pasv() | Turns passive mode on or off | 3 |
| ftp_put() | Uploads a file to the FTP server | 3 |
| ftp_pwd() | Returns the current directory name | 3 |
| ftp_quit() | Alias of ftp_close() | 3 |
| ftp_raw() | Sends a raw command to the FTP server | 5 |
| ftp_rawlist() | Returns a detailed list of files in the specified directory |
3 |
| ftp_rename() | Renames a file or directory on the FTP server | 3 |
| ftp_rmdir() | Removes a directory on the FTP server | 3 |
| ftp_set_option() | Sets runtime options for the FTP connection | 4 |
| ftp_site() | Sends a SITE command to the server | 3 |
| ftp_size() | Returns the size of the specified file | 3 |
| ftp_ssl_connect() | Opens a secure SSL-FTP connection | 4 |
| ftp_systype() | Returns the system type identifier of the FTP server | 3 |
PHP: indicates the earliest version of PHP that supports the constant.
| Constant | Description | PHP |
|---|---|---|
| FTP_ASCII | 3 | |
| FTP_TEXT | 3 | |
| FTP_BINARY | 3 | |
| FTP_IMAGE | 3 | |
| FTP_TIMEOUT_SEC | 3 | |
| FTP_AUTOSEEK | 4 | |
| FTP_AUTORESUME | Determine resume position and start position for get and put requests automatically |
4 |
| FTP_FAILED | Asynchronous transfer has failed | 4 |
| FTP_FINISHED | Asynchronous transfer has finished | 4 |
| FTP_MOREDATA | Asynchronous transfer is still active | 4 |
Server Side Includes
You can insert the content of a file into a PHP file before the server carry out it, with the include() or require() function. The two functions are identical in every way, except how they handle errors.
The include() function generates a warning (but the script will continue execution)
The require() function generates a fatal error (and the script execution will stop after the error).
This can save the developer a substantial amount of time. This means that you can develop a standard header or menu file that you want all your web pages to include. When the header needs to be updated, you can only update this one include file, or when you add a new page to your site, you can simply change the menu file
The include() Function
The include() function get all the text in a particular file and copies it into the file that uses the include function.
Example
suppose that you have a standard header file, called “welcome.php”. To include the header file in a page, use the include() function, like this:
<html>
<body>
<?php include(“welcome.php”); ?>
<h1>Welcome</h1>
<p>any text</p>
</body>
</html>
Example
Now, let’s suppose we have a standard menu file that should be used on all pages (include files usually have a “.php” extension). Look at the “any.php” file below:
<html>
<body>
<a href=”http://www.any.com/xxx.php”>hi</a> |
<a href=”http://www.any.com/zzz.php”>your Us</a> |
<a href=”http://www.any.com/yyy.php”>name Us</a>
The three files, “xxx.php”, “zzz.php”, and “yyy.php” should all include the “any.php” file. Here is the code in “xxx.php”:
<?php include(“any.php”); ?>
<h1>Welcome</h1>
<p>any text</p>
</body>
</html>
If you look at the source code of the “xxx.php” in a browser, it will look something like this:
<html>
<body>
<a href=”xxx.php”>hi</a> |
<a href=”zzz.php”>your Us</a> |
<a href=”yyy.php”>name</a>
<h1>Welcome</h1>
<p>any text</p>
</body>
</html>
And, of course, we would have to do the same thing for “zzz.php” and “yyy.php”. By using include files, you simply have to update the text in the “any.php” file if you decide to rename or change the order of the links or add another web page to the site.
The require() Function
The require() function is indistinguishable to include(), except for that it handles errors differently.
The include() function produce a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error).
If you include a file with the include() function and an error occurs, you might get an error message like the one below.
PHP code
<html>
<body>
<?php
include(“phpguru.php.php”);
echo “Welcome!”;
?>
</body>
</html>
Error message:
Warning: include(phpguru.php) [function.include]:
failed to open stream:
No such file or directory in on line 5
Warning: include() [function.include]:
Failed opening ‘phpguru.php’ for inclusion
(include_path=’.;C:\php\ar’)
on line 5
Welcome!
Now, let’s run the same example with the require() function.
PHP code:
<html>
<body>
<?php
require(“phpguru.php “);
echo “Welcome!”;
?>
</body>
</html>
It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.
There is another popular method to create and manage arrays, and it uses square brackets [ ] to mean “add to array”, earning it the name “the array operator”. Using this functionality, you can both create arrays and add to existing arrays, so this is generally more popular – you will generally only find the array() function being used when several values are being put within the array, as it will fit on one line. Here are some examples of the array operator in action:
<?php
$array[] = “Zoo”;
$array[] = “War”;
$array[] = “Taz”;
var_dump($array);
?>
That should work in precisely the same as using the array() function, except it is much more elastic – we can add to the array whenever we want to. When it comes to working with non-default indices, we can just place our key inside the square brackets, like this:
<?php
$array["a"] = “Zoo”;
$array["b"] = “War”;
$array["c"] = “Taz”;
var_dump($array);
?>
array array ( [mixed ...])
int count ( mixed var [, int mode])
bool print_r ( mixed expression [, bool return])
void var_dump ( mixed expression [, mixed expression [, mixed ...]])
mixed var_export ( mixed expression [, bool return])
PHP has fitted support for arrays of data, and there are two ways you can create an array: using the array function, or using a special operator, [ ].
Before we look at how arrays work, there are two key things you require to understand before you continue:
1 An array is a normal PHP variable like any others, but it works like a container – you can put other variables inside it
2 Each variable inside an array is called an element. Each element has a key and a value, which can be any other variable.
Now, see this PHP code:
<?php
$myarray = array(“Dean”, “Akki”, “Pars”);
$size = count($myarray);
print_r($myarray);
?>
On line one we see the most basic way to create an array, the array() function. The array() function takes a minimum of one parameter (and a maximum of as many as you want), and returns an array containing those variables. That is right – $myarray now contains all three variables. Line two contains a new function, count(), that returns the number of elements consisting in the array passed to it as its only parameter – in the example we pass in my $myarray, then store the number of elements (three) in $size.
Author’s Note: The array() function actually allows you to have a trailing comma after the last element, eg: array(“Apples”, “Oranges”, “Pears”,). This is rarely used in hand-written code, but it can make generating code much easier.
Line three contains another new function, print_r(). This takes just one parameter, but it outputs detailed information about a variable, such as its type, length, and contents. In the case of arrays, print_r() iteratively outputs all elements inside the array – it is a good way to see how arrays work.
Here is the output of print_r() from the above code:
Array (
[0] => Dean
[1] => Akki
[2] => Pars
)
As you can see, there are our three variables – Apples is at index 0 in the array (signified by “[0]=>”), Oranges is at index 1 in the array, and Pears is at index 2 in the array. Note that if you are running your scripts through a web browser as opposed to from the command-line, you may find it help to put a HTML <pre> tag before your print_r() calls, as this will format them for easier reading.
Using the proper array terminology defined earlier, the 0, 1, and 2 indices are the keys of each element, the “Apples”, “Oranges”, and “Pears” are the values of each element, and the key and the value considered together are the elements themselves.
Note that you can provide a second parameter to print_r(), which, if set to true, will make print_r() pass its output back as its return value, and not print anything out. To achieve the same output using this method, we would need to alter the script to this:
<?php
$myarray = array(“Dean”, “Akki”, “Pars”);
$size = count($myarray);
$output = print_r($myarray, true);
print $output;
?>
You can store whatever you like as values in an array, and you can mix values also. For example: array(“Foo”, 1, 9.995, “bar”, $somevar). You can also put arrays inside arrays, but we will be getting on to that later.
There is a similar function to print_r(), which is var_dump(). It does largely the same thing, but a) prints out sizes of variables, b) does not print out non-public data in objects, and c) does not have the option to pass a second parameter to return its output. For example, altering the first script to use var_dump() rather than print_r() would give the following output:
array(3) {
[0]=>
string(6) “Dean”
[1]=>
string(7) “Akki”
[2]=>
string(5) “Pars”
}
In there you can observe var_dump() has told us that the array has three values, and also prints out the lengths of each of the strings. For teaching purposes, var_dump() is better as it shows the variable sizes, however you will probably want to use print_r() in your own work.
Finally, there is the function var_export(), which is similar to both var_dump() and print_r(). The key difference with var_export(), however, is that it prints out variable information in a style that can be used as PHP code. For example, if we had use var_export() instead of print_r() in the test script, it would have output the following:
array (
0 => ‘Dean’,
1 => ‘Akki’,
2 => ‘Pars’,
)
Note there is an extra comma after the last element, however this is ignored by PHP and you can copy and paste that information directly into your own scripts, like this:
<?php
$foo = array (
0 => ‘ Dean ‘,
1 => ‘ Akki ‘,
2 => ‘Pars’,
);
?>
* When grabbing data from an array, you can simply add the identifier from the array in a square brackets outside the name of the array.
$myarray = array(“Boos”,”Dars”,”Aazzes”);
print $myarray[0];
print “<br>”;
print $myarray[2];
This will return the text “Boos Aazzes”.
This will also work if you specify a key (covered a bit later).
Here’s how to send an email using PHP scripts (via PHP Mailer class).
PLAIN TEXT
CODE:
require (“phpmailer/class1.phpmailer.php”);
//****
//PLEASE CHANGE THE SETTINGS HERE !!!!
//change settings here
$your_email = “info@example.com”;
$your_smtp = “mail.example.com”;
$your_smtp_user = “info@example.com”;
$your_smtp_pass = “example_password”;
$your_website = “http://example.com”;
//****
//get contact form details
$name = $_POST['name'];
$email = $_POST['email'];
$url = $_POST['url'];
$comments = $_POST['comments'];
$response=”Name: $name\nContents:\n$comments\n”;
$mail = new PHPmailer();
$mail = $mail->SetLanguage(“en”, “phpmailer/language”);
$mail->From = $your_email;
$mail->FromName = $your_website;
$mail->Host = $your_smtp;
$mail->Mailer = “smtp”;
$mail->Password = $your_smtp_pass;
$mail->Username = $your_smtp_user;
$mail->Subject = “$your_website feedback”;
$mail->SMTPAuth = “true”;
$mail->Body = $response;
$mail->AddAddress($your_email,”$your_website admin”);
$mail->AddReplyTo($email,$name);
$mail->AddAttachment(“picture.png”,”picture”);
echo “<p>Thanks for your feedback, <em>$name</em>! We will contact you soon!</p>”;
if (!$mail->Send()) {
echo “<p>There was an error in sending mail, please try again at a later time</p>”;
}
$mail->ClearAddresses();
$mail->ClearAttachments();
the key function of this script is $mail->AddAttachment(“picture.png”,”picture.png”);, where you can add any file as email attachments from your script.
Hopefully this example will help you to create a useful and flexible mail sending php scripts