All In One

No developer can remember all the code all the time for everything. Open this php index page and start coding in php. This is all in one help for php programming. I will update it from time to time and advanced version of this section will be up soon. Page contains the following php secrets:

PHP database connection, login session check, php request ID, php logout, php and JS redirect, php array, php referer, optimized mySQL query, php loop script, php delete record script, php update record script, php update record script, php insert record script, php get some part of sentence script, php current page, php secure programming, securing php script, php anti-XSS programming, php anti-cross-site-scripting programming, php user logged in check and display records, php self form submit, php assign session variables, php delete image, php get input and remove vulnerability and much more….

Learn to create php mass email, php help desk software, php sql backup, php email marketing software, php bug tracking software, php project management system, php web content management system, draft php membership software, php intranet software, php ecommerce software, php email manager, php helpdesk system, php ticketing system, php survey software, php content management software, php email marketing and even more complex php systems by using the following scripts.

Here is how you can code in PHP even if you are not a programmer. Scroll down and have a glimpse at what this page reveals?…You will be amazed! Next time you code in PHP, open this page, copy past…done.

Following is raw code. You have to guess what’s going on, to use it. If you know basic programming then its a piece of cake for you to use or customize following scripts.

Useful Functions Part 1
Useful Functions Part 2

Security Essentials

Get variables by checking if they are set or not:

If you want to do this:

$act = $_REQUEST["act"];

Do it like this

$act = @$_REQUEST['act'];


if(isset($_POST['act'])) { echo $_POST['act']; }

OR better

$act = (isset($_REQUEST["act"])?$_REQUEST["act"]:"");

OR even better create a function:

function getIfSet(&$value, $default = null)
    return isset($value) ? $value : $default;

Now use this function like this:

$act = getIfSet($_REQUEST["act"]);

If you have to use an if, do it like below:

