MoonPoint Support Logo




Advanced Search
Search:
Entire Site This Topic Only
Match:
Any All
Partial Whole Words only
September
Sun Mon Tue Wed Thu Fri Sat
     
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    
2010
Months
Sep
Oct Nov Dec


Sun, Nov 05, 2006 10:55 pm

Displaying the Modification Time for a Webpage with PHP

You can display the last time a webpage was modified by including the following PHP code on a webpage:


<?php

$thisfile = pathinfo($_SERVER['PHP_SELF']);

echo "Last modified: ".date("l jS F Y g:ia",
filemtime($thisfile["basename"]));

?>

Note: your webpage must have a .php extension rather than .htm or .html and your webserver must provide PHP support in order for the code to work.

The above code would display the date and time the webpage was modified in the format below:

Last modified: Sunday 5th November 2006 8:57pm

The options to the PHP date function above are encluded in parentheses. Within the parentheses the first argument is the date format to be used, which is followed by a comma and then the time value to be formatted. In this case the time value to be formatted is the file modification time, filemtime of the webpage.

The lowercase "L" will display the day of the week, e.g. "Sunday". The lowercase "j" displays the day of the month without leading zeros, e.g. "5". Putting the "S" immediately after it displays two characters for the English ordinal suffix for the day of the month. In the case above it causes the "th" to be put after the "5". The "F" displays the full month name, e.g. "November" and the "Y" displays the year as 4 digits, e.g. "2006". The "g" displays the hour in 12 hour format without leading zeros, e.g. "8" in the above case. It is followed by a colon and then the "i" displays the minutes with leading zeros, e.g. "07" or in this case "57". The "a" displays a lowercase "am" or "pm" as the case may be.

The characters you can use to control the display of the date are as follows:

a 'am' or 'pm'
A 'AM' or 'PM'
B Swatch Internet time
d day of the month, 2 digits with leading zeros; i.e. '01' to '31'
D day of the week, textual, 3 letters; i.e. 'Fri'
F month, textual, long; i.e. 'January'
g hour, 12-hour format without leading zeros; i.e. '1' to '12'
G hour, 24-hour format without leading zeros; i.e. '0' to '23'
h hour, 12-hour format; i.e. '01' to '12'
H hour, 24-hour format; i.e. '00' to '23'
i minutes; i.e. '00' to '59'
I (capital i) '1' if Daylight Savings Time, '0' otherwise.
j day of the month without leading zeros; i.e. '1' to '31'
l (lowercase 'L') day of the week, textual, long; i.e. 'Friday'
L boolean for whether it is a leap year; i.e. '0' or '1'
m month; i.e. '01' to '12'
M month, textual, 3 letters; i.e. 'Jan'
n month without leading zeros; i.e. '1' to '12'
r RFC 822 formatted date; i.e. 'Thu, 21 Dec 2000 16:01:07 +0200' (added in PHP 4.0.4)
s seconds; i.e. '00' to '59'
S English ordinal suffix, textual, 2 characters; i.e. 'th', 'nd'
t number of days in the given month; i.e. '28' to '31'
T Timezone setting of this machine; i.e. 'MDT'
U seconds since the epoch
w day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday)
Y year, 4 digits; i.e. '1999'
y year, 2 digits; i.e. '99'
z day of the year; i.e. '0' to '365'
Z timezone offset in seconds (i.e. '-43200' to '43200'). The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.

For another example, using the following code woulld display the same date as above as Sunday November 5, 2006 8:57 PM instead.


<?php

$thisfile = pathinfo($_SERVER['PHP_SELF']);

echo "Last modified: ".date("l F j, Y g:i A",
filemtime($thisfile["basename"]));

?>

You can put the code in a PHP file that can be included in every webpage, so that if you decide to change the format of the displayed date, you don't have to modify every web page that you have on your website. For instance, I include a "footer.php" file in webpages using incfile.

References:

  1. php displaying last modification time
    thescripts developer community
    July 17, 2005
  2. PHP:date - Manual
    The PHP Group
    September 28, 2006
  3. PHP Date()
    W3Schools
  4. Date Format php for month day year and time formatting
    Plus2net
  5. Including Files in a Web Page with PHP
    MoonPoint Support
    February 8, 2006

