Archive for September 2013

Populate triple drop down list from database using Ajax and PHP


This is my first post on this Blog for populating triple drop down list from the database without refreshing page using Ajax and PHP. In this post, I’ve put three drop down of country , state and city and the drop down’s value changes without refreshing the page. Now let show you how to create it quickly.
First create the following tables of country city and states,
CREATE TABLE `country` (
`id` tinyint(4) NOT NULL auto_increment,
`country` varchar(20) NOT NULL default '',
PRIMARY KEY (`id`)
) TYPE=MyISAM ;

CREATE TABLE `state` (
`id` tinyint(4) NOT NULL auto_increment,
`countryid` tinyint(4) NOT NULL,
`statename` varchar(40) NOT NULL,
PRIMARY KEY (`id`)
) TYPE=MyISAM ;

CREATE TABLE `city` (
`id` tinyint(4) NOT NULL auto_increment,
`city` varchar(50) default NULL,
`stateid` tinyint(4) default NULL,
`countryid` tinyint(4) NOT NULL,
PRIMARY KEY (`id`)
) TYPE=MyISAM ;
Now place the following form in the index.php file
<form method="post" name="form1">
<table border="0" cellpadding="0" cellspacing="0" width="60%"><tbody>
<tr>
<td width="150">Country</td>
<td width="150"><select style="background-color: #ffffa0" name="country" onchange="getState(this.value)"><option>Select Country</option><option value="1">USA</option><option value="2">Canada</option> </select></td>
</tr>
<tr>
<td>State</td>
<td>
<p id="statediv">
<select style="background-color: #ffffa0" name="state"><option>Select Country First</option> </select></td>
</tr>
<tr>
<td>City</td>
<td>
<p id="citydiv">
<select style="background-color: #ffffa0" name="city"><option>Select State First</option> </select></td>
</tr>
</tbody></table>
</form>
As you can see above, in the onChage event of the country drop down getState() function of the javascript is called which change the options values the State drop down, let’s look at the code the getState() function.
function getState(countryId)
{
var strURL="findState.php?country="+countryId;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
// only if "OK"
if (req.status == 200)
{
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
The code of the PHP file findState.php, which populate the options in the drop down of the state which is fetched from Ajax , is given below
<? $country=intval($_GET['country']);
$link = mysql_connect('localhost', 'root', ''); //changet the configuration in required
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_ajax');
$query="SELECT id,statename FROM state WHERE countryid='$country'";
$result=mysql_query($query);

?>
<select name="state" onchange="getCity(<?=$country?>,this.value)">
<option>Select State</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value=<?=$row['id']?>><?=$row['statename']?></option>
<? } ?>
</select>
In the above state dropdown, getCity() function is called in onChage event with countryId and stateId parameter, now let’s look at the code of the getCity() function
function getCity(countryId,stateId)
{
var strURL="findCity.php?country="+countryId+"&state="+stateId;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4) // only if "OK"
{
if (req.status == 200)
{
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
In the above ajax function, findcity.php is called and this PHP file populate the city dropdown according to the supplied parameters country and state from get method. Now let’s look at the code of findcity.php,
<?php $countryId=intval($_GET['country']);
$stateId=intval($_GET['state']);
$link = mysql_connect('localhost', 'root', ''); //changet the configuration in required
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_ajax');
$query="SELECT id,city FROM city WHERE countryid='$countryId' AND stateid='$stateId'";
$result=mysql_query($query);

?>
<select name="city">
<option>Select City</option>
<?php while($row=mysql_fetch_array($result)) { ?>
<option value><?=$row['city']?></option>
<?php } ?>
</select>
And thats all, the triple drop down list of city, country and state using Ajax and PHP will be populated.

For fixing facebox loading content twice in it, after calling ajax/jquery content

We have a facebox popup which will show when click on a link from the top of the page.

We have also facebox popup which is inside a product listing. After replacing the content in the product list using jquery/ajax we have to reinitialize the facebox to work the popup in the list.

for it we use:

$.post(abc.com/fun.php",{sort:sort_field},function (data){   
                           
                $("#tbl_product_list tbody").html(data);
                $('a[rel*=modal]').facebox() ;
            });

Now the when click on the first facebox at the first facebox from the link, we can see the content is twice in it. this is because the facebox initializing twice.

For avoiding this, we can use a different rel in facebox links which is loading by ajax/jquery like

<a href="pop.php"  rel="tests">

now the above function will need to change like


 $.post(abc.com/fun.php",{sort:sort_field},function (data){   
                           
                $("#tbl_product_list tbody").html(data);
                $('a[rel*=tests]').facebox() ;
            });

 

Install Php on Windows

I have been using WampServer for a while, and it's an excellent piece of program, it comes bundled with MySQL, PHP 5, phpMyAdmin and Apache server. I strongly recommend that you use it. If still you want to go lengthy way, go on reading.

How to Install PHP on Windows IIS.

Please remmember PHP will not work on 16 bit platforms such as Windows 3.1. There are many ways you can install php in your windows. You can refer to This site that shows you nicely how to install Php, MySQL and Apache Server. Or you can follow PHP online guide to installation, which covers everything.

First Go to Php Download page and download a Windows Binaries package. You can choose php package with installer for automated installation or Zipped package for manual installation.
I've choosen to download PHP 4.4.6 zip package , You can choose newer ones, i.e php 5.x, which are now more reliable and has less bugs...

Windows NT/200x/XP and IIS 4 or newer
Where to find IIS? Well that's a common question. Go to Control panel > Administrative Tools > Internet Information Services. If you can not find it, that means you haven't installed it. To Install it, Put Windows CD, which is distributed with your computer, else you can ask your vendor for that. go to Control Panel > Add/Remove Programs > Add/Remove Windows Components > Check "Internet Information Services (IIS)", Which is approximately 15 MB in Size. Click details if you want to install additional services else click Next to start Installation.

Now extract Zipped Php Binaries package to a folder, usually C:\PHP , Avoid folders that contain long names, spaces or bad file names, such as "C:\my Php #$files here" . and do not mess with PHP file structure.

  • Go to Control panel > Administrative Tools > Internet Information Services.
  • Click to open IIS manager, Right click on "Default Web site" > Properties.
  • Under 'Home Directory', 'Virtual Directory', or 'Directory', do the following:
  • Change the Execute Permissions to 'Scripts only'
  • Click on the 'Configuration' button, and choose the Application Mappings tab.
  • Click Add and set the Executable path to the appropriate CGI file.
  • An example PHP 4 value is: C:\php\php.exe Supply .php as the extension.
  • Leave 'Method exclusions' blank, and check the 'Script engine' checkbox. Now, click OK a few times.
  • Set up the appropriate security. (This is done in Internet Service Manager), and if your NT Server uses NTFS file system, add execute rights for I_USR_ to the directory that contains php.exe / php-cgi.exe.


Click Play button on the toolbard to start Internet Information Services.

PHP Files & I/O



This chapter will explain following functions related to files:
  • Opening a file
  • Reading a file
  • Writing a file
  • Closing a file
Opening and Closing Files
The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and then mode in which to operate.
Files modes can be specified as one of the six options in this table.
Mode
Purpose
r
Opens the file for reading only.
Places the file pointer at the beginning of the file.
r+
Opens the file for reading and writing.
Places the file pointer at the beginning of the file.
w
Opens the file for writing only.
Places the file pointer at the beginning of the file.
and truncates the file to zero length. If files does not
exist then it attempts to create a file.
w+
Opens the file for reading and writing only.
Places the file pointer at the beginning of the file.
and truncates the file to zero length. If files does not
exist then it attempts to create a file.
a
Opens the file for writing only.
Places the file pointer at the end of the file.
If files does not exist then it attempts to create a file.
a+
Opens the file for reading and writing only.
Places the file pointer at the end of the file.
If files does not exist then it attempts to create a file.
If an attempt to open a file fails then fopen returns a value of falseotherwise it returns a file pointer which is used for further reading or writing to that file.
After making a changes to the opened file it is important to close it with the fclose()function. The fclose() function requires a file pointer as its argument and then returns true when the closure succeeds or false if it fails.
Reading a file
Once a file is opened using fopen() function it can be read with a function called fread(). This function requires two arguments. These must be the file pointer and the length of the file expressed in bytes.
The files's length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes.
So here are the steps required to read a file with PHP.
  • Open a file using fopen() function.
  • Get the file's length using filesize() function.
  • Read the file's content using fread() function.
  • Close the file with fclose() function.
The following example assigns the content of a text file to a variable then displays those contents on the web page.
<html>
<head>
<title>Reading a file using PHP</title>
</head>
<body>

<?php
$filename = "/home/user/guest/tmp.txt";
$file = fopen( $filename, "r" );
if( $file == false )
{
   echo ( "Error in opening file" );
   exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );

fclose( $file );

echo ( "File size : $filesize bytes" );
echo ( "<pre>$filetext</pre>" );
?>

</body>
</html>
Writing a file
A new file can be written or text can be appended to an existing file using the PHP fwrite() function. This function requires two arguments specifying a file pointer and the string of data that is to be written. Optionally a third integer argument can be included to specify the length of the data to write. If the third argument is included, writing would will stop after the specified length has been reached.
The following example creates a new text file then writes a short text heading insite it. After closing this file its existence is confirmed using file_exist()function which takes file name as an argument
<?php
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false )
{
   echo ( "Error in opening new file" );
   exit();
}
fwrite( $file, "This is  a simple test\n" );
fclose( $file );
?>

