Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Wednesday, July 14, 2010

MLM application using PHP, Javascipt, CSS

Multi-level marketing (MLM), (also called network marketing, direct selling, and referral marketing,) is a term that describes a marketing structure used by some companies as part of their overall marketing strategy. The structure is designed to create a marketing and sales force by compensating promoters of company products not only for sales they personally generate, but also for the sales of other promoters they PHPintroduce to the company, creating a downline of distributors and a hierarchy of multiple levels of compensation(Source: WIKI).

Complete Multilevel marketing website script in PHP with a nice MLM TREE . Here are the screen shots of the same. Try to develop one like this.Full source code for commercial use is also available. If need that please contact us.

Read More

Wednesday, March 3, 2010

Way2Sms php

$post_data = "username=username&password=pwd";
//$header_array[]="User-Agent:
$url = "http://wwwa.way2sms.com/auth.cl";
$cookie = tempnam ("/tmp", "CURLCOOKIE");
$ch = curl_init();
curl_setopt( $ch, CURLOPT_USERAGENT,"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5" );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: application/x-www-form-urlencoded","Accept: */*"));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_ENCODING, "" );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ); # required for https urls
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 );
curl_setopt($ch,CURLOPT_REFERER,"http://wwwg.way2sms.com//entry.jsp");
$content = curl_exec( $ch );
$response = curl_getinfo( $ch );


$url = "http://wwwa.way2sms.com//jsp/InstantSMS.jsp?val=0";
curl_setopt( $ch, CURLOPT_USERAGENT,"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5" );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_ENCODING, "" );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
curl_setopt( $ch, CURLOPT_MAXREDIRS, 0 );
$content = curl_exec( $ch );
$response = curl_getinfo( $ch );
//site content in the instant sms
$tmp = substr ($content,strrpos($content,"Action",0)+15,15);
//value of Action=custfromnnnn which will be different for each customer
$id = substr($tmp,0,strrpos($tmp,"\"",0));


$post_data = "custid=undefined&HiddenAction=instantsms&Action=$id&login=&pass=&MobNo=9986966496&textArea=test sms";
$url = "http://wwwa.way2sms.com/FirstServletsms?custid=";
curl_setopt( $ch, CURLOPT_USERAGENT,"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5" );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: application/x-www-form-urlencoded","Accept: */*"));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_ENCODING, "" );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ); # required for https urls
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
curl_setopt( $ch, CURLOPT_MAXREDIRS, 0 );
$content = curl_exec( $ch );
$url = "http://wwwa.way2sms.com/jsp/logout.jsp";
curl_setopt( $ch, CURLOPT_USERAGENT,"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5" );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: application/x-www-form-urlencoded","Accept: */*"));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_ENCODING, "" );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ); # required for https urls
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
curl_setopt( $ch, CURLOPT_MAXREDIRS, 0 );
$content = curl_exec( $ch );
//echo $content;
?>

Thursday, October 15, 2009

HTML Form elements array

Creating array of HTML form elements

Array is a collection of similar data elements, means we can use array to store similar elements referenced under a common name.


In web development sometimes we need to group HTML form elements as arrays do. For example, you have a form where user has to select his hobbies from a group of check boxes as given below.










Sample Code
<form action="showlist.php" method="post" name="hobby_frm">
<h3> Select your hobbies </h3>
<input type="checkbox" name="hobbies[]" value="hb1"  />
Reading <br />
<input type="checkbox" name="hobbies[]" value="hb2" />
Surfing <br />
<input type="checkbox" name="hobbies[]" value="hb3" />
Listening to music  <br />
<input type="submit" value="submit" />
</form>
Please notice the name of all checkboxes hobbies[]
The above code will define an array with the name hobbies

Accessing form elements array using JavaScript

Now, let's see how to access the hobbies[] using JavaScript.
<script type="text/javascript">
var hobbies = document.hobby_frm.elements['hobbies[]'];
var str = "Length  : "+hobbies.length+"\n";
for( var i = 0; i < hobbies.length; i++ ) {
str = str + "Hobby "+(i+1)+" : "+hobbies[i].value+"\n";
}
alert(str);
</script>
Handle form elements array in PHP

In PHP, data sent from a form with post method is available in $_POST array.
We can access hobbies[] using the following code.


<?php
$hobbies = $_POST['hobbies']; // use name of the array as key
foreach( $hobbies as $value )
print $value;
?>



courtesey webdevelopment hosting company cochin kerala

Tuesday, July 14, 2009

EXTRACT ALL LINK FROM A GIVEN HTML PAGE

This below function accept an html page(as a result of curl_excec()) as input
it will search and retrieve all links from that page and return it
it uses xpath to retrieve the link
try it.....

function get_link($html)
{
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");
for ($i = 0; $i < $hrefs->length; $i++) {
$href = $hrefs->item($i);
$url = $href->getAttribute('href');
echo $url."
"
return $url;
}
?>

parsing data from excel xml sheet using DOM

here the excel sheet contains two coulmns
1.url
2.result
parsed the above are saved into corresponding variables,$url,$result

enter data into a excel sheet then save it as excel xml with extension .xml
upload in to the script





if ( $_FILES['file']['tmp_name'] )
{
$dom = DOMDocument::load( $_FILES['file']['tmp_name'] );
$rows = $dom->getElementsByTagName( 'Row' );
$first_row = true;
foreach ($rows as $row)
{
if ( !$first_row )
{
$url = "";
$result = "";

$index = 1;
$cells = $row->getElementsByTagName( 'Cell' );
// echo $cells;
foreach( $cells as $cell )
{
$ind = $cell->getAttribute( 'Index' );
if ( $ind != null ) $index = $ind;
//echo $index;
if ( $index == 1 ) $url = $cell->nodeValue;

if ( $index == 2 ) $result = $cell->nodeValue;
//echo "$cell->nodeValue";
$index += 1;
}

PHP code to check whether a yahoo user is online or not

Hi

Do you want to check whether a yahoo user is avoiding you by setting his status to invisible mode. Please try this code..

< ? php //-------> No spaces in between
$id="sujith.sasi";
$url = 'http://opi.yahoo.com/online?u=';
$data = file_get_contents($url . $id);
if (trim(strtolower(strip_tags($data))) != 'user not specified.') {
echo (strlen($data) == 140) ? 'online' : 'offline'; }
else {
echo trim(strip_tags($data));
} ?>


cheers........ :-) [Remember to remove the spaces b/w the php "
< ? php " tag]

login and get contacts from yahoo mail with php curl

This is the script used to login into yahoo mail in an automated way. This script also fetching the contacts and email addresses from the address book.Very popular php curl library is used in this script.


set_time_limit(0);

if($_POST['login'])
{

$php_userid = $_POST['login'];
$php_password = $_POST['passwd'];


$cookie_file_path = "./cookie.txt"; // Please set your Cookie File path


$fp = fopen($cookie_file_path,'wb');
fclose($fp);
$agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)";
$reffer = "http://mail.yahoo.com/";

// log out.
$LOGINURL = "http://us.ard.yahoo.com/SIG=12hoqklmn/M=289534.5473431.6553392.5333790/D=mail/S=150500014:HEADR/Y=YAHOO/EXP=1135053978/A=2378664/R=4/SIG=133erplvs/*http://login.yahoo.com/config/login?logout=1&.done=http://mail.yahoo.com/&.src=ym&.lg=us&.intl=us";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$LOGINURL);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
$result = curl_exec ($ch);
curl_close ($ch);

//1. Get first login page to parse hash_u,hash_challenge

$LOGINURL = "http://mail.yahoo.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$LOGINURL);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
$loginpage_html = curl_exec ($ch);
curl_close ($ch);

preg_match_all("/name=\".u\" value=\"(.*?)\"/", $loginpage_html, $arr_hash_u);
preg_match_all("/name=\".challenge\" value=\"(.*?)\"/", $loginpage_html, $arr_hash_challenge);

$hash_u = $arr_hash_u[1][0];
$hash_challenge = $arr_hash_challenge[1][0];

// 2- Post Login Data to Page https://login.yahoo.com/config/login?

$LOGINURL = "https://login.yahoo.com/config/login?";
$POSTFIELDS = '.tries=1&.src=ym&.md5=&.hash=&.js=&.last=&promo=&.intl=us&.bypass=&.partner=&.u='.$hash_u.'&.v=0&.challenge='.$hash_challenge.'&.yplus=&.emailCode=&pkg=&stepid=&.ev=&hasMsgr=0&.chkP=Y&.done=http%3A%2F%2Fmail.yahoo.com&login='.$php_userid.'&passwd='.$php_password;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$LOGINURL);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$POSTFIELDS);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_REFERER, $reffer);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
$result = curl_exec ($ch);
curl_close ($ch);

preg_match_all("/replace\(\"(.*?)\"/", $result, $arr_url);
$WelcomeURL = $arr_url[1][0];

// 3- Redirect to Welcome page. (Login Success)

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$WelcomeURL);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_REFERER, $reffer);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
$result = curl_exec ($ch);
curl_close ($ch);
// echo $result;

// 4- Get Address Book.
$addressURL = 'http://address.mail.yahoo.com/?A=B';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$addressURL);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_REFERER, $reffer);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
$result = curl_exec ($ch);
curl_close ($ch);


//print $result;
preg_match_all("/\"\/yab\/us\/Yahoo\.csv\?(.*?)\"/", $result, $arr_address_url);
$randURL = html_entity_decode($arr_address_url[1][0]);
preg_match_all("/id=\"crumb2\" value=\"(.*?)\"/", $result, $arr_crumb);
$hash_crumb = $arr_crumb[1][0];

// 5- show Address Book.
$addressURL = 'http://address.mail.yahoo.com/index.php';

$POSTFIELDS ='.crumb='.$hash_crumb.'&VPC=import_export&submit%5Baction_export_yahoo%5D=Export+Now';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$addressURL);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$POSTFIELDS);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_REFERER, $reffer);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
$result = curl_exec ($ch);
curl_close ($ch);

//print $result;

} // extra code 2 if

else
{
login_form();
}


////////////////////////////////////////////////////////////////////////////////////////////////
Here login form is the function to generate a html form with username and password
login and passwd are the name of the used text field respectively

Monday, July 13, 2009

Random Number generation in PHP

function randomdigit($digits) {
static $startseed = 0;
if (!$startseed) {
$startseed = (double)microtime()*getrandmax();
srand($startseed);
}
$range = 8;
$start = 1;
$i = 1;
while ($i<$digits) {
$range = $range . 9;
$start = $start . 0;
$i++;
}
return (rand()%$range+$start);
}
?>

PHP program for trace remote IP address

This program helps you to trace the IP address of u'r visitor
class IPDetails{
var $ip;
var $countryName;
var $countryCode;
var $status;
var $regionCode;
var $regionName;
var $city;
var $zip;
var $latitude;
var $longitude;
var $gmtOffset;
var $dstOffset;

function collectIPDetails($ip){
$proxy = "192.168.0.6:3128";
$addr = "http://www.ipinfodb.com/ip_query.php?ip=$ip&output=xml";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $addr);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPGET,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
$pg = curl_exec($ch);
if($pg){
$data = new SimpleXMLElement($pg);
$this->ip = $data->Ip;
$this->countryName = $data->CountryName;
$this->countryCode = $data->CountryCode;
$this->status = $data->Status;
$this->regionCode = $data->RegionCode;
$this->regionName = $data->RegionName;
$this->city = $data->City;
$this->zip = $data->ZipPostalCode;
$this->latitude = $data->Latitude;
$this->longitude = $data->Longitude;
$this->gmtOffset = $data->Gmtoffset;
$this->dstOffset = $data->Dstoffset;
}
}
}
$dt=new IPDetails();
$ip = $_SERVER['REMOTE_ADDR'];
$dt->collectIPDetails($ip);
echo $dt->countryName;
echo $dt->ip;
?>

Monday, June 8, 2009

Currency Exchange Rate from Europian Cental Bank (PHP)


// Define a context for HTTP.
$aContext = array(
'http' => array(
'proxy' => 'tcp://192.168.0.5:3128', // This needs to be the server and the port of the NTLM Authentication Proxy Server.
'request_fulluri' => True,
),
);
$cxContext = stream_context_create($aContext);

// Now all file stream functions can use this context.

//$sFile = file_get_contents("http://www.php.net", False, $cxContext);

//This is a PHP (4/5) script example on how eurofxref-daily.xml can be parsed

//Read eurofxref-daily.xml file in memory
$XMLContent= file("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml",False,$cxContext);
//the file is updated daily between 2.15 p.m. and 3.00 p.m. CET

foreach ($XMLContent as $line) {
if (ereg("currency='([[:alpha:]]+)'",$line,$currencyCode)) {
if (ereg("rate='([[:graph:]]+)'",$line,$rate)) {
//Output the value of 1 EUR for a currency code
echo '1 € = '.$rate[1].' '.$currencyCode[1].'
';

//--------------------------------------------------
// Here you can add your code for inserting
// $rate[1] and $currencyCode[1] into your database
//--------------------------------------------------
}
}
}
?>

csv file to an array

$row = 1;
$handle = fopen("test.csv", "r");
while ((
$data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo
"

$num fields in line $row:

\n"
;
$row++;
for (
$c=0; $c < $num; $c++) {
echo
$data[$c] . "
\n"
;
}
}
fclose($handle);
?>

Tuesday, May 26, 2009

online Exchange Rate (PHP)


$us_price = '100';

$ticker= 'CADUSD=X';
$open = fopen("http://quote.yahoo.com/d/quotes.csv?s=$ticker&f=sl1d1t1c1ohgv&e=.csv", "r");
$exchange_rate = fread($open, 2000);
fclose($open);
$exchange_rate = str_replace("\"", "", $exchange_rate);
$exchange_rate = explode(",", $exchange_rate);
$ca_price = ($us_price/$exchange_rate[1]);
$price = number_format ($ca_price, 2);

echo "$us_price US dollars = \$$price Canadian dollars";

?>

Saturday, April 25, 2009

Send email from a PHP script

PHPMailer is a powerful email transport class. Sending email using PHPMailer is simple.

PHPMailer features:-


  • Supports emails digitally signed with S/MIME encryption!
  • Supports emails with multiple TOs, CCs, BCCs and REPLY-TOs
  • Works on any platform.
  • Supports Text & HTML emails.
  • Embedded image support.
  • Multipart/alternative emails for mail clients that do not read HTML email.
  • Flexible debugging.
  • Custom mail headers.
  • Redundant SMTP servers.
  • Support for 8bit, base64, binary, and quoted-printable encoding.
  • Word wrap.
  • Multiple fs, string, and binary attachments (those from database, string, etc).
  • SMTP authentication.
  • Tested on multiple SMTP servers: Sendmail, qmail, Postfix, Gmail, Imail, Exchange, etc.
  • Good documentation, many examples included in download.
  • It's swift, small, and simple.
[http://phpmailer.codeworxtech.com]

How to use

Download PHPMailer from http://sourceforge.net/projects/PHPmailer
Extract it into your web directory.
Turn on SSL support.
Use the following code to send email.

Sample code

include("/lib/phpmailer/class.phpmailer.php");
$mail = new PHPMailer(); // Creating PHPMailer object
$body = "Hai hello, this is my first mail using PHPMailer. ";
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Host = "ssl://smtp.gmail.com:465"; // SMTP Server.
/*
Setting gmail as the SMTP Server
*/
$mail->Username = "myphpapp@gmail.com"; // username [Gmail]
$mail->Password = "mypassword
"; // password for myphpapp
$mail->AltBody = "This is the body when user views in plain text format";
$mail->Subject = "Say hello!"; // This is the subject
$mail->From = "myphpapp@gmail.com"; // From email-id
$mail->FromName = "PHP Developer"; // From Name
$mail->MsgHTML($body);
$mail->AddAddress("toaddress@gmail.com","Name"); // To address.
$mail->IsHTML(true);
if(!
$mail->Send()) {
echo
"Mailer Error: " . $mail->ErrorInfo;
}
else {
echo
"Message has been sent";
}
?> 