[/languages/php] permanent link

Sat, Apr 29, 2006 1:24 pm

PHP - Exec

The PHP exec function can be used to call external programs. For instance, if I wish to create a webpage that displays the MD5 checksum for a file, I can call the md5sum program that is present on Unix and Linux systems. If I called the program from a shell prompt on the system, I would see something like the following:

# md5sum file.txt
529dc67dde9486a1af8353915ab94870 file.txt

Using PHP, I can get the MD5 checksum with the following code:

<?php

$filename="mboxgrep-0.7.9-1.i386.rpm";
$md5sum = exec('md5sum '.$filename);
$md5sum = substr($md5sum,0,strpos($md5sum,' '));

?>

The results of the call to the external md5sum program are stored in a variable named md5sum. The md5sum program returns the MD5 checksum followed by a space and then the filename. The filename can be stripped away by using strpos to determine the position of the space in the string and then substr can be used to remove all of the charcters from the string starting with the space to the end of the string.

Since I need to calculate the MD5 checksum, aka hash, regularly, I can create a function that calls the external md5sum program to do so.


function md5sum($filename) {

  $hash = exec('md5sum '.$filename);
  // The md5sum command returns the MD5 hash followed by a space and the
  // filename. Remove the space and filename.
  $hash = substr($hash,0,strpos($hash,' '));
  return($hash);

}

But what if you call an external program that returns multi-line output. If you just store the results obtained by using exec to call the program, you will get only the last line of output for the program.

For instance, I can use the command rpm -qp --requires file.rpm to determine what other software is required by a RPM file. If I call that program with PHP's exec function and assign the results to a variable, requires, however, I get just the last line of the results of calling rpm -qp --requires, which produces multiline output.

<?php
$filename="mboxgrep-0.7.9-1.i386.rpm";
$requires = exec('rpm -qp --requires '.$filename);
?>

What I need to do instead, is put the output of the external command into an array. When using the exec function, I can specify an array to be used to hold the output, by putting a comma after the command to be called and then specifying an array to hold the output of the command.

<?php exec(external_command, $output_array); ?>

For instance, to obtain the output from the rpm command above, I could use the following code:


<?php

$filename="mboxgrep-0.7.9-1.i386.rpm";
exec('rpm -qp --requires '.$filename, $requires);

for ($i = 0; $i < count($requires); $i++) {
   print "$requires[$i]<br>\n";
}

?>

The exec function is used to call the program, storing the output from the rpm command in the array $requires. I can then use a for loop to print each of the lines in the array, putting a <br> tag at the end of each line, so that the HTML output is more readable and matches that of the program. I also use /n to create a new line at the end of each line of output so the source HTML code is more readable, also.

References:

  1. PHP: exec - Manual
  2. MD5
  3. Programming PHP: Chapter 5: Arrays

[/languages/php] permanent link

Wed, Feb 08, 2006 12:07 pm

Including Files in a Web Page with PHP

If you want to pull in code from other files into your webpages, you can use the PHP include function.

Suppose you want to include a header and footer file in each webpage you create so that you don't have to type the same HTML code into each webpage to get a standard header and footer for each webpage. You can create a template directory beneath the root directory of your website and put two files there: header.php and footer.php. The files can contain standard HTML code, though of course you just have the snippets of code you need not the <html>, <body>, and other tags you would have in a complete webpage.

For instance, suppose you just want to include a logo for your site at the top of every page. You could create a header.php file with just the following code.

<div id="header" align="center">
<img src="/images/mplogo-white.jpg" alt="MoonPoint Support Logo">
</div>

Let's suppose that you have two directories called examples and template beneath the root directory for your website. You place all template files, such as header.php, footer.php, menu.php, etc. in the template directory. You want to place those in every webpage on your site. In the examples directory you have a webpage titled mywebpage.php. To include the header file in the page you could insert the following line at the appropriate place in mywebpage.php. You would insert similar lines for any other files you wished to include.

<?php include("../template/header.php"); ?>

