Monday, 11 June 2012

Interfaces in php



Everyone is familiar with interfaces in java. but here iam trying to explain about interfaces in php.Iam not explaining here what interfaces means but iam expaining an example of code which is done using interface.Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.

Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.

All methods declared in an interface must be public, this is the nature of an interface.

so here iam giving a small code which implements Interfaces in php......
Question is to create html and txt file according to the users choice.???

create an interface with following code.
<?php
interface interf{
public function fileopen();
public function filewrite();
public function fileclose();
public function setFileName($string);
public function  settext($content);
}
?>
name interface as interf.php

Now we have to create two classes named Htmlwriter and textwriter which implements the interface:-
<?php
class Htmlwriter implements interf{

public $fileorg;
public $txt;
    public $fp;

    function __construct(){

$this->fileorg =null;// declaring variables publically
$this->txt=null;
$this->fp=null;
}
function setFileName($string){
$this->fileorg=$string;//setting the filename to public string

}
function settext($content){
$this->txt=$content;//setting the content text
}
function fileopen(){
$path="uploads/";
// if(is_dir($path)){
// $d=mkdir($path,0777,true);
// }
$name='uploads/'.$this->fileorg;//opening the filename that set publically with the setfilename function
$this->fp=fopen($name,"w");

 }
function filewrite(){

fwrite($this->fp,$this->txt);//writing to the publically set file
return true;
 }

function fileclose(){
fclose($this->fp);//closing the file
return true;
 }
}
?>
name this file as Htmlwriter.php


now create another file called Textwriter.php
<?php
class Textwriter implements interf{

public  $fileorg;
public  $txt;
    public  $fp;
    function __construct(){

$this->fileorg =null;
$this->txt=null;
$this->fp=null;
}
function setFileName($string){
$this->fileorg=$string;

}
function settext($content){
$this->txt=$content;
}
function fileopen(){
$path="uploads/";
// if(is_dir($path)){
// $d=mkdir($path,0777,true);
// }
$name='uploads/'.$this->fileorg;
$this->fp=fopen($name,"w");

 }
function filewrite(){

fwrite($this->fp,$this->txt);
return true;
 }
function fileclose(){
fclose($this->fp);
return true;
 }
}
?>
save it.. save these interface and classes in libs folder in your main folder

don't forget to create a folder named uploads inside the main folder so that it can store the created html and text files.

now include the user interface file name it as index.php and paste code like this:-
<?php
include("autoload.php");
include("Htmlwriter.php");
include("Textwriter.php");
//include("interf.php");
// $db = new Factory();
// $db->connect();


//include("interf.php");

function SelectClass($type){// main factory method returns the object corresponding to the file want to create
if($type=='1'){
$rec=new Textwriter();
return($rec);
}
else
{
$rec=new Htmlwriter();
return($rec);
}
 }

if(isset($_POST["saveForm"])){
 $txt=$_POST["txt"];
 $type=$_POST["type"];
 $filename=$_POST["filename"];

$obj=SelectClass($type);
if($type==1){//checking which type of file to be created
$file=$filename.'.txt';
//$obj=new Textwriter();
}else{
$file=$filename.'.html';
//$obj=new Htmlwriter();
}

$obj->setFileName($file);//setting file name
$obj->fileopen();//opening the setted file
$obj->settext($content);//setting contents to be write to the file
$obj->filewrite();//writing to file
$obj->fileclose();  //closing file
if($obj){
echo "success";
} else
{
echo 'notsuccess';
}

}
?>
<h1> Form</h1>
<form action="index.php" method="post">

  <div style="float:left">
  <div style="width:200px;height:50px;float:left">File Type</div>
  <div  style="width:400px;height:50px;float:left"><select name="type">
  <option value="1">Text</option>
  <option value="2">Html</option>
  </select></div>
  </div>
         

          <div style="float:left">
          <div style="width:200px;height:100px;float:left">file name</div>
          <div  style="width:400px;height:100px;float:left"><input type="text" name="filename"/></div>
          </div>


<div style="float:left">
<div style="width:200px;height:100px;float:left">Contents</div>
<div  style="width:400px;height:100px;float:left"><textarea name="txt" cols="50" rows="20"></textarea></div>
</div>



<div style="width:200px;height:500px;float:left;padding:250px;"><input type="submit" name="saveForm" value="Save"  title="Save Content" /></div>
<!--Content-->

</form>

Now it's time to run the code.

Working with graphics in php


we can also draw basic shapes like rectagle,square,circle...etc..and can do garphics much like all programming languages also in php. There exist a library for helping users in doing graphics.
Here iam giving you a sample of graphics work. here iam going to draw acircle and small circles just like what given in above image. like the atoms arranged in shell of an element.
so for doing this code is like this:-
<?php

header('Content-type:image/jpeg');//setting that the output is an i,age

$image = imagecreatetruecolor(500,500);// generating canvas for the image
$col1 = imagecolorallocate($image,255,255,255);//generating a colour
$col2 = imagecolorallocate($image,125,100,20);//generating a colour
imagefilledrectangle($image, 0,0, 500,500,$col1);//creatinga canvas rectangle
imagefilledrectangle($image, 50,50, 450,450,$col2);
imagearc( $image,220,220, 300,300, 0, 360, $col1);//creating the major circle
$f=6;//number of circles to generate
//$f=$_GET['number'];
if($f!=0){
$degree=(360/$f);// finding the unit degree so that circle comes in equal distance over the main circle
$d=ceil($degree);
$r=ceil($degree);//removing decimal places

for($i=0;$i<=360;$i++){// looping 360 degree

if($i==$d){// checking between current degree and calculated degree
$s=($i*3.14)/180;//converting degree to radian
 $x[$i]=220+(150*cos($s));//finding x cordiante of the point in circle

 $y[$i]=220+(150*sin($s));//finding y cordinate of point in circle

 imagearc($image,$x[$i],$y[$i], 50,50, 0, 360, $col1);//dawing the circle
 $d=$d+$r;//incrementing the angle
}

 }
}
imagejpeg($image);//outputting the image




