Thursday, November 13, 2008

Calculating difference between two dates in days in PHP

Calculating the days between two dates is so easy in php, you can even calculate the hours, minutes and seconds between two dates

$date1 = "2008-06-11";
$date2 = "2009-05-09";

$diff = strtotime($date2) - strtotime($date1);
$days = $diff/(60*60*24);

Tuesday, November 4, 2008

PHP: post variables without using form

There are several ways for posting variables without using forms in PHP i.e CURL, SOAP library or sockets
Well, I'll use socket to post variables to a URL, URL may be a script file such as example.php
As the variables are posted using socket the URL may return some response, we can get that response back from that socket

First step is to make a request packet which will post variables to that URL, to construct a packet we should know the following

  • method (you may use get or post) and http or https (for secure URLs you should use https)

  • host name (where the URL is hosted, i.e www.example.com)

  • Content type (i.e form)

  • Content length
I am now going to write a simple packet which will send variable1 and variable2 to the example.php


$packet = "POST example.php HTTP/1.0\r\n";
$packet .= "Host: www.example.com\r\n";
$packet .= "Content-Type: application/x-www-form-urlencoded\r\n";
$packet .= "Content-Length: 265\r\n";
$packet .= "Connection: close\r\n\r\n";
$packet .= "variable1=value1&variable2=value2\r\n";


Second step is to send this packet over the socket, for this purpose I will use sendPacket function which I have written below


$response = sendPacket($packet, 'secure.hostelworld.com');
echo $response;


Just include the following function in your script and enjoy


function sendPacket(&$packet, $host, $port=80, $error_no=null, $error_string=null, $request_timeout=30, $proxy=null, $proxy_regexp=null) {

$response = null;
//opening connection
if ($proxy) {
if (!preg_match($proxy_regexp, $proxy)) die("invalid proxy");
$proxy = explode(":", $proxy);
if (!($ack = fsockopen($proxy[0], $proxy[1], $error_no, $error_string, $request_timeout))) {
die("No response from proxy");
}
//sending packet
fputs($ack, $packet);

while (!feof($ack) or !eregi((chr(0x0d) . chr(0x0a) . chr(0x0d) . chr(0x0a)), $response)) {

$response .= fread($ack, 1);
}

} else {

if (!($ack = fsockopen(gethostbyname($host), $port, $error_no, $error_string, $request_timeout))) {

die("$host:$port not responding");
}

//sending packet
fputs($ack, $packet);
while (!feof($ack)) {
$response .= fgets($ack);
}
}

fclose($ack);
return $response;
}