Now, whenever you want to change the header file, you don't have to edit every webpage on the site and make the needed changes. You just edit header.php.

But one caveat to this approach is that you have to keep in mind the directory structure for the site every time you use the include function. For instance you may have 8 levels of directories beneath the root directory of your website. For a particular dirctory you might need to use <?php include("../../../../../template/header.php"); ?>. Keeping track of the number of dots and slashes you need can be a little cumbersome. And, if you rearrange the directory structure for the site, you may have to edit every webpage in the affected directories to put in the appropriate number of dots and dashes for the new directory structure.

However, you could also insert the following code provided by Paul Whitrow at PHP Include File Path Finder in the webpages instead.

<?php

function incfile($file,$d=""){
while(!is_file($d.$file)){$d.="../";}
include ($d.$file);
}

?>

Then instead of using PHP's include function to insert the header file, you could place the incfile function in your webpages where you want the header to appear, as below. Make sure you have inserted the incfile function code shown above prior to the point where you call it.

<?php incfile("template/header.php"); ?>

You could use either incfile("template/header.php"); or just incfile("header.php");. The incfile function will check the current directory, i.e. the one in which the webpage is located, for a subdirectory named template with header.php within it if you use the first form or will look for header.php within the current directory if you use the second form. If it doesn't find the requested file, then it will put a "../" in front of the directory path and try again. If it still doesn't find header.php, it will prepend another "../" and try again and so on.

So using including the incfile function in your webpages and calling it to look for files you want to include will save you from figuring out how many sets of dots and slashes you need to locate the file you want to include and from having to edit webpages to modify the number of dots and slashes should you alter the directory structure of your website.

One note of warning, though. The file you include must exist. Otherwise your website visitors may see many repetitions of lines like the following when they visit your webpages where you used incfile.

Warning: stat failed for ../../../../../../../../../../../../../../../../../../../.
in /www/mysite/examples/linux/test.php on line 22

References:

  1. PHP Include File Path Finder
    By Paul Whitrow
    September 28, 2005

[/languages/php] permanent link

Sat, Jan 15, 2005 2:17 pm

Using PHP to Upload Files to a Website

You can use PHP to provide the capability for users to upload files to your website. First create an HTML file with a form for uploading a file. Specify the PHP file that will handle the uploads in the "action" part of the form.

For the form portion of the HTML file, I've named the PHP file I will use as "upload.php". You must specify "POST" rather than "GET" for "action". PHP on the server you are using is likely to have a maximum size for POST data of 8 MB. Look for the following lines in your php.ini file, which should be in the /etc directory on a Linux system, and adjust the size to what you consider to be an appropriate number.

; Maximum size of POST data that PHP will accept.
post_max_size = 8M

There is also another limiting factor, the maximum size for a file to be uploaded, which is controlled by upload_max_filesize, in php.ini. The default value is likely to be 2 MB. When you are transmitting a file via POST using a form on a webpage, there may be other data transmitted for other fields on the form as well plus MIME headers as well. So, if you wanted to be able to transmit a file of 8 MB, you would need to set the value of upload_max_filesize to 8M, and make post_max_size slightly larger. But for this example, I'm simply going to set them both to 8M, since the other data I'm transmitting is fairly small.

To adjust the maximum allowed size for file uploads, look for the following lines in php.ini. You can specify the number in bytes or in KiloBytes (KB) or MegaBytes (MB) by putting a "K" or "M" immediately after the number in the latter two cases. Keep in mind a KiloByte is 1,024 bytes and a MegaByte is 1,024 KiloBytes, so to determine the number of bytes equivalent to a certain number of MB use Bytes = MB * 1024 * 1024.

; Maximum allowed size for uploaded files.
upload_max_filesize = 2M