if(isset($act) == 'doit') { // do something }

If Not Set:

if (!isset($act)) { $act="$someOtherVar"; }


if(empty($variable)){ //do something }


if(!(isset($_POST['text1']) && isset($_POST['text2']))) { // do something }

view all variables without requesting

<?php print_r($_POST); ?>

Get a value by this


forget requesting every variable
Above uses if else and it check if a variable was posted or not

Session Check

Instead of doing like:

if($_SESSION['something']=='' || $_SESSION['otherthing']=='') { // do something }

Do the following

if(!isset($_SESSION['something']) || !isset($_SESSION['otherthing'])) { // do something }

Easiest DB Connection

$con=mysql_connect("localhost","username","password")or die("Unable to connect");
mysql_select_db("dbname",$con)or die("Unable to open database");
// username is root and pass is blank in case of ocalhost

Login session check

<? session_start();
header("location: Admin.php?action=Apl");

Request ID



<?php session_start();
// session_destroy();
// $_SESSION=array();
header("location: index.php?action=Aloggedout");


header("Location: index.php");
// or
header("location: index.php?action=Aloggedout");
// or javascript way redirect
<script language="javascript" type="text/javascript">
document.location = "index.php";
<script language="javascript" type="text/javascript">
document.location = "<? echo "$ref"; ?>";


$ref=getenv('HTTP_REFERER'); // in case globals are off


exit( );


$sql="select * from admin";

Optimized Query

SELECT employee_number,firstname,surname FROM employee WHERE employee_number= '10875';


//display record set rows by loop
for($i=0; $i<$no; $i++)
<? print mysql_result($check,0+$i,"link"); ?>

Delete Record

$sql="select * from gb where gbid='$id1';";
$sqlup="DELETE from gb where gbid='$id1';";
header("location: CtrlGb.php");
header("location: CtrlGb.php");

Update Record

$sql="select * from ld where ldid='$idg';";
$sqlup="update ld set website='$wne', link='$wle' where ldid='$idg';";
header("location: Ctrlld.php");
header("location: Ctrlld.php");

Update Record Advanced

What if values you are updating inserting contains ” or ‘. In this case query won’t be successful. In this case update code like below:

$sqlup="update countries set 
where id='$originalID';";

Note name=\”$CountryName\”, instead of name=’$CountryName’, in above case…

Insert Record

$sql="insert into gb values('','$gbn','$gbe','$gbc','$t','no')";
header("location: GuestBook.php?action=posted");

Get Part of Data – substr

<?php $data="PHP is a great programming platform where we can do anything relating to dynamic web pages and huge websites";
$data1 = substr($data, 0, 35);
$data2 = substr($data, -17);
echo "$data1 ...";
// returns "PHP is a great programming platform ..."
echo "$data2";
// returns "and huge websites"
$result = substr("abcdef", -1); // returns "f"
$result = substr("abcdef", 1); // returns "bcdef"
$result = substr("abcdef", 2, -1); // returns "cde"
$result = substr("abcdef", 0, -3); // returns "abc"
$date = 140708;
$day = substr($date, 0, 2);
$month = substr($date,2, 2);
$year = substr($date, -2);
echo "$day - $month - $year"; //returns "14 - 07 - 08"

Finding Page Name

<?php //detect page name
$jdPage = explode("/", $_SERVER['PHP_SELF']);
$pgname= $jdPage[count($jdPage)-1];
// pgname contains page name eg page.php
// page url complete
function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
 } else {
 return $pageURL;
//  echo curPageURL();
// $pgu contains complete page url, call this var in any page

Hide PHP Warning Messages (Security)

// hide warning messages
// remove it while development
// add before final upload of project
@ini_set( "display_errors", 0);

Define WordPress Memory Limit

<?php define('WP_MEMORY_LIMIT', '128M'); ?>

User Login Check and Display

<?php if($_SESSION['uName']=="") { ?>
user account link | Logout link
<?php } else { ?>
simple nav links | Register | Login
<?php } ?>
// or
<?php if(isset($_SESSION['uName'])) { ?>
user pic or avatar
<?php } else { ?>
default pic or avatar
<?php } ?>

Site URL in Link

<a href="<?php print $siteurl; ?>pagename.php"></a>

Self Page Submit – Submit Form Vars to Same Page

<form action="<?php echo $PHP_SELF;?>" method="post" onsubmit="return CheckData()">

Unset Session Vars one by One


Assigning Session Vars


Simple Text and PHP var Together

$mystr = $siteurl . 'your-items';
if($pgu != $mystr)

Redirect Snippet

?><script language="javascript" type="text/javascript">
document.location = "<?php print $siteurl; ?>";

Single Record

$sql="select * from admin";
if($no > 0 ) { $emm=mysql_result($checkem,0,"email"); }

Delete Pic

// checking if stored pic is not default pic and then delete
$myfiledel = 'items/'.$picnm;

Before Inserting Record in Db Do this

// remove " ' / ( ) characters before insertng into db from title and description
$find5 = array("'","/","(",")",";","\"");
//$replace5 = array(" - "," - "," - "," - "," - "," - ");
$replace5 = array(" ");
$itemTitle1 = str_replace($find5, $replace5, $itemTitle);
$find6 = array("'","/","(",")",";","\"");
$replace6 = array(" ");
$itemDetails1 = str_replace($find6, $replace6, $itemDetails);
// $itemDetails2=strip_tags("$itemDetails1");

Strip Tags




Call data from DB as it is, in Textarea

<textarea name="itemDetails" id="itemDetails" cols="58" rows="20"><?php print strip_tags($dtt); ?></textarea>

Post data from textarea with breaks and basic html to store in db


Easy Alternative Background Color Rows in Table while Displaying Records in a Loop

in loop $i stores the record number that is being populated. Divide this by 2 and see if result is 0, declare it odd and add class odd to tr. If its not 0, declare it even and add class even in tr with different background.

$num = mysql_num_rows($qPhysician);
echo "<table>"
while($i < $num)
if ($i % 2 == 0){
echo "<tr class='style1'>";
echo "<tr class='style2'>";
echo "<td>" . mysql_result($qPhysician,$i,"lastName") . "</td>";
echo "<td>" . mysql_result($qPhysician,$i,"firstName") . "</td>";
echo "</tr>";
echo "</table>";


if ($i % 2 == 0)
echo "even";
echo "odd";

Close MySQL connections

In footer at every page, you can close mysql connection to save resources.

// connection starts
$dbConnectionName=mysql_connect("hostname","user","password")or die("Unable to connect");
mysql_select_db("db-name",$con)or die("Unable to open database");
// connection closes
<?php mysql_close($dbConnectionName); ?>

Requirements in File Upload

1- Define max file size in hidden field in form
2- Use Multipart data in form

<form enctype="multipart/form-data">
<input type="hidden" value="5242880" name="MAX_FILE_SIZE">
file upload field and other fields

Post form at same page without mentioning URL everytime

Post form to:

<?php print $siteURL; ?>

like this;

<form id="frmRecord" name="frmRecord" action="<?php echo $PHP_SELF;?>" method="post" onSubmit="return CheckData()">

Easy Date

<?php print date("j F Y, l"); ?>

Problem with the URLrewriting? Images not showing? :)

Alright, use absolute URLS – instead of images/image.jpg use
And create a blank htaccess file and paste this code: RewriteEngine off in that and copy this htaccess in every folder that contains images. Only root folder contains full htaccess code.

And make sure you edit httpd.conf and do on symlinks

Code for directory listing in htaccess can also create problem.
Option -Indexes
Option Indexes

htaccess for symlinks

RewriteRule products/ products.php
RewriteRule page/pgid/(.*) page.php?pgid=$1
now call and

Pages: 1 2