?>

Wednesday, 6 June 2012

Sending mail through smtp servers in php

By default the php provides mail function of it's own.But in some servers this will not work.Or there may be situation arise when your network ip may be blacklisted.so the every mail you have send is regarded as spam by most mail servers so their arise situation where you have to send mail using smtp server.Iam not ensuring that it works with all smtp servers,but it will work with most smtp servers. try it................
<?php

$from="yourmail@gmail.com";
$namefrom="name";
$to = "receivermail@gmail.com";
$nameto = "litzr";
$subject = "haaai";
$message = "Email from My Domain";
$smtpServer = "smtpserverip"; //ip address of the mail server. This can also be the local domain name
$port = "25"; // should be 25 by default, but needs to be whichever port the mail server will be using for smtp
$timeout = "45"; // typical timeout. try 45 for slow servers
$username = "usernameXXXX"; // the login for your smtp
$password = "XXXXX"; // the password for your smtp
$localhost = "localhost"; // Defined for the web server. Since this is where we are gathering the details for the email
$newLine = "\r\n"; // aka, carrage return line feed. var just for newlines in MS
$secure = 0; // change to 1 if your server is running under SSL

//connect to the host and port
$smtpConnect = fsockopen($smtpServer, $port, $errno, $errstr, $timeout);
$smtpResponse = fgets($smtpConnect, 4096);
if(empty($smtpConnect)) {
$output = "Failed to connect: $smtpResponse";
echo $output;
return $output;
}
else {
$logArray['connection'] = "<p>Connected to: $smtpResponse";
echo "<p />connection accepted<br>".$smtpResponse."<p />Continuing<p />";
}

