homepage Welcome to WebmasterWorld Guest from 54.205.188.59
register, free tools, login, search, subscribe, help, library, announcements, recent posts, open posts,
Subscribe to WebmasterWorld
Visit PubCon.com
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

This 41 message thread spans 2 pages: < < 41 ( 1 [2]     
Bag-O-Tricks for PHP II
some code snippets that should be helpful for all in creating dynamic sites
andreasfriedrich




msg:1296699
 2:40 pm on Jan 30, 2003 (gmt 0)

This thread continues the collection of PHP tricks in our Php bag of tricks [webmasterworld.com], which among others is referenced in the Perl and PHP CGI Scripting library [webmasterworld.com].


Validating an URI

Validating an URI is a task that appears quite often. You may have a form where users have to enter a valid URL. You might want to check that a referrer [webmasterworld.com] that you will echo on a page is valid to prevent injection of bad code and linking to bad sites.

While PHP provides the [url=http://www.php.net/parse_url]parse_url[/url] function to parse a URL and return its components it still lacks some functionality that will come in handy when validating a URI.

-o0o-

Features that my is_url function provides:

  • Lets you specify which components are required
  • Reports which components are missing
  • Cleans up the parts to comply with RFC2396 and return them as an array
  • Returns true if all required components are present

-o0o-

How to use my is_url function:

For the impatient among you here´s a complete example first. It checks whether the HTTP_REFERER is valid and converts it into an absolute URI before using it on our page.


$cleaned = array();
$error = 0;
if (is_url($_SERVER['HTTP_REFERER'], PATH, $error, $cleaned)) {
if ($error & (SCHEME + AUTHORITY)) {
$_SERVER['HTTP_REFERER'] = make_abs($_SERVER['HTTP_REFERER'],
$_SERVER['SCRIPT_URI']);
} elseif ($cleaned['authority']!= $_SERVER['SERVER_NAME']) {
echo "Referer is from other domain. We do not include it.";
} else {
$_SERVER['HTTP_REFERER'] = make_uri($cleaned);
echo "<br>$_SERVER[HTTP_REFERER]";
}
} else {
echo "errors: $error<br>";
}

-o0o-

Step by step guide through the above example:

Now let´s have a closer look at how it does just that.


$cleaned = array();
$error = 0;
if (is_url($_SERVER['HTTP_REFERER'], PATH, $error, $cleaned)) {

After initializing the $cleaned and $error variables we call the is_url() function. The first parameter is the HTTP_REFERER as contained in the Referer header field in the client request header. The value of this field may be either an absolute or relative URI. Of course it would be possible to pass along just about any code that the user wants.

The second parameter specifies what components need to be present for is_url to be considering the URI to be valid. We only pass the PATH constant since that is all that is required for a relative URI. If we were to check for an absolute URI we would use SCHEME+AUTHORITY+PATH as the second argument.

As the third and fourth argument we pass references to the $error and $cleaned variables. Those will be filled with a value indicating the missing components and the cleaned components of the URI.


if ($error & (SCHEME + AUTHORITY)) {
$_SERVER['HTTP_REFERER'] = make_abs($_SERVER['HTTP_REFERER'],
$_SERVER['SCRIPT_URI']);
}

If there is no SCHEME and no AUTHORITY we know that we have a relative URI which we need to turn into an absolute one. The base URI that we use to resolve it is the requested URI which is contained in $_SERVER['SCRIPT_URI'].


elseif ($cleaned['authority']!= $_SERVER['SERVER_NAME']) {
echo "Referer is from other domain. We do not include it.";
}

Now can be reasonably sure1 that we have an absolute URI. If the authority component is not equal our server name the referrer is from another domain and we will not use it since we do not want to link to some other site.


} else {
$_SERVER['HTTP_REFERER'] = make_uri($cleaned);
echo "<br>$_SERVER[HTTP_REFERER]";
}

When we have an absolutely URI that is from our domain we assemble the cleaned parts to form a URI again.

-o0o-

Code of my is_url function:

Here´s the code for is_url:


define(SCHEME, 1);
define(AUTHORITY, 2);
define(PATH, 4);
define(QUERY, 8);
define(FRAGMENT, 16);
define(AUTHORITY_WF, 32);# AUTORITY_WELLFORMED
function is_url($string, $components, &$error, &$cleaned) {
$error = 0; // first clear error variable
$_error = 0;
#
$ret = ereg("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?",
$string, $regs);
#
// return false if we were not even able to parse uri
if (!$ret) return false;
#
// check the seperate parts
if (empty($regs[2])) $_error += SCHEME;
if (empty($regs[4])) $_error += AUTHORITY;
if (!empty($regs[4]) and strcmp($regs[2], 'http') == 0) {
// do we have an ok hostname?
if (!ereg("((([a-z0-9]+)[a-z0-9_]¦\\-)+\\.)+".// subdomain + domain
"[a-z]{2,4}".// TLD
":?[0-9]{0,5}$",// port
$regs[4])) {
$_error += AUTHORITY_WF;
}
}
if (empty($regs[5])) $_error += PATH;
if (empty($regs[7])) $_error += QUERY;
if (empty($regs[9])) $_error += FRAGMENT;
#
if ($cleaned!= '') {
$cleaned['scheme'] = $regs[2];
$cleaned['authority'] = $regs[4];
$cleaned['path'] =
preg_replace("{[^-/:@&=+$,_.!~*()'a-zA-Z0-9]}", '', $regs[5]);
$cleaned['query'] =
preg_replace("{[^-;/?:@&=+$,_.!~*'()A-Za-z0-9%]}", '',
urlencode_querystring($regs[7]));
$cleaned['fragment'] =
preg_replace("{[^-;/?:@&=+$,_.!~*'()A-Za-z0-9%]}", '',
urlencode($regs[9]));
}
#
foreach (array(SCHEME, AUTHORITY, AUTHORITY_WF, PATH, QUERY, FRAGMENT)
as $comp) {
if ($components & $comp and $_error & $comp) $error += $comp;
}
#
if ($error > 0) {
$error = $_error;
return false;
}
$error = $_error;
return true;
}

-o0o-

Step by step guide through the above code:


define(SCHEME, 1);
define(AUTHORITY, 2);
define(PATH, 4);
define(QUERY, 8);
define(FRAGMENT, 16);
define(AUTHORITY_WF, 32);# AUTORITY_WELLFORMED

We define some constants that we use to specify the required parts and that is_url() uses to encode which parts of the URI are missing.


function is_url($string, $components, &$error, &$cleaned) {

$string is the URI that we want to check. $components is a numeric value specifying which components are required for a valid URI. Use the constants defined above. $error is a variable that is passed by reference. It will contain a numeric value specifying which components were missing. Note that it will report all components that are missing, not just those that were required. Use the constants to decode that value. $cleaned is an array that is passed by reference. It will contain the cleaned parts of the URI, i.e. they will contain only allowed characters. Invalid characters in the query and fragment component are url_encoded.


$ret = ereg("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?",
$string, $regs);
#
// return false if we were not even able to parse uri
if (!$ret) return false;

We split the URI into its components using the regular expression given in RFC2396. We could have used PHP´s parse_uri, but I liked the RE better.

If the RE does not match at all, the given URI is something else and we return immediately with a return value of false.


if (empty($regs[2])) $_error += SCHEME;
if (empty($regs[4])) $_error += AUTHORITY;
if (!empty($regs[4]) and strcmp($regs[2], 'http') == 0) {
// do we have an ok hostname?
if (!ereg("((([a-z0-9]+)[a-z0-9_]¦\\-)+\\.)+".// subdomain + domain
"[a-z]{2,4}".// TLD
":?[0-9]{0,5}$",// port
$regs[4])) {
$_error += AUTHORITY_WF;
}
}
if (empty($regs[5])) $_error += PATH;
if (empty($regs[7])) $_error += QUERY;
if (empty($regs[9])) $_error += FRAGMENT;

Here we check the parts returned by the RE and build the $_error variable.


$cleaned['scheme'] = $regs[2];
$cleaned['authority'] = $regs[4];
$cleaned['path'] =
preg_replace("{[^-/:@&=+$,_.!~*()'a-zA-Z0-9]}", '', $regs[5]);
$cleaned['query'] =
preg_replace("{[^-;/?:@&=+$,_.!~*'()A-Za-z0-9%]}", '',
urlencode_querystring($regs[7]));
$cleaned['fragment'] =
preg_replace("{[^-;/?:@&=+$,_.!~*'()A-Za-z0-9%]}", '',
urlencode($regs[9]));

Checking the components for illegal characters. They are simply deleted from the URI. Note that scheme is not checked. It should be! The authority is not cleaned up as well. You can check whether $error contains AUTHORITY_WF to tell whether there are illegal characters. Better yet add some clean up code as well.


foreach (array(SCHEME, AUTHORITY, AUTHORITY_WF, PATH, QUERY, FRAGMENT)
as $comp) {
if ($components & $comp and $_error & $comp) $error += $comp;
}
#
if ($error > 0) {
$error = $_error;
return false;
}
$error = $_error;
return true;

So far we just checked which components were missing. Now we need to determine whether any required parts are missing. This is done in the foreach loop. When a component is required and it is missing we add that components numeric value to the $error variable. When error is larger than zero we return false. Otherwise we return true. In both cases we assign the $error variable the value of our internal $_error variable which contains all the missing elements.

-o0o-

Have fun giving it a try.

Andreas

-o0o-


Note: The WebmasterWorld posting software deletes spaces preceding the exclamation point "!" character. It also replaces a solid vertical pipe symbol with a broken vertical pipe "¦" symbol. Both of these changes will need to be undone in any code you copy from WebmasterWorld. Make sure to include a space preceding the "!" in mod_rewrite code, and always replace "¦" with a solid vertical pipe.

1 To be absolutely sure one would need to check for cases where there is a AUTHORITY but no SCHEME.

 

andreasfriedrich




msg:1296729
 12:24 am on Mar 25, 2003 (gmt 0)

I just ran your script Birdman and it works quite nicely. I have never used GD with PHP [php.net] before so it was a great encouragement to go ahead and give it a try. The only thing I didn´t like was that Aaron come out slightly out of proportion (and a bit miscolored due to my old PHP [php.net] and gd version which do not support imagecreatetruecolor [php.net]). A
$dest_x = $dest_y * $source_x / $source_y; later everything was back in proportion.

Andreas

andreasfriedrich




msg:1296730
 12:51 am on Mar 25, 2003 (gmt 0)

How to handle permission levels

A nice way of handling permissions is using a bit of bit bashing. Here´s a short intro to bitwise operators [webmasterworld.com].

Define a some user permission levels.


define('USER', 1);
define('MODS', 2 ¦ USER);
define('ADMI', 4 ¦ MODS);

This will result in three user permission levels. Since MODS have the USER bits set as well they are both USERs and MODS. ADMIs have both the USER and MODS bits set.

If your MODS were to have no USER rights you would just not set the USER bits by not adding the ¦ USER.

Now define some user levels. We use these levels to compare the actual user level to and decide which permissions to grant to a user. We need to set the same bits as above.


define('L_USER', 1);
define('L_MODS', 2);
define('L_ADMI', 4);

Now for testing we need a simple way of changing the user level. This is done by using a query string parameter. You may pass the level as either a number or one of the user permission levels from above.


$level = $_GET['level'];
if (!is_numeric($level)) eval("\$level = $level;");

Now we display the appropriate information for each user permission level. If the actual user level has all the bits set that a certain level like L_USER, L_MODS, and L_ADMI has then we display a short notice of the user level.


if ($level & L_USER) { echo 'USER'; }
if ($level & L_MODS) { echo 'MODS'; }
if ($level & L_ADMI) { echo 'ADMI'; }

Here´re some examples:

index.[url=http://www.php.net/]PHP[/url]?level=1 and index.[url=http://www.php.net/]PHP[/url]?level=USER will display USER. index.[url=http://www.php.net/]PHP[/url]?level=3 and index.[url=http://www.php.net/]PHP[/url]?level=MODS will display USERMODS. A user with MODS permissions will see content for both users and mods because he has both the USERs and MODS bits set. index.[url=http://www.php.net/]PHP[/url]?level=7 and index.[url=http://www.php.net/]PHP[/url]?level=ADMI will display USERMODSADMI. A ADMI has all possible permissions since all bits are set.

In the case of a just MODS as explained about above only MODS would be displayed since such a MODS does not have the USER bits set and therefor does not have USER permissions.

HTH Andreas

andreasfriedrich




msg:1296731
 12:13 am on Apr 4, 2003 (gmt 0)

Using heredoc syntax

Since PHP [php.net] does not provide a universal quoting operator like q [perldoc.com] or q [perldoc.com]q in Perl [perl.com] that lets you choose the string delimiter you need to use heredoc quoting syntax when you do not want to have to worry about escaping quotes.

Using heredocs to assign a string to a variable is easy:


$text = <<<END
Stevie ...
Calvin ...
END;

Using heredocs to echo [php.net] a text is easy as well:


echo [php.net] <<<END
Stevie ...
Calvin ...
END;

But how do you use it to quote the second argument in a function call? Being the Perl [perl.com] programmer that I am I tried it the Perl [perl.com] way:


fwrite [php.net]($fp, <<<END_OF_MAIL);
Stevie ...
Calvin ...
END_OF_MAIL

Wrong. Then I remembered that PHP [php.net] wants the semicolon after the closing delimiter or so I thought.


fwrite [php.net]($fp, <<<END_OF_MAIL)
Stevie ...
Calvin ...
END_OF_MAIL;

Wrong. I decided that a close reading of the manual might help:

It is very important to note that the line with the closing identifier contains no other characters, except possibly a semicolon (;).

Heredoc [php.net]

Now that possibly was the thing that got me thinking. Heredoc text behaves just like a double-quoted string and in fact is just like a double-quoted string.

When using double quoted strings one would write the code like this:


fwrite [php.net]($fp, "
Stevie ...
Calvin ...
");

Now I did the same with the heredoc syntax and just substituted the double quote by END_OF_MAIL and made sure that the closing delimiter was on a line by itself.


fwrite [php.net]($fp, <<<END_OF_MAIL
Stevie ...
Calvin ...
END_OF_MAIL
);

Hope this saves somebody a few minutes.

Andreas

DrDoc




msg:1296732
 7:37 pm on Apr 12, 2003 (gmt 0)

21 -> Twenty-first
This is a tweaked and improved version of the "numerstowords" class.


Changes:

• The original class contained a couple of spelling errors ("fourty" and "eightteen")
• It also added "and" way too often. ("two thousand and three hundred and twelve" instead of "two thousand three hundred and twelve")
• The class didn't hyphenate certain numbers. ("twenty one" instead of "twenty-one")
• I've added two options: (1) You can choose whether you want ordinal suffixes added ("one" vs. "first") (2) You can choose whether you want the string capitalized ("two thousand and three" vs. "Two Thousand and Three")



spelloutnumbers.php:

<?php
class spelloutnumbers {

function hundreds($number) {
$lasts = array('one','two','three','four','five','six','seven','eight','nine');
$teens = array('eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen');
$tens = array('ten','twenty-','thirty-','forty-','fifty-','sixty-','seventy-','eighty-','ninety-');
$many = array('', ' thousand ',' million ',' billion ',' trillion ');

$string = "";
$j = strlen($number);
$done = false;
for($i=0; $i<strlen($number); $i++) {
if($j==2) {
if(strlen($number)>2) {
if($number[0]!=0) {$string .= ' hundred ';}
}
if($number[$i]==1) {
if($number[$i+1]==0) {$string .= $tens[$number[$i]-1];}
else {
$string .= $teens[$number[$i+1]-1];
$done = true;
}
}
else {
if(!empty($tens[$number[$i]-1])) {$string .= $tens[$number[$i]-1].' ';}
}
}
elseif($number[$i]!=0 &&!$done) {$string .= $lasts[$number[$i]-1];}
$j--;
}
return $string;
}

function spellout($number,$suffix=0,$caps=1,$uk=0) {
$lasts = array('one','two','three','four','five','six','seven','eight','nine');
$teens = array('eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen');
$tens = array('ten','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety');
$many = array('', ' thousand ',' million ',' billion ',' trillion ');

$foo = strval($number);
$string = "";

if(strlen($foo)%3!=0) {
$string .= $this->hundreds(substr($number,0,strlen($number)%3));
$string .= $many[floor(strlen($number)/3)];
}

for($i=0; $i<floor(strlen($number)/3); $i++) {
$string .= $this->hundreds(substr($number,strlen($number)%3+($i*3),3));
if($number[strlen($number)%3+($i*3)]!=0) {
$string .= $many[floor(strlen($number)/3)-1-$i];
}
}

$match = array('/ +/','/- /','/-$/','/-thousand/','/-million/','/-billion/','/-trillion/');
$replace = array(' ','-','',' thousand',' million',' billion',' trillion');
$string = preg_replace($match,$replace,$string);

if($uk) {
$match = array('/billion/','/trillion/');
$replace = array('milliard','billion');
$string = preg_replace($match,$replace,$string);
}

if($suffix) {
$match = array('/ve$/','/t$/','/y$/','/one$/','/two$/','/three$/','/e$/');
$replace = array('fth','th','ieth','first','second','third','th');
$string = preg_replace($match,$replace,$string);
if(!preg_match("/first$¦second$¦third$¦th$/",$string)) {
$string .= "th";
}
}

if($caps) {
$string = ucwords($string);
$string = preg_replace("/(-[A-Z])/",strtolower("\\1"),$string);
}

$foo = strrpos($string," ");
if($foo!==false) {
$string = substr($string,0,$foo)." and".substr($string,$foo);
}

return $string;
}
}
?>



Syntax:

include("spelloutnumbers.php");
$BLAH = new spelloutnumbers();
$myvar = $BLAH->spellout(number[,suffix[,caps[,uk]]]);

number is the number you want spelled out.
It can be an integer or a string. Range = 1 to 999.999.999.999.999

suffix can be set to 0 or 1.
1 = use ordinal suffix ("first" instead of "one" etc.). Default is 0.

caps can be set to 0 or 1.
1 = capitalize the words ("Two Thousand" instead of "two thousand" etc.). Default is 1.

uk can be set to 0 or 1.
1 = use British standard ("milliard" instead of "billion" etc.). Default is 0.



Examples:

spellout(3) prints Three
spellout(3,1) prints Third
spellout(3,1,0) prints third
spellout(2003) prints Two Thousand and Three
spellout(2003,1) prints Two Thousand and Third
spellout(999999999999999) prints Nine Hundred Ninety-nine Trillion Nine Hundred Ninety-nine Billion Nine Hundred Ninety-nine Million Nine Hundred Ninety-nine Thousand Nine Hundred and Ninety-nine
spellout(999999999999999,0,1,1) prints Nine Hundred Ninety-nine Billion Nine Hundred Ninety-nine Milliard Nine Hundred Ninety-nine Million Nine Hundred Ninety-nine Thousand Nine Hundred and Ninety-nine
spellout(990) prints Nine Hundred and Ninety
spellout(990,1) prints Nine Hundred and Ninetieth
spellout(990,1,0) prints nine hundred and ninetieth

grahamstewart




msg:1296733
 8:47 am on Apr 17, 2003 (gmt 0)

I just wrote this little function for a site I am working on. Quite like it so I thought I'd show it off here.

Basically it is for automatically generating breadcrumbs link (breadcrumbs are links that let you go back in the site hierarchy, like the "Home / Forums Index / The Webmaster World / Perl and PHP CGI Scripting" one at the top of this page.

[pre][1]
$thisUrl = parse_url( $_SERVER['PHP_SELF'] );
$thisPath = $thisUrl['path'];

if ( preg_match('/^(\/directory_x\/¦\/directory_y\/)[^\/]+\//i', $thisPath) ) {

print '<div id="breadcrumb"><small>';
$dirs = array();
$linkUrl = '/';
$firstLink = TRUE;

preg_match_all( '/([^\/]+)\//', $thisPath, $dirs, PREG_PATTERN_ORDER );

foreach( $dirs[1] as $dir ) {

if ( $firstLink )
$firstLink = FALSE;
else
print '&gt ';

$linkUrl .= $dir.'/';
$link = ucwords( str_replace( '_', ' ', $dir ) );
print '<a href="'.$linkUrl.'">'.$link.'</a> ';
}

print "</small></div>\n";
}
[/1][/pre]

How it Works

It goes back through the path of the current file and generates a link to each directory in the path. For the name of the link it takes the directory name, replaces underscores with spaces and capitalises the words.

So for the file:
/stuff/holiday_pics/album_1/index.php

The trail generated will be:
Stuff > Holiday Pics > Album 1

Note

The first if statement restricts which directories that it generates the trail for. In this example it will only operate when in subdirectories of directory_x or directory_y.

If you'd like it to work everywhere then you could remove the outermost if statement.

Feel free to use this script as you see fit.
No licence - no warranty.

Of course, all this is only useful if your directory structure reflects the design of your site - but then why shouldn't it?

Nick_W




msg:1296734
 8:53 am on Apr 17, 2003 (gmt 0)

Nice! - Flagging this, I'll need it in a little while, thanks Graham! ;)

Nick

davez1000




msg:1296735
 7:23 pm on Apr 26, 2003 (gmt 0)

PHP session timeouts

This works. It registers 2 sessions, an userID and the current time the page is loaded. Each time a session page is loaded, it grabs the time from the session, and compares it to the current time. If the difference is more than the timeout allowed, it sets a timeout variable. If a session page is reloaded within the time, it resets the time session with the current time. So, this script can set 4 variables:

$loggedin, $timeoutflag, $notloggedin, and $wrongpassword

So, with a little bit of adjustment, this script can be used as an include in every "member" page (except for the form bit at the bottom of course). At the moment the timeout is only set to 30 seconds so you can test it. I have tried it numerous times with a stopwatch.

The current username is "hello" and the password is "test"
You can easily change this to grab info from SQL databases, and set the userID with a random ID for each person for example. Lots of different options.

Have fun with it. Just cut and paste it below and load it into an empty file and save it as PHP.


<?
session_name("s_ID");
session_start();
header("Cache-control: private"); // IE6 cache fix


// timeout in seconds
$logintime = 30;


$loggedin=0; $timeoutflag=0; $notloggedin=0; $wrongpassword=0;


if ((session_is_registered("cookie_user_id"))&&(session_is_registered("cookie_time"))){


$timenow = time();


if (($timenow - $_SESSION['cookie_time']) > $logintime){
session_unset(); session_destroy();
$timeoutflag = 1;
} else {
$_SESSION['cookie_time'] = time();
session_register("cookie_time");
$loggedin = 1;
}


} else {
if ($loginsubmit){
session_unset();
$login["username"] = trim($login["username"]);
$login["password"] = trim($login["password"]);


// next line u/name and password check
if ($_POST['login']['username'] == "hello" && $_POST['login']['password'] == "test"){
$_SESSION['cookie_user_id'] = 123456789;
$_SESSION['cookie_time'] = time();
session_register("cookie_time");
session_register("cookie_user_id");
$loggedin = 1;
} else {
session_unset(); session_destroy();
$wrongpassword = 1;
}
}else {
session_unset(); session_destroy();
$notloggedin = 1;
}
}
?>


<?
if ($loggedin){
print "you are logged in!<BR><BR><BR>";
}
else if ($timeoutflag){
print "your session timed out, not logged in!<BR><BR><BR>";
}
else if ($notloggedin){
print "you are not logged in!<BR><BR><BR>";
}
else if ($wrongpassword){
print "wrong password!<BR><BR><BR>";
}
?>


<form name="form1" method="post" action="<? print $PHP_SELF;?>">
<input type="text" name="login[username]" value="<? print "$login[username]";?>">
login<br>
<br>
<input type="password" name="login[password]">
password<br>
<input type="hidden" name="loginsubmit" value="1">
<br>
<br>
<input type="submit" name="Submit" value="Submit">
</form>

davez1000




msg:1296736
 7:56 pm on Apr 26, 2003 (gmt 0)

PHP countdown

You can save this script below as a PHP file and run it

the $bday variable contains the date to countdown to.
at the moment it is set to (23, 59, 0, 4, 17, 2003)
(which is 11:59pm, 17 April, 2003)

numbers are:
HOUR (24 hr), MINUTE, SECOND, MONTH, DAY, YEAR

SO, for example, you wanted to countdown to new year
2006, it would be
$bday = mktime(0, 0, 0, 1, 1, 2006);


<?
// change this for your date to countdown to
$bday = mktime(23, 59, 0, 4, 17, 2003);


print "Your countdown date is " . date("j F Y, g.i a", $bday) . ".<BR>";


print "You visited this page at " . date("j F Y, G.i:s", time());


$diff = $bday - time();


$days = ($diff - ($diff % 86400)) / 86400;
$diff = $diff - ($days * 86400);
$hours = ($diff - ($diff % 3600)) / 3600;
$diff = $diff - ($hours * 3600);
$minutes = ($diff - ($diff % 60)) / 60;
$diff = $diff - ($minutes * 60);
$seconds = ($diff - ($diff % 1)) / 1;


print "Only $days days, $hours hours, $minutes minutes and $seconds seconds until your countdown date!";
?>

:)

davez1000




msg:1296737
 8:22 pm on Apr 26, 2003 (gmt 0)

PHP printf for aligning

Here is an example for left and right justification, padding, and decimal position using printf.

Firstly, I set an array of 9 items with prices. The whole thing is set over 43 pixels. The first section (printf("%-20s%23s\n", "Name", "Price")) sets the "Name" title at the very left, with 20 pixels padding after it (%-20s). It is left justified because of the "-" before the number. The "Price" is right justified (no minus symbol) 23 pixels after the padding of the first one (%23s). Total 43 pixels.

The next line (printf("%'-43s\n", "")) prints a line of dashes, 43 pixels across. The "'" is needed for any symbol, letter, or number except a zero "0".

It loops through the array, and prints the keys and values much the same as the name and price titles.

The whole thing is wrapped in <pre></pre> tags so it prints out nicely formatted.

Cut an paste the code below to try it.


<?
$awa = array(
"Steaks" => 359.608,
"Other food" => 4485.33,
"Milk" => 3.60,
"Charity" => .1,
"More drinks" => 2189.66,
"Assorted sweets" => 9714.51,
"Phone calls" => 3212,
"Hacking fines" => 5316.24,
"Misc" => 8412.76
);


print "<pre>";


printf("%-20s%23s\n", "Name", "Price");
printf("%'-43s\n", "");


foreach ($awa as $key => $val){
$total += $val;
printf("%-20s%20.2f\n", $key, $val);
}


printf("%'-43s\n", "");
$total = sprintf("%0.2f", $total);
printf("%-20s%23s\n", "The boys total spend", $total);


print "</pre>";
?>

andreasfriedrich




msg:1296738
 10:28 pm on Apr 26, 2003 (gmt 0)

printf [php.net] does not use pixels but spaces or whatever other padding character you specify for padding the results to the right string size. That is why printf [php.net] will only work when you use fixed width fonts to display the strings. Thus the use of the PRE [w3.org] element which is usually rendered using fixed width fonts.

See the sprintf [php.net] manual page for an explanation of the format string that printf [php.net] expects.

Andreas

davez1000




msg:1296739
 5:36 pm on Apr 28, 2003 (gmt 0)

Yeah sorry, that is what I meant, not pixels. Stupid me, duh! No idea why I wrote that...


thread continues here
Bag-O-Tricks for PHP III [webmasterworld.com]

[edited by: jatar_k at 4:52 pm (utc) on Aug. 8, 2003]

This 41 message thread spans 2 pages: < < 41 ( 1 [2]
Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved