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");
exit;
}
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" )
continue;
echo "<a href=\"$file\">$file</a><br />";
}
closedir($dir_handle);
Easy Way to Optimize Database Table
dbConnect()
$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) {?>
<h1>Login</h1>
<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>
</form>
<?} else {?>
<p>This is the protected page. Your private content goes here.</p>
<?}?>
If you liked my post then,
Click here to Subscribe to FREE email updates from "itrickz", so that you do not miss out anything that can be valuable to you and your blog!!
0 comments: on "PHP Programming Tricks for beginners"
Post a Comment