//you have to say HELO again after TLS is started
fputs($smtpConnect, "HELO ".$localhost.$newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['heloresponse2'] = $smtpResponse;
//request for auth login
fputs($smtpConnect,"AUTH LOGIN" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['authrequest'] = $smtpResponse;

//send the username
fputs($smtpConnect, base64_encode($username) . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['authusername'] = $smtpResponse;

//send the password
fputs($smtpConnect, base64_encode($password) . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['authpassword'] = $smtpResponse;

//email from
fputs($smtpConnect, "MAIL FROM: <$from>" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['mailfromresponse'] = $smtpResponse;

//email to
fputs($smtpConnect, "RCPT TO: <$to>" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['mailtoresponse'] = $smtpResponse;

//the email
fputs($smtpConnect, "DATA" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['data1response'] = $smtpResponse;

//construct headers
$headers = "MIME-Version: 1.0" . $newLine;
$headers .= "Content-type: text/html; charset=iso-8859-1" . $newLine;
$headers .= "To: $nameto <$to>" . $newLine;
$headers .= "From: $namefrom <$from>" . $newLine;

//observe the . after the newline, it signals the end of message
fputs($smtpConnect, "To: $to\r\nFrom: $from\r\nSubject: $subject\r\n$headers\r\n\r\n$message\r\n.\r\n");
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['data2response'] = $smtpResponse;

// say goodbye
fputs($smtpConnect,"QUIT" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['quitresponse'] = $smtpResponse;
$logArray['quitcode'] = substr($smtpResponse,0,3);
fclose($smtpConnect);
//a return value of 221 in $retVal["quitcode"] is a success
print_r($logArray);




?>

Tuesday, 5 June 2012

Sending email in your lan network from any existing emails



You can send mail in your lan network not using any gmail connection, if you have linux system with you.
just go to terminal and type

telnet localhost 25

eg: [developer@localhost ~]$ telnet localhost 25
now the server will return like this


Trying 192.168.1.23...
Connected to localhost.localdomain (192.168.1.23).
Escape character is '^]'.
220 localhost.localdomain ESMTP Postfix

now the message from server tells that you are connected to server and we can start our operation
just type
HELO localhost
and now server will return a postive message something like
eg:
250 localhost6.localdomain6 Hello localhost.localdomain [127.0.0.1], pleased to meet you


now type from address that you wish in the lan network

type
MAIL FROM:address@gmail.com

if it is ok then server will send message like
250 2.1.0 Ok

now type the recepient address that you wish
type
RCPT TO:receptaddress@gmail.com

now if it is ok then server will return some message like this
250 2.1.5 Ok

Now it's time to submit content of message type like this :

DATA
press enter the server returns something like
354 End data with <CR><LF>.<CR><LF>

then you can type your message below it like
Subject:HELLo

hello da
.

when you finish your message type . to stop.
now press enter your message will be listed in que of localserver and it will be send soon..

so overall terminal looks something like this :-
[developer@localhost ~]$ telnet localhost 25
Trying 192.168.1.23...
Connected to localhost.localdomain (192.168.1.23).
Escape character is '^]'.
220 localhost.localdomain ESMTP Postfix
HELO localhost
250 localhost.localdomain
MAIL FROM:rcpt@gmail.com
250 2.1.0 Ok
RCPT TO:youraddress@gmail.com
250 2.1.5 Ok
DATA
354 End data with <CR><LF>.<CR><LF>
Subject:HELLo

hello da
.
250 2.0.0 Ok: queued as 7195CD7CC6

Monday, 4 June 2012

Finding Current Exchange rates in php

Here is the code for finding current exchange rates in php... simply copy the code. it will give you details of exchange rates at particular time.........
<?php

$names = array ( 0=> "USD",1=> "JPY",2=> "DKK",3=> "GBP",4=> "SEK",5=> "CHF",6=> "ISK",7=> "NOK",8=> "BGN",9=> "CYP",10=> "CZK",11=> "EEK",12=> "HUF",13=> "LTL",14=> " LVL",15=> "MTL",16=> "PLN",17=> "ROL",18=> "SIT",19=> "SKK",20=> "TRL",21=> "TRY",22=> "AUD",23=> "CAD",24 => "HKD",25 => "NZD",26 => "SGD27 =28=> "EUR ",
29=> "ZAR");
$g = array ( 0=> "USD",1=> "JPY",2="DKK",3=>"GBP",4=>"SEK",5=>"CHF",
6=> "ISK",7=> "NOK",8=> "BGN",9=> "CYP",10=> "CZK",11=> "EEK",12=> "HUF",13=> "LTL",14=> " LVL",15=> "MTL",16=> "PLN",17=> "ROL",18=> "SIT",19=> "SKK",20=> "TRL",21=> "TRY",22=> "AUD",23=> "CAD",24 => "HKD",25 => "NZD",26 => "SGD",27 => "KRW",28=> "EUR ",29=> "ZAR");

for($j=0;$j<count($g);$j++){

for($i=0;$i<count($names);$i++){
$from = $g[$j];
$to = $names[$i];
$url = 'http://finance.yahoo.com/d/quotes.csv?f=l1d1t1&s='.$from.$to.'=X';
$handle = fopen($url, 'r');

if ($handle) {
$result = fgetcsv($handle);
fclose($handle);
}

echo '1 '.$from.' is worth '.$result[0].' '.$to.' Based on data on '.$result[1].' '.$result[2];
echo '</br>';
}

}
?>

Simple Mysql functions for your php project

When you do a project in php related to web the main thing you have to came across is the management of database.This all functions including,connectig to database,retreiving values from databse,deleting,updating,inserting....etc.. so by including the library file iam providing below, you can just call that functions in your code and do all operations very fast without manually writing functions again and again:-
You can download the library from here:  https://github.com/litto/PHP-MYSQL-Library
The code is
<?php

class MySql
{
private $dbUser;
private $dbPass;
private $dbName;
private $dbHost;
private $dbConnection;
private $errorString;
private $filter;
private $util;
public static $instance;
public $query;
public $newCon;

function __construct(){

$this->dbConnection = null;
$this->filter = true;
$this->newCon = false;
}


function setNew(){
$this->newCon = true;
}
function noFilter()
{
$this->filter = false;
}
/*
* Setting Error Message on Db Operation
* Input String Message
* Called upon db operation
*/

function setError($string)
{
$this->errorString = $string;
//echo "MYSQL ERROR - ".$this->errorString;
}

/*
* get Error Message after a db operation
* Retrieves the current error Status
*/

function getError()
{
return $this->errorString;
}

/*
* Connect to Mysql Database using set up data
* Set up data being hold on Constructor
* Modify the constrct params for connection change
*/

function connect()
{
if(is_null($this->dbConnection)){
require_once(CONST_BASEDIR.'/config.php') ;
$this->dbUser = $config["databaseUser"];
$this->dbPass = $config["databasePass"];
$this->dbName = $config["databaseName"];
$this->dbHost = $config["databaseHost"];
try{
if($this->newCon==true){
$this->dbConnection = mysql_connect($this->dbHost,$this->dbUser,$this->dbPass,true);
}else{
$this->dbConnection = mysql_connect($this->dbHost,$this->dbUser,$this->dbPass);
}
if($this->dbConnection){
if(mysql_select_db($this->dbName,$this->dbConnection)){
}else{
$this->setError(mysql_error());
}
}else{
$this->setError(mysql_error());
}
}catch(Exception $c){
$this->setError($c);
}
}
}

function getInstance(){
return $this->dbConnection;
}

/*
* Close the Mysql Connection
*/

function close()
{
if($this->dbConnection){
mysql_close($this->dbConnection);
$this->dbConnection = null;
}else{
$this->dbConnection = null;
}
}

/*
* get ALl results for an SQL Select Statement
* Retrieves the result set values in 2 dimensional array
* Parms : query String
* Returns Array
*/

function fetchAll($query)
{
$this->query=$query;

$fileds = array();
$resultSet = array();
try{
$result = mysql_query($query);
if($result){
$fieldsLength = mysql_num_fields($result);
for($i=0;$i<$fieldsLength;$i++ ){
$fileds[$i] = mysql_field_name($result,$i);
}
if(mysql_num_rows($result)>0){
$start = 0;
while($row=mysql_fetch_row($result)){
for($i=0;$i<$fieldsLength;$i++ ){
if($this->filter){
$resultSet[$start][$fileds[$i]] = $this->removeFilter($row[$i]);
}else{
$resultSet[$start][$fileds[$i]] = $row[$i];
}

}
$start++;
}
}
mysql_free_result($result);
}

}catch(Exception $c){
$this->setError($c);
}
return $resultSet;
}

/*
* Mysql Insert operations
* Paramms $fild->value pair , table name
*/

function insert($options,$table)
{
$queryString = "";
$p = count($options);
$start = 0;
$fieldString = null;
$valueString = null;
foreach($options as $key=>$val){
$fieldString.=" `{$key}`";
$valueString.=" '{$val}' ";
if($start<$p-1){
$fieldString.=",";
$valueString.=",";
}
$start++;
}
$queryString = "INSERT INTO `{$table}` ({$fieldString}) VALUES ({$valueString}) ";
//echo "db".$queryString;

try{
$result = mysql_query($queryString) or $this->setError("Insert".mysql_error());
}catch(Exception $c){
$this->setError($c);
}
}


function insertMulti($fields,$values,$table)
{

$queryString = "";
$p = count($fields);
$start = 0;
foreach($fields as $key=>$val){
$fieldString.=" `{$val}`";
if($start<$p-1){
$fieldString.=",";
}
$start++;
}



for($i=0;$i<count($values);$i++){
$p = count($values[$i]);
$start = 0;
$valueString.="(";
foreach($values[$i] as $key=>$val){
$valueString.="'{$val}'";
if($start<$p-1){
$valueString.=",";
}
$start++;
}
$valueString.=")";
if($i<count($values)-1){
$valueString.=",";
}
}
unset($fields);
unset($values);
$queryString = "INSERT INTO `{$table}` ({$fieldString}) VALUES {$valueString} ";
//echo $queryString;
try{
$result = mysql_query($queryString);
}catch(Exception $c){
$this->setError($c);
}
}


/*
* Mysql Update
* Params - field->value pair,table name,update condition
*/

function update($options,$table,$condition)
{
$queryString = "";
$fieldString = "";
$p = count($options);
$start = 0;
foreach($options as $key=>$val){
$fieldString.=" `{$key}`='{$val}'";
if($start<$p-1){
$fieldString.=",";
}
$start++;
}
$queryString = "UPDATE `{$table}` SET {$fieldString} ";
if(!empty($condition)){
$queryString.=" WHERE {$condition} ";
}
$this->query = $queryString;
try{
$result = mysql_query($queryString) or $this->setError(mysql_error());
}catch(Exception $c){
$this->setError($c);
}
//echo $this->query." <br/>";
}

/*
* Mysql Delete Operation
* Params - table name , condition
*/

function delete($table,$condition)
{
$queryString = "DELETE FROM `{$table}` ";
if(!empty($condition)){
$queryString.=" WHERE {$condition} ";
}
try{
$result = mysql_query($queryString) or $this->setError(mysql_error());
}catch(Exception $c){
$this->setError($c);
}
}

function execute($query){
$result = mysql_query($query) or $this->setError(mysql_error());
}
/*
* Returns last insert ID
*/

function lastInsertId()
{
return mysql_insert_id();
}

function affectedRows($instance){
return mysql_affected_rows($instance);
}

/*
* Filter with Slash on special chars
*/

function addFilter($string){
//return addslashes($string);
return $string;
}

/*
* Remove added special chars on STring
*/

function removeFilter($string){
return stripslashes($string);
}


function escapeHtml($text){
return strip_tags($text);
}


}

?>
Now i will  explain how it is used:-
@for deleting arecord you have to just call like this
for eg:-
$this->delete('cms_company','`company_id`='.$list[$i]);

@for updating a record you have to just call like this
for eg:
$this->update(array('status'=>'0'),"cms_company",'`company_id`='.$list[$i]);

@for fetching data ,you have to call like this.
for eg:
$query = "SELECT count(c.`company_id`) FROM `cms_company` c WHERE c.`company_id`!=''";
$query.=$qry;
$rec = $this->fetchAll($query);

@for inserting data you have to only do like this
for eg:
$insert = array('company_name'=>$txtTitle,'company_logo'=>$file,'company_banner'=>$file1,'company_address'=>$txtContent,'company_desc'=>$txtdesc,'company_web'=>$web);// array of values in table

$this->insert($insert,'cms_company');



Download PHP-MYSQL Library from here https://github.com/litto/PHP-MYSQL-Library



Simple chat system in php

Everyone is familiar with chats. But when you perform chats in social networking sites did you ever think of creating by ourselfs. here iam publishing a code of a simple chat system using php..... It is a basic chat system which refreshes every minute and u can perform noramal chat...

For this first you have to create a databse with name chat please import the following code to make the database:-
CREATE TABLE IF NOT EXISTS `chat` (
`time` int(11) NOT NULL,
`name` varchar(30) NOT NULL,
`ip` varchar(15) NOT NULL,
`message` varchar(255) NOT NULL,
PRIMARY KEY (`time`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Now you have to create files for the simple chat system.
Below iam providing three files,you can copy paste from here:-

1)chat.php
........................
<html>
<head>
<style>
.message {
overflow:hidden;
width:498px;
margin-bottom:5px;
border:1px solid #999;
}
.messagehead {
overflow:hidden;
background:#FFC;
width:500px;
}
.messagecontent {
overflow:hidden;
width:496px;
}
</style>
</head>

<body style="background:cyan">
<h1> <span style="color:red; float:center">Chat system</span></h1>
<div id="chat" style="width:500px;margin:0 auto;overflow:hidden;">

<div id="messages"></div>

<div id="error" style="width:500px;text-align:center;color:red;"></div>

<div id="write" style="text-align:center;"><textarea id="message" cols="50" rows="5"></textarea><br/>Name:<input type="text" id="name"/><input type="button" value="Send" onClick="send();"/></div>
</div>

<script type="text/javascript">

function showmessages(){

if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();

xmlhttp.open("GET","show-messages.php?" + Math.random(),false);
xmlhttp.send(null);
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET","showmessages.php?" + Math.random(),false);
xmlhttp.send();
}

document.getElementById('messages').innerHTML = xmlhttp.responseText;

setTimeout('showmessages()',30000);
}

showmessages();

function send(){

var sendto = 'send.php?message=' + document.getElementById('message').value + '&name=' + document.getElementById('name').value;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",sendto,false);
xmlhttp.send(null);
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET",sendto,false);
xmlhttp.send();
}
var error = '';

switch(parseInt(xmlhttp.responseText)){
case 1:
error = 'The database is down!';
break;
case 2:
error = 'The database is down!';
break;
case 3:
error = 'Don`t forget the message!';
break;
case 4:
error = 'The message is too long!';
break;
case 5:
error = 'Don`t forget the name!';
break;
case 6:
error = 'The name is too long!';
break;
case 7:
error = 'This name is already used by somebody else!';
break;
case 8:
error = 'The database is down!';
}
if(error == ''){
document.getElementById('error').innerHTML = '';
showmessages();
}
else{
document.getElementById('error').innerHTML = error;
}
}
</script>

</body>
</html>

2)send.php
...................................
<?php

mysql_connect('localhost', 'root', 'dbadmin') or die (1);

mysql_select_db('chat') or die (2);
$message = $_GET['message'];
$name = $_GET['name'];

if(strlen($message) < 1){
echo 3;
}

else if(strlen($message) > 255){
echo 4;
}

else if(strlen($name) < 1){
echo 5;
}

else if(strlen($name) > 29){
echo 6;
}

else if(mysql_num_rows(mysql_query("select * from chat where name = '" . $name . "' and ip != '" . @$REMOTE_ADDR . "'")) != 0){
echo 7;
}

else{

$search = array("<",">","&gt;","&lt;");

mysql_query("insert into chat values ('" . time() . "', '" . str_replace($search,"",$name) . "', '" . @$REMOTE_ADDR . "', '" . str_replace($search,"",$message) . "')") or die(8);
}
?>
3)show-messages.php
........................................
<?php
mysql_connect('localhost', 'root', 'dbadmin') or die (1);

mysql_select_db('chat') or die (2);
if(isset($_GET['message'])){
$message = $_GET['message'];
}
if(isset($_GET['name'])){
$name = $_GET['name'];
}

$result = mysql_query("select * from chat order by time desc limit 0,10");
$messages = array();

while($row = mysql_fetch_array($result)){

$messages[] = "<div class='message'><div class='messagehead'>" . $row['name'] . " - " . date('g:i A M, d Y',$row['time']) . "</div><div class='messagecontent'>" . $row['message'] . "</div></div>";

$old = $row['time'];
}

for($i=count($result);$i>=0;$i--){
echo $messages[$i];
}

mysql_query("delete from chat where time < " . $old);
?>

put all files in a folder now take localhost/foldername/chat.php and enjoy the chat

Generating Thumbnail in cakephp

When you do a website , their may arrive situation where you like to display the thumbnail of the orginal images.Here iam explaining how you can display athumb with the height and width you wanted.
For that please include the ollowing code in a file named ThumbController.php in your /app/controller/ folder
<?php


class ThumbController extends AppController{

public $uses = array('SessionManager','Validator','Captcha');
public $components=array('Session');

function init(){
$this->SessionManager->Session=$this->Session;
}

function index(){

$datas = $query=$this->params->query;
ini_set('memory_limit','64M');
$cacheBaseDir = Configure::read('CacheDir'); //Cache Base Directory//
$mediaBaseDir = Configure::read('MediaDir'); //Media Base Directory//
$site_config['document_root'] = $_SERVER['DOCUMENT_ROOT'];
$site_config['path_thumbnail'] = $cacheBaseDir.'cache/';


$thumb_size = 128;
$thumb_size_x = 0;
$thumb_size_y = 0;
$quality = 80;


if (isset($datas["size"]) && $datas["size"]<>0) {
$thumb_size=intval($datas["size"]);
}
if(isset($datas['sizex'])){
$thumb_size_x =$datas['sizex'];
}
if(isset($datas['sizey'])){
$thumb_size_y =$datas['sizey'];
}

if(isset($datas['file'])){
$file = $datas['file'];
}
$subF='images';
if(isset($datas['t'])){
if($datas['t']=='b'){
$subF = 'banners';
}
if($datas['t']=='v'){
$subF = 'videos';
}
}
$filename = $mediaBaseDir.$datas['file'];
$baseCache = explode("/",$datas['file']);
$cacheName = $baseCache[1];
//$filename = $mediaBaseDir.'projects/project-769ac34a132887725692236433110021180.jpg';

$fileextension=substr($filename, strrpos ($filename, ".") + 1);


$cache_file=$cacheBaseDir.$cacheName;
if ((file_exists($cache_file)) && (@filemtime($cache_file)>@filemtime($filename)))
{
header('Content-type: image/'.$fileextension);
header("Expires: Mon, 26 Jul 2030 05:00:00 GMT");
header('Content-Disposition: inline; filename='.str_replace('/','',md5($filename.$thumb_size.$thumb_size_x.$thumb_size_y.$quality).'.'.$fileextension));
echo (join('', file( $cache_file )));
exit; # no need to create thumbnail - it already exists in the cache
}
# determine php and gd versions
$ver=intval(str_replace(".","",phpversion()));
if ($ver>=430)
{
$gd_version=@gd_info();
}

# define the right function for the right image types
if (!$image_type_arr = @getimagesize($filename))
{


}
$image_type=$image_type_arr[2];

switch ($image_type)
{
case 2: # JPG
if (!$image = @imagecreatefromjpeg ($filename))
{
# not a valid jpeg file
$image = imagecreatefrompng ($image_error);
$file_type="png";
if (file_exists($cache_file))
{
# remove the cached thumbnail
unlink($cache_file);
}
}
break;

case 3: # PNG
if (!$image = @imagecreatefrompng ($filename))
{
# not a valid png file
$image = imagecreatefrompng ($image_error);
$file_type="png";
if (file_exists($cache_file))
{
# remove the cached thumbnail
unlink($cache_file);
}
}
break;

case 1: # GIF
if (!$image = @imagecreatefromgif ($filename))
{
# not a valid gif file
$image = imagecreatefrompng ($image_error);
$file_type="png";
if (file_exists($cache_file))
{
# remove the cached thumbnail
unlink($cache_file);
}
}
break;
default:
$image = imagecreatefrompng($image_error);
break;

}

# define size of original image
$image_width = imagesx($image);
$image_height = imagesy($image);

# define size of the thumbnail
if (@$thumb_size_x>0)
{
# define images x AND y
$thumb_width = $thumb_size_x;
$factor = $image_width/$thumb_size_x;
$thumb_height = intval($image_height / $factor);
if ($thumb_height>$thumb_size_y)
{
$thumb_height = $thumb_size_y;
$factor = $image_height/$thumb_size_y;
$thumb_width = intval($image_width / $factor);
}
} else {
# define images x OR y
$thumb_width = $thumb_size;
$factor = $image_width/$thumb_size;
$thumb_height = intval($image_height / $factor);
if ($thumb_height>$thumb_size)
{
$thumb_height = $thumb_size;
$factor = $image_height/$thumb_size;
$thumb_width = intval($image_width / $factor);
}
}

# create the thumbnail
if ($image_width < 4000) //no point in resampling images larger than 4000 pixels wide - too much server processing overhead - a resize is more economical
{
if (substr_count(strtolower($gd_version['GD Version']), "2.")>0)
{
//GD 2.0
$thumbnail = ImageCreateTrueColor($thumb_width, $thumb_height);
imagecopyresampled($thumbnail, $image, 0, 0, 0, 0, $thumb_width, $thumb_height, $image_width, $image_height);
} else {
//GD 1.0
$thumbnail = imagecreate($thumb_width, $thumb_height);
imagecopyresized($thumbnail, $image, 0, 0, 0, 0, $thumb_width, $thumb_height, $image_width, $image_height);
}
} else {
if (substr_count(strtolower($gd_version['GD Version']), "2.")>0)
{
# GD 2.0
$thumbnail = ImageCreateTrueColor($thumb_width, $thumb_height);
imagecopyresized($thumbnail, $image, 0, 0, 0, 0, $thumb_width, $thumb_height, $image_width, $image_height);
} else {
# GD 1.0
$thumbnail = imagecreate($thumb_width, $thumb_height);
imagecopyresized($thumbnail, $image, 0, 0, 0, 0, $thumb_width, $thumb_height, $image_width, $image_height);
}
}



switch ($image_type)
{
case 2: # JPG
header('Content-type: image/jpeg');
header('Content-Disposition: inline; filename='.str_replace('/','',md5($filename.$thumb_size.$thumb_size_x.$thumb_size_y.$quality).'.jpeg'));
@imagejpeg($thumbnail,$cache_file, $quality);
imagejpeg($thumbnail,'',$quality);

break;
case 3: # PNG
header('Content-type: image/png');
header('Content-Disposition: inline; filename='.str_replace('/','',md5($filename.$thumb_size.$thumb_size_x.$thumb_size_y.$quality).'.png'));
@imagepng($thumbnail,$cache_file);
imagepng($thumbnail);
break;

case 1: # GIF
if (function_exists('imagegif'))
{
header('Content-type: image/gif');
header('Content-Disposition: inline; filename='.str_replace('/','',md5($filename.$thumb_size.$thumb_size_x.$thumb_size_y.$quality).'.gif'));
@imagegif($thumbnail,$cache_file);
imagegif($thumbnail);
} else {
header('Content-type: image/jpeg');
header('Content-Disposition: inline; filename='.str_replace('/','',md5($filename.$thumb_size.$thumb_size_x.$thumb_size_y.$quality).'.jpg'));
@imagejpeg($thumbnail,$cache_file);
imagejpeg($thumbnail);
}
break;
}

//clear memory
imagedestroy ($image);
imagedestroy ($thumbnail);

die();
//Thumb//
}


}



?>

And for displaying image you have to call like this in the view folder
<img src="<?php echo $urlRoot; ?>thumb/?file=page/imagename" alt="no image" />
no run your code

Sunday, 3 June 2012

Sample project in cakephp

Here iam providing a demo site done in cakephp.This post will be more useful for the php newbies. Here iam explaining a project called inventory system. The main logic is simply adding some items and displaying them. By viewing this project you can certainly get some idea about adding,editing in cakephp.ok

so first prepare database:-

--
-- Table structure for table `db_stocks`
--

CREATE TABLE IF NOT EXISTS `db_stocks` (
  `stock_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `productname` varchar(500) DEFAULT NULL,
  `price` int(120) DEFAULT NULL,
  `quantity` varchar(500) DEFAULT NULL,
  `date` date DEFAULT NULL,
  PRIMARY KEY (`stock_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;


now iam explaining this project in the view that users would have a basic understanding about cakephp.

.so configure your database first.
then add a file named index.ctp and copy following code in it:-

<?php  
 $urlRoot=Router::url('/',false);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- include css and js files here -->
</head>

<body>
    <div id="container">
    <div class="headerC">
        <div class="main-headerC">
            <div class="logoC"></div>
                <div class="admin-title"></div>
                <div class="menuC">
                <ul id="menu">
                       
                    </ul>
                </div>
            </div>
        </div>
    <?php echo $content_for_layout;?>
    <div class="footerC">
            <div class="footer">
                Copy Right &copy;    All Rights Reserved.
            </div>
        </div>
    and put this file under app/view/layout folder ..




 then add controller codes specifying under in your controller folder:-
@ create a file named StocksController.php in your /app/controller folder and paste this code their:-
    <?php  
    class StocksController extends AppController   {  
var $uses = array('Stock');  
        function index()  
        { 
            $this->layout="index";
        $stk=$this->Stock->getallstock();
              $this->set('Stocks',$stk);
        }  
    function view()    
        {   
            $this->layout="index";
            $id=$_GET['id'];
            $stockdetails=$this->Stock->getstockdetails($id);
            $this->set('data', $stockdetails);    
        }  
function add()
{
   $this->layout="index"; 
   $data=$this->data;
    if(isset($data['submit'])){
        $productname=trim(strip_tags($data['productname']));
        $price=trim(strip_tags($data['price']));
         $quantity=trim(strip_tags($data['quantity']));
         $date=date('Y-m-d');
          $save['Stock']=array('productname'=>$productname,'price'=>$price,'quantity'=>$quantity,'date'=>$date);
       $this->Stock->save($save);
$this->redirect('/stocks/index');
    }    
}


function edit()    
{    
    $this->layout="index";
    $id=$_GET['id'];
     $stockdetails=$this->Stock->getstockdetails($id);
    $this->set('data', $stockdetails);
    $this->set('id',$id);
    $data=$this->data;
    if(isset($data['submit'])){
      

        $id=$data['id'];
        $productname=trim(strip_tags($data['productname']));
        $price=trim(strip_tags($data['price']));
         $quantity=trim(strip_tags($data['quantity']));
          $save['Stock']=array('productname'=>$productname,'price'=>$price,'quantity'=>$quantity);
       $this->Stock->id=$id;
       $this->Stock->save($save);
$this->redirect('/stocks/index');
    }    

}  
function delete()    
    {   
$this->layout="index";
    $id=$_GET['id'];
    $this->Stock->deleteall($id);
        $this->redirect('/stocks/index'); 
       
    }  

 }  
    ?>  
@ create a file named PagesController.php in your /app/controller folder and paste this code their:-
<?php
/**
 * Static content controller.
 *
 * This file will render views from views/pages/
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('AppController', 'Controller');

/**
 * Static content controller
 *
 * Override this controller by placing a copy in controllers directory of an application
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers/pages-controller.html
 */
class PagesController extends AppController {

/**
 * Controller name
 *
 * @var string
 */
public $name = 'Pages';

/**
 * Default helper
 *
 * @var array
 */
public $helpers = array('Html', 'Session');

/**
 * This controller does not use a model
 *
 * @var array
 */
public $uses = array();

/**
 * Displays a view
 *
 * @param mixed What page to display
 * @return void
 */
public function display() {
$path = func_get_args();

$count = count($path);
if (!$count) {
$this->redirect('/');
}
$page = $subpage = $title_for_layout = null;

if (!empty($path[0])) {
$page = $path[0];
}
if (!empty($path[1])) {
$subpage = $path[1];
}
if (!empty($path[$count - 1])) {
$title_for_layout = Inflector::humanize($path[$count - 1]);
}
$this->set(compact('page', 'subpage', 'title_for_layout'));
$this->render(implode('/', $path));
}
}
so after that it is time to create view files:-
just add some files as mentioned below:-
@create  index.ctp file in /app/view/Stocks folder and paste code like this:-
 <?php  
$urlRoot=Router::url('/',false);
?>
  <h1 align="center">Inventory</h1>  
  <h4 align="center">
    <a href="<?php echo $urlRoot; ?>Stocks/add" ><span style="color:black; background:grey;"> Add new products </span></a>

  </h4>
    <table border="1" background="green" cellpadding="1" cellspacing="2" align="center">  
        <tr>  
            <th>StockID</th>  
            <th>ProductName</th>  
            <th>Price</th>
   <th>Quantity</th>
   <th>Date</th>  
        </tr>  
        <?php 
for($i=0;$i<count($Stocks);$i++){
?><tr>  
            <td><?php echo $Stocks[$i]['Stock']['stock_id']; ?></td>  
            <td><?php echo $Stocks[$i]['Stock']['productname']; ?></td> 
            <td><?php echo $Stocks[$i]['Stock']['price']; ?></td>  
            <td><?php echo $Stocks[$i]['Stock']['quantity']; ?></td>  
              <td><?php echo $Stocks[$i]['Stock']['date']; ?></td>   
            <td>  
<a href="<?php echo $urlRoot; ?>Stocks/view/?id=<?php echo $Stocks[$i]['Stock']['stock_id'];   ?>"> View</a>
            </td>
            <td><a href="<?php echo $urlRoot; ?>Stocks/edit/?id=<?php echo $Stocks[$i]['Stock']['stock_id'];   ?>"> Edit</a>
            </td>
      <td>   
     <td><a href="<?php echo $urlRoot; ?>Stocks/delete/?id=<?php echo $Stocks[$i]['Stock']['stock_id'];   ?>"> Delete</a>
            </td>
        </td>    
            
          
      </tr>  
  <?php  } ?>
    </table>  
@create  add.ctp file in /app/view/Stocks folder and paste code like this:-
<?php  
$urlRoot=Router::url('/',false);
?>
<h1 align="center">Add inventory</h1>    
<form action="<?php echo $urlRoot;?>Stocks/add/" method="post" name="addform">    
   
    <table border="1" background="green" cellpadding="1" cellspacing="2" align="center">  
    <tr><td>Product name: </td><td>    
            <input type="text" name="productname" />   
        </td></tr>    
       <tr><td>Price: </td><td>      
           <input type="text" name="price"/>     
        </td></tr>    
   <tr><td>Quantity </td><td> 
     
    <input type="text" name="quantity" />   
  </td></tr>
        <tr><td></td><td> 
            <input type="submit" name="submit" value="submit"/>   
        </td></tr>    
    </form>      
@create  edit.ctp file in /app/view/Stocks folder and paste code like this:-
<?php  
$urlRoot=Router::url('/',false);
?>
<h1 align="center">Edit Note</h1>    
<form action="<?php echo $urlRoot;?>Stocks/edit/?id=<?php echo $id; ?>" method="post" name="edit form">    
   <input type="hidden" name="id" value="<?php echo $id;  ?>"/>   
   <table border="1" background="green" cellpadding="1" cellspacing="2" align="center">  
    <tr><td>Product name: </td><td>    
            <input type="text" name="productname" value="<?php echo $data[0]['Stock']['productname']; ?>"/>   
        </td></tr>    
       <tr><td>Price: </td><td>      
           <input type="text" name="price" value="<?php echo $data[0]['Stock']['price']; ?>"/>     
        </td></tr>    
<tr><td>Quantity </td><td> 
  
 <input type="text" name="quantity" value="<?php echo $data[0]['Stock']['quantity']; ?>"/>   
</td></tr>
        <tr><td></td><td> 
            <input type="submit" name="submit" value="submit"/>   
        </td></tr>    
    </form>      
   @create  view.ctp file in /app/view/Stocks folder and paste code like this:- 
     <?php  
$urlRoot=Router::url('/',false);
?>
    <h1 align="center"><?php echo $data[0]['Stock']['productname']?></h1> 
     <table border="1" background="green" cellpadding="1" cellspacing="2" align="center">     
    <tr><td>Price: </td><td> <?php echo $data[0]['Stock']['price']?></td></tr>
     <tr><td>Date: </td><td>   <?php echo $data[0]['Stock']['date']?></td></tr>
   <tr><td>Quantity: </td><td>  <?php echo $data[0]['Stock']['quantity']?></td></tr>
     
<tr><td> </td><td> <a href="<?php echo $urlRoot; ?>Stocks/index/"> <span style="color:black; background:grey;">Back to index</span></a></td></tr>
<tr><td> </td><td> <a href="<?php echo $urlRoot; ?>Stocks/edit/?id=<?php echo $data[0]['Stock']['stock_id'];   ?>"> <span style="color:black; background:grey;">Edit</span></a></td></tr>

 Now its time to create model:-
Stock.php in /app/Model/
<?php  
class Stock extends AppModel  {
      public $name        =   'Stock';
    public $useTable    =   'stocks';
    public $primaryKey  =   'stock_id';


function add()
{
    if (!empty($this->data))
    {
        if ($this->Stock->Save($this->data))
        {
            ($this->flash('Your Inventory has been added!', '/Stocks/'));
        }
        else {
            debug($this->Stock->validationErrors);
        }
    }
}
function getallstock(){
        
        
        $rec    =   $this->find('all',array('conditions'=>array('Stock.stock_id !=""')));
        return $rec;
    }
    function getstockdetails($id){
        
        $rec    = $this->find('all',array('conditions' => array('Stock.stock_id !="" ','Stock.stock_id' =>$id)));
        return $rec;
    }
    function deleteall($id)
    {
        $this->delete($id=$id, $cascade=false);
    }
}
?>
now run your code......

Download Project From Here:- https://github.com/litto/Cakephp-CRUD-Sample-Project
   




Easy way to hack in a website

If you want to autopost in a website without wasting time to visit that page and filling forms manually, you can do it simply by php curl function.. for this you have to know the html code of that registration page you want to fill. for eg:
<form id="RegisterForm" class="styled" action="registerme.asp" method="post">
<fieldset>
<ol>
<li class="form-row">
<label>Title:</label>
<input style="width:50px" name="txtTitle" type="text" class="required"/>
</li>
<li class="form-row">
<label>First name:</label>
<input style="width:100px" name="txtFirstName" type="text" class="required"/>
</li>

<li class="form-row">
<label>Email:</label>
<input style="width:300px" name="txtEmail" type="text" class="required email"/>
</li>
<li class="form-row">
<label>Password:</label>
<input name="txtPassword" type="password" class="required password"/>
<br/>Password must be alpha-numeric with between 6 and 15 characters
</li>
</ol>
</fieldset>
<input type="submit" value="Register" class="submit background_lightest colour_darkest" name="submitbtn"  />
Here is the code to autopost:-
Here you have to specify the url in which you want to autopost. in the above html code you know that the form action is going to http://sitename/registerme.asp
from the code
<form id="RegisterForm" class="styled" action="registerme.asp" method="post">
so we specify url as http://sitename/registerme.asp
next we have to find the field names:- and looking from the above site we know that field names are:-
# txtTitle
#txtFirstName
#txtEmail
#txtPassword

and also in submit action maybe the the programmer checks the submit button is set or not. so we have to asign submit button name to true. also while doing this you should note whether any hidden values are passed in the form.if any hidden values are passed,don't forget to pass that values in your code.
so provide values to these variables in the field string. so final code is:-


<?php
set_time_limit(0);
$user = "Your title";
$d = "true";

$auth = "Name";
$email="name@gmail.com";
$pass="243434gh";// anything you like

$user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/2.0.0.9";

$fields = array(
            'txtTitle'=>$user,'txtFirstName'=>$auth,'txtEmail'=>$email,'txtPassword'=>$pass,'submitbtn'=>"true"
        );

$fields_string='';
foreach($fields as $key=>$value) {
$fields_string .= $key.'='.$value.'&';
}

define("COOKIE_FILE", "c:\cookie.txt");

$url='http://www.sitename/registarationpage';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);   //
curl_setopt($ch,CURLOPT_MAXREDIRS,2); //
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_USERAGENT,$user_agent);
curl_setopt($ch,CURLOPT_REFERER,'http://google.com');
curl_setopt($ch,CURLOPT_HEADER,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
$result = curl_exec($ch);
curl_setopt($ch,CURLOPT_POST,0);
print_r(curl_getinfo($ch));
$d=curl_getinfo($ch);
echo "haai";
print_r(curl_error($ch));
   echo $curl_errno = curl_errno($ch);
echo"lool";

if ($curl_errno > 0) {
                echo "cURL Error ($curl_errno): $curl_error\n";
        } else {
echo $result;
}

?>