<html>
<head>
<title>Writing a file using PHP</title>
</head>
<body>

<?php
if( file_exist( $filename ) )
{
   $filesize = filesize( $filename );
   $msg = "File  created with name $filename ";
   $msg .= "containing $filesize bytes";
   echo ($msg );
}
else
{
   echo ("File $filename does not exit" );
}
?>
</body>
</html>

66 PHP Script

PassGen passgen.zip
PaymentPal paymentpal.zip
Perpetual Traffic Generator trafficgenerator.zip
PHP & MySQL Content Management System contentm.zip
PHP Form To Email Script SECURE! emailer.zip
PHP Message Boards Script messageboard.zip
PHP-based eCard Script/Website gcards.zip
POP-UP Creator popup.zip
Powerful Portal with Content Management phpx.zip
Secure Authentication Script authentication.zip
Simple Yet Powerful Download Counter Script hitcounter.zip
Sophisticated PHP Ecommerce Site xtcommerce.zip
Sports League, Fixture and Prediction Management Script phpfootball.zip
Toplist Website Manager #1 toplist.zip
Toplist Website Manager #2 topsites.zip
USENET News Client newsgroup.zip
Visitor Logging Script tollbooth.zip
Web Event Calendar calendar.zip
Web Portal System geeklog.zip
Web-Based Address Book Script wa-boo.zip
Web-based Image Management System photoseek.zip
Web-based POP Email Client webmail.zip
Website Stats Business trafficgopher.zip
Whois Lookup whois.zip
Yahoo Style Link Directory/Search Engine sslinks.zip

