Various PHP Programming Tricks-For Beginers

Posted: April 28, 2010 in Uncategorized

Various PHP Programming Tricks

I’ll be presenting a couple of nice PHP Programming Tricks in this page. You can take a look at the various tricks in these sub pages.

Force a secure HTTP connection
if (!($HTTPS == “on”)) {
header (“Location: https://$SERVER_NAME$php_SELF”);

Get the date
$today = getdate();
$month = $today[‘month’];
$mday = $today[‘mday’];
$year = $today[‘year’];

Random Loading
You can load random stuff by using this code. For this example, I load random color code:
$selectnumber = rand (1, 5);
if($selectnumber==1) $pagebg=”#990000″;
if($selectnumber==2) $pagebg=”#0000FF”;
if($selectnumber==3) $pagebg=”#00AAAA”;
if($selectnumber==4) $pagebg=”#000099″;
if($selectnumber==5) $pagebg=”#DDDD00″;

Easy Way to List Directory Structure
$path = “/home/user/public/foldername/”;
$dir_handle = @opendir($path) or die(“Unable to open $path”);

while ($file = readdir($dir_handle)) {
if($file == “.” || $file == “..” || $file == “index.php” )
echo “<a href=\”$file\”>$file</a><br />”;

Easy Way to Optimize Database Table
$alltables = mysql_query(“SHOW TABLES”);

while ($table = mysql_fetch_assoc($alltables))
foreach ($table as $db => $tablename)
mysql_query(“OPTIMIZE TABLE ‘”.$tablename.”‘”)
or die(mysql_error());

Create a password protect webpage
$username = “someuser”;
$password = “somepassword”;

if ($_POST[‘txtUsername’] != $username || $_POST[‘txtPassword’] != $password) {?>
<form name=”form” method=”post” action=”<?php echo $_SERVER[‘PHP_SELF’]; ?>”>
<p><label for=”txtUsername”>Username:</label>
<br><input type=”text” title=”Enter your Username” name=”txtUsername”></p>

<p><label for=”txtpassword”>Password:</label>
<br><input type=”password” title=”Enter your password” name=”txtPassword”></p>
<p><input type=”submit” name=”Submit” value=”Login”></p>
<?} else {?>
<p>This is the protected page. Your private content goes here.</p>


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.