There are also other parameters to consider when using a form that calls a PHP script to upload files to your website. There is also a memory_limit value, which will be a factor if the enable-memory-limit is set. In my case, using Apache 2.0.40 and PHP 4.2.2 on a Fedora Linux system, the only parameters I needed to set in php.ini were upload_max_filesize (you can determine the versions by apachectl -v and php -v. For a complete discussion of the parameters to consider see How to optimize your PHP installation to handle large file uploads.

Once you have adjusted the upload_max_filesize and post_max_size to the desired values, you may need to restart your webserver software. If you are using Apache on a Linux system you will need to do so. Use apachectl restart to restart Apache. You will need to have root access to do so. If you are using Apache, you will also need to put the following lines in Apache's httpd.conf, likely located in /etc/httpd/conf, before restarting Apache.

<Files *.php>
  SetOutputFilter PHP
  SetInputFilter PHP
  LimitRequestBody 8388608
</Files>

The reason you will need to add the lines above to httpd.conf is that Apache has a default limit for LimitRequestBody that restricts the size of all POST data for any scripting language used on a webpage. Some Redhat Package Manager (RPM) installations may set this value at 512 KB.

The HTML code you should use for the form portion of your HTML file is shown below.

<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="upload.php" method="POST">
<!-- Name of input element determines name in $_FILES array -->
Send this file: <input name="userfile" type="file">
<input type="submit" value="Send File">
</form>

See upload.html for a complete HTML file to perform the upload.

For the PHP file, you can use the following code:

<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.

$uploaddir = "../../uploads/";
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
   echo "File is valid, and was successfully uploaded.<br><br>";
   echo "<b>Name:</b> " . $_FILES['userfile']['name'] . "<br>";
   echo "<b>Type:</b> " . $_FILES['userfile']['type'] . "<br>";
   printf ("<b>Size:</b> %.2f KB ", $_FILES['userfile']['size'] / 1024);
   echo "(" . $_FILES['userfile']['size'] . " bytes)<br>";
}
else {
   echo '<pre>';
   echo "Possible file upload attack!\n\n";
   echo "Here is some more debugging info:\n";
   print_r($_FILES);
   print "</pre>";
}
?>

Be sure to put a "/" at the end of the directory name for the upload directory.

When a user uploads a file, it will go into whatever directory is specified as the temp directory in php.ini. If no temp directory is specified in php.ini, the files will go into the default temp directory for the system. When the PHP program completes, it will be moved into whatever directory you specified for the upload directory. You should change the permission of the upload directory to 733, e.g. chmod 733 uploads or grant permission for the user account under which your webserver software runs, e.g. Apache, to write to this directory. I would strongly advise you to use a directory outside the document root for your website, e.g. if all of your website HTML files go under a directory named "www" under your home directory, create another directory, e.g. "uploads" at the same level as the www directory, but not underneath the "www" directory. Otherwise, if some malicious user guesses where you are placing the uploaded files, he can store a file with executable code in that directory and then use a URL which includes the name of the file he just uploaded to execute its contents.

For example, let's suppose that you are putting the uploaded files in a directory called "uploads" that lies directly beneath the one where your upload.php file resides. Someone knows or guesses that you are using a directory with that name underneath the one containing the upload.php file. He then creates a file with PHP code within it and uploads it to your webserver. Let's suppose your upload.html file is at http://somewhere.com/files/upload.html and the upload.php file is at http://somewhere.com/files/upload.php. The malicious user puts the code below in showinfo.php and then uploads it. He knows it went into a directory called "uploads" beneath the "files" directory He can then use the URL http://somewhere.com/files/showinfo.php to execute the PHP file he just put on the site.

<?

$files = `ls -la`;
$users = `who`;

echo "<pre>";
echo "Directory \n";
echo $files . "\n";
echo "Users \n";
echo $users . "\n";
echo "</pre>";

?>

The code above is relatively innocous. On a Unix or Linux system, it will only display all files in the directory where it is located and a list of the users logged into the system. But code could just as easily be inserted to replace or delete files, including system files, so it is important to protect yourself against malicious individuals wishing to do damage to your system or compromise it. So put the uploaded files in a location where no one can execute the files.

You may also wish to password protect the directory where the upload.php file is located, so that you can limit who will be able to upload files.

References:

  1. Chapter 38. Handling file uploads
  2. File Uploads (tutorial)
  3. How do I do html form file uploads
  4. How to optimize your PHP installation to handle large file uploads
  5. ini_get (finding post_max_size)

[/languages/php] permanent link

Blosxom logo