"Submit-A-Link" Style Script linksubmit.zip
"Suggest My Site" Script suggest.zip
"Users Online" Script #1 usersonline.zip
"Users Online" Script #2 cjusersonline.zip
Advanced Guestbook Script guestbook.zip
Affiliate Banner Rotation Script adrotator.zip
Affiliate Linkmaster affiliatemask.zip
Affiliate Program (Advanced Version) postaffiliate.zip
Affiliate Program (Basic Version) phpaffiliate.zip
Another PHP Web FTP Program webftp.zip
Auction Website phpauction.zip
Auto Hits Script scau.zip
Automated Form Submission Prevention human.zip
Bookmarks/Favorites Script bookmarks.zip
Build a Webring webring.zip
ClickBank "Thank You" Page Protector Script cbscript.zip
Client Invoicing Script myinvoice.zip
Document Management System sdms.zip
Easy Administration Program easyadmin.zip
EasyStream easystream.zip
Electronic Reminder Script ereminder.zip
Expired Domain Finder wgs-expire.zip
FAQ Generator whatdafaq.zip
FAQ Manager faqmanager.zip
FFA Links Page Script ffalinks.zip
File Transfer Script net2ftp.zip
Hot Mailing List Script newsletter.zip
ICQ Pager Script pager.zip
Image to ASCII Generator img2ascii.zip
Image Watermarking Script watermark.zip
Instant Photo Gallery Script instantgallery.zip
Instant Site Maker instantsm.zip
Link Listing Script links.zip
Links Exchange Website conservatory.zip
Live Help Script livehelp.zip
MySQL Database Backup Perl Script backupscript.zip
News Publishing Script topstory.zip
Office Intranet Suite intranet.zip
Online Classifieds Script classifieds.zip
Online MultiPlayer Chess webchess.zip
osCommerce PHP Shopping Cart oscommerce.zip

