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'];

OR

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

OR better

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

OR even better create a function:

<?php
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"; }

OR

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

OR

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

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

<?php
$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();
if($_SESSION['AName']=="")
{
header("location: Admin.php?action=Apl");
exit();
}
?>

Request ID

$id1=$_REQUEST["txtid"];

Logout

<?php session_start();
unset($_SESSION['AName']);
unset($_SESSION['APass']);
// session_destroy();
// $_SESSION=array();
header("location: index.php?action=Aloggedout");
?>

Redirect

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

Referrer

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

Exit

exit( );

Select

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

Optimized Query

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

Loop

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

Delete Record

$id1=$_REQUEST["txtid"];
$sql="select * from gb where gbid='$id1';";
$check=mysql_query($sql);
$no=mysql_num_rows($check);
if($no==1)
{
$sqlup="DELETE from gb where gbid='$id1';";
$string=mysql_query($sqlup);
if($string==true)
{
header("location: CtrlGb.php");
}
}
else
{
header("location: CtrlGb.php");
}

Update Record

$idg=$_REQUEST["getid"];
$sql="select * from ld where ldid='$idg';";
$check=mysql_query($sql);
$no=mysql_num_rows($check);
if($no==1)
{
$sqlup="update ld set website='$wne', link='$wle' where ldid='$idg';";
$string=mysql_query($sqlup);
if($string==true)
{
header("location: Ctrlld.php");
}
}
else
{
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 
code='$CountryCode', 
name=\"$CountryName\",
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')";
if(mysql_query($sql)==true)
{
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"
?>
 
<?php
$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"
?>
 
<?php
$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
?>
 
<?php
// page url complete
function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}
//  echo curPageURL();
    $pgu=curPageURL();
// $pgu contains complete page url, call this var in any page
?>

Hide PHP Warning Messages (Security)

<?php
// hide warning messages
// remove it while development
// add before final upload of project
@ini_set( "display_errors", 0);
@ini_set('display_errors','Off');
@error_reporting(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

unset($_SESSION['uName']);
unset($_SESSION['uUser']);
unset($_SESSION['uPhone']);
unset($_SESSION['uEmail']);
unset($_SESSION['uId']);

Assigning Session Vars

$_SESSION['uName']=$myname;
$_SESSION['uUser']=$myusername;
$_SESSION['uPhone']=$myphone;
$_SESSION['uEmail']=$myemail;
$_SESSION['uId']=$myid;

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; ?>";
-->
</script>
<?php

Single Record

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

Delete Pic

// checking if stored pic is not default pic and then delete
if($picnm!='default.jpg')
{
$myfiledel = 'items/'.$picnm;
@unlink($myfiledel);
}

Before Inserting Record in Db Do this

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

Strip Tags

$itemTitle=strip_tags($_REQUEST["itemTitle"]);

nl2br

$itemDetails=nl2br($_REQUEST["itemDetails"]);

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

$itemDetails=nl2br($_REQUEST["itemDetails"]);

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);
$i=0;
echo "<table>"
while($i < $num)
{
if ($i % 2 == 0){
echo "<tr class='style1'>";
}
else{
echo "<tr class='style2'>";
}
echo "<td>" . mysql_result($qPhysician,$i,"lastName") . "</td>";
echo "<td>" . mysql_result($qPhysician,$i,"firstName") . "</td>";
echo "</tr>";
$i++;
}
echo "</table>";

or

if ($i % 2 == 0)
echo "even";
else
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
</form>

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 https://www.sitename.com/images/image.jpg
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 www.site.com/products/ and www.site.com/pgid/1/

Pages: 1 2