I am beginning to publish posts containing snippets of code that you can use in your own project or just so that you can store it in your "Useless Snippets Folder" on your Desktop. Nevertheless, I wanted to do something on my blog to liven it up a little. View more code snippets.

For the first one, here is a little script that I found extremely useful, it allows you to retrieve the file size of a file located on a remote server using a HTTP, HTTPS, FTP or FTPS URI, quickly and easily. This is useful because the PHP filesize() function does not always accept HTTP wrappers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
function remotefilesize($url) {
	$sch = parse_url($url, PHP_URL_SCHEME);
	if (($sch != "http") && ($sch != "https") && ($sch != "ftp") && ($sch != "ftps")) { return false; }  // Error: unrecognized URI scheme.
 
	if (($sch == "http") || ($sch == "https")) {
		$headers = array_change_key_case(get_headers($url, 1), CASE_LOWER);
		if (!array_key_exists("content-length", $headers)) { return false; }  // Error: no 'content-length' header.
 
		return $headers["content-length"];  // Return: $headers["content-length"] value.
	}
 
	if (($sch == "ftp") || ($sch == "ftps")) {
		$server = parse_url($url, PHP_URL_HOST);
		$port = parse_url($url, PHP_URL_PORT);
		$path = parse_url($url, PHP_URL_PATH);
		$user = parse_url($url, PHP_URL_USER);
		$pass = parse_url($url, PHP_URL_PASS);
 
		if ((!$server) || (!$path)) { return false; }  // Error: invalid FTP URI.
		if (!$port) { $port = 21; }
		if (!$user) { $user = "anonymous"; }
		if (!$pass) { $pass = "phpos@"; }
 
		switch ($sch) {
			case "ftp":
				$ftpid = ftp_connect($server, $port);
				break;
			case "ftps":
				$ftpid = ftp_ssl_connect($server, $port);
				break;
		}
 
		if (!$ftpid) { return false; }  // Error: could not connect to the FTP server.
 
		$login = ftp_login($ftpid, $user, $pass);
		if (!$login) { return false; }  // Error: could not login to the FTP server.
 
		$ftpsize = ftp_size($ftpid, $path);
		if ($ftpsize == -1) { return false; }  // Error: could not size the FTP file.
 
		ftp_close($ftpid);
 
		return $ftpsize;  // Return: $ftpsize value.
	}
}
?>

This function takes one argument; $url, which is required and should contain the URL of the file to retrieve the size of. The output will be returned as a string in bytes, or if an error was encountered it will return false.

This code can be used accordingly:

1
<?php echo remotefilesize("http://www.google.co.uk/images/logo.gif") . " bytes."; ?>

This example would return: "8706 bytes.". As that is the size, in bytes of the Google logo.