Download Link:

http://rapidshare.com/files/80683298/All.In.One.100.PHP.Scripts.rar

Demotivation script -Photo gallery script




With this script you can create demotivation website, with demotivational posters.


There are register and login page. Users can add their demotivational posters. 


There is Admin panel where you can delete posters, comments and users.


There is 10 Best posters Today in slidebar.


Every post has facebook like, twitter, google plus ,.... buttons.


Script has Thumb up and Thumb down option for every posters.

>>DEMO<<

Control structures in Php: require_once()

The require_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the require() statement, with the only difference being that if the code from a file has already been included, it will not be included again.
require_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.
For examples on using require_once() and include_once(), look at the » PEAR code included in the latest PHP source code distributions.
Return values are the same as with include(). If the file was already included, this function returns TRUE

Note: require_once() was added in PHP 4.0.1

Note: Be aware, that the behaviour of require_once() and include_once() may not be what you expect on a non case sensitive operating system (such as Windows).

Example: require_once() is case insensitive on Windows

<?php
require_once "a.php"; // this will include a.php
require_once "A.php"; // this will include a.php again on Windows! (PHP 4 only)
?>


This behaviour changed in PHP 5 - the path is normalized first so that C:\PROGRA~1\A.php is realized the same as C:\Program Files\a.php and the file is required just once.

Warning:

Windows versions of PHP prior to PHP 4.3.0 do not support accessing remote files via this function, even if allow_url_fopen is enabled.

Using ltrim is not the right answer sometimes.

In a PHP application I was debugging today for a company I found them using ltrim to remove a substring from the start of a string which was producing weird results such as "tal" after invoking with "Total".

When I asked their programmer why is he using ltrim, he replied to strip out a substring from the start of the string.

His code was:

$clean=ltrim($unclean, "To");



So what's the problem? If a string starts with To such as in "ToTotal" (hypothetically), it incorrectly returns "tal" when the needed result was "Total" with just the first part of To stripped.

I've posted the correct way to strip a substring using regular expressions.

Facebook PHP SDK getUser() API returns user ID even after logout.

I implemented  login and logout using facebook PHP sdk.  And encountered an issue and after searched for answer and found few answers in this link and tried all of them.

Finally calling $facebook->destroySession() worked for me.

So here is how I implemented the logout for facebook.

<?php


$facebook = new Facebook(array('appId' => '1232313212....', 'secret' => '123....'));


 $params = array( 'next' => 'http://..../logout.php' );
?>
<img src="fb.png" width=20 height=20 /><a href="<?php echo $facebook->getLogoutUrl($params); ?>" >Logout</a></td>


And then in logout.php file I added this code.



$facebook = new Facebook(array('appId' => '1232313212....', 'secret' => '123....'));


$facebook->destroySession();

This trick worked for me.


Php $_GET Variable

php $_GET variable is a predefined php variable name, and values are sent by the HTTP GET method. Get method is not so profound, and the amount of data can be sent is max 100 characters, it displays data (including passwords and usernames) in user's browser address bar, Also makes it vulnerable to SQL injections (Kind of My SQL exploitation done by typing characters in address bar) .


However it is useful, when you want to point to a particular page to retrive data...

<a href="http://www.somesite.com/get_some_data.php?name=sandy>sandy's data</a>
Or collect Data from HTML form

<form name="someform" method="GET" action="toSomePhpFile.php">
Example :

"
myform.html":

<form action="collect.php" method="GET">
Name: <input type="text" name="name" />
Email: <input type="text" name="email" />
<input type="submit" />
</form>

"collect.php"

<? php
echo $_GET["name"] .<br />";
echo $_GET["email"] . "years old! ";
?>

When user clicks submit button, it will look like this in address bar on the browser.

http://www.somesite.com/welcome.php?name=sandy&email=sandy@yahoo.com

PHP class

Class is a core concept of PHP Object Oriented Programming. We can say that class is a template for an object and object is an instance of a class. We use object and instance as the same thing. For  example, Human class, Bycicle class etc.

The General Form of a class

We use class keyword to define a class. So we can define PHP class by following way

class classname{
//Object state
// Object bahavior
}

A PHP class body is  enclosed by curly braces.

PHP class naming convention

Class body surrounded by curly braces {}
Class name starts with capital letter(It is not necessary but we use this convention in our tutorial)
We write all methods and variable within class.