courtsey: nexabion software cum webdevelopers and webhosting providers kerala

Wednesday, April 15, 2009

php object array to javascript array

The code.

'php_object_array' is the object array
each object has the values 'php_name' and 'php_id'.

'js_name' and 'js_id' are the javascript array corresponding to the objects values



Wednesday, March 25, 2009

Create a web service with PHP

[W3C Definition: A Web service is a software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format (specifically WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web-related standards.] For more details visit http://www.w3.org/TR/ws-arch/

In PHP, the soap extension can be used to create soap based web services. http://php.net/soap

This article will shows you how to create a simple web service with PHP.

Soap Server

A simple server that receives a soap request and sends a response.The server takes a name from the client and returns a hello message.

Recommended IDE : Eclipse PDT [ http://www.eclipse.org/pdt ]

Listing 1: HelloServer.php


<?php

// Method

function sayHello($name){

return
"Hello $name";

}

// Create a SoapServer object using WSDL file.

// For the simplicity, our SoapServer is set to operate in non-WSDL mode. So we do not need a WSDL file

$server = new SoapServer(null, array('uri'=>'http://localhost/hello'));

// Add sayHello() function to the SoapServer using addFunction().

$server->addFunction("sayHello");

// To process the request, call handle() method of SoapServer.

$server->handle();

?>


Soap Client

Soap client allows you to communicate with server.

Listing 2: HelloClient.php


<?php

try {



// Create a soap client using SoapClient class

// Set the first parameter as null, because we are operating in non-WSDL mode.

// Pass array containing url and uri of the soap server as second parameter.



$client = new SoapClient(null, array(

'location' => "http://localhost/hello/HelloServer.php",

'uri' => "http://localhost/hello"));



// Read request parameter



$param = $_GET['name'];



// Invoke sayHello() method of the soap server (HelloServer)



$result = $client->sayHello($param);

print
$result; // Process the the result

}

catch(
SoapFault $ex) {

$ex->getMessage();

}



?>

HelloView

Create view for interacting with end-user

Listing 3: Helloview.php

<?php

print "<h3>Welcome to PHP Web Service</h3>";

print
"<form action='HelloClient.php' method='GET'/>";

print
"<input name='name' /><br/>";

print
"<input type='Submit' name='submit' value='GO'/>";

print
"</form>";

?>

locate Helloview.php with your web browser




Wednesday, March 18, 2009

SQL INJECTION

What is SQL Injection

SQL injection refers to the act of someone inserting a MySQL statement to be run on your database without your knowledge. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a MySQL statement that you will unknowingly run on your database.

SQL Injection Example

Below is a sample string that has been gathered from a normal user and a bad user trying to use SQL Injection. We asked the users for their login, which will be used to run a SELECT statement to get their information.

MySQL & PHP Code:

// a good user's name
$name = "timmy";
$query = "SELECT * FROM customers WHERE username = '$name'";
echo "Normal: " . $query . "
";

// user input that uses SQL Injection
$name_bad = "' OR 1'";

// our MySQL query builder, however, not a very safe one
$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";

// display what the new query will look like, with injection
echo "Injection: " . $query_bad;

Display:

Normal: SELECT * FROM customers WHERE username = 'timmy'
Injection: SELECT * FROM customers WHERE username = '' OR 1''

The normal query is no problem, as our MySQL statement will just select everything from customers that has a username equal to timmy.

However, the injection attack has actually made our query behave differently than we intended. By using a single quote (') they have ended the string part of our MySQL query

  • username = ' '

and then added on to our WHERE statement with an OR clause of 1 (always true).

  • username = ' ' OR 1

This OR clause of 1 will always be true and so every single entry in the "customers" table would be selected by this statement!

More Serious SQL Injection Attacks

Although the above example displayed a situation where an attacker could possibly get access to a lot of information they shouldn't have, the attacks can be a lot worse. For example an attacker could empty out a table by executing a DELETE statement.

MySQL & PHP Code:

$name_evil = "'; DELETE FROM customers WHERE 1 or username = '";

// our MySQL query builder really should check for injection
$query_evil = "SELECT * FROM customers WHERE username = '$name_evil'";

// the new evil injection query would include a DELETE statement
echo "Injection: " . $query_evil;

Display:

SELECT * FROM customers WHERE username = ' '; DELETE FROM customers WHERE 1 or username = ' '

If you were run this query, then the injected DELETE statement would completely empty your "customers" table. Now that you know this is a problem, how can you prevent it?

Injection Prevention - mysql_real_escape_string()

Lucky for you, this problem has been known for a while and PHP has a specially-made function to prevent these attacks. All you need to do is use the mouthful of a function mysql_real_escape_string.

What mysql_real_escape_string does is take a string that is going to be used in a MySQL query and return the same string with all SQL Injection attempts safely escaped. Basically, it will replace those troublesome quotes(') a user might enter with a MySQL-safe substitute, an escaped quote \'.

Lets try out this function on our two previous injection attacks and see how it works.

MySQL & PHP Code:

//NOTE: you must be connected to the database to use this function!
// connect to MySQL

$name_bad = "' OR 1'";

$name_bad = mysql_real_escape_string($name_bad);

$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";
echo "Escaped Bad Injection:
" . $query_bad . "
";


$name_evil = "'; DELETE FROM customers WHERE 1 or username = '";

$name_evil = mysql_real_escape_string($name_evil);

$query_evil = "SELECT * FROM customers WHERE username = '$name_evil'";
echo "Escaped Evil Injection:
" . $query_evil;

Display:

Escaped Bad Injection:
SELECT * FROM customers WHERE username = '\' OR 1\''
Escaped Evil Injection:
SELECT * FROM customers WHERE username = '\'; DELETE FROM customers WHERE 1 or username = \''

Notice that those evil quotes have been escaped with a backslash \, preventing the injection attack. Now all these queries will do is try to find a username that is just completely ridiculous:

  • Bad: \' OR 1\'
  • Evil: \'; DELETE FROM customers WHERE 1 or username = \'

And I don't think we have to worry about those silly usernames getting access to our MySQL database. So please do use the handy mysql_real_escape_string() function to help prevent SQL Injection attacks on your websites. You have no excuse not to use it after reading this lesson!

LinkWithin

Related Posts with Thumbnails