Thursday, June 28, 2007

PHP-Convert any HTML file into PDF

############################################################################
Function to Convert any HTML file into PDF
Can save into a pdf file on server, or stream to the user's browser
If you want to stream to the browser: $objClass->fnURL2PDF("http://www.yahoo.com", "pdf.pdf");
If you want to save on the server: $objClass->fnURL2PDF("http://www.yahoo.com", "", "../folder/filename.pdf");
Usage: $objClass->fnURL2PDF("http://www.yahoo.com", "pdf.pdf"); Default is USA
############################################################################
function fnURL2PDF($varURL, $varFileName = "pdf.pdf", $varSavePath = "")
{
$varSocket = fsockopen("www.easysw.com", 80, $errno, $errstr, 1000);
if (!$varSocket) die("$errstr ($errno)\n");

fwrite($varSocket, "GET /htmldoc/pdf-o-matic.php?URL=" . $varURL . "&FORMAT=.pdf HTTP/1.0\r\n");
fwrite($varSocket, "Host: www.easysw.com\r\n");
fwrite($varSocket, "Referer: http://www.easysw.com/htmldoc/pdf-o-matic.php\r\n");
fwrite($varSocket, "\r\n");

$varHeaders = "";
while ($varStr = trim(fgets($varSocket, 4096)))
$varHeaders .= "$varStr\n";

$varBody = "";
while (!feof($varSocket))
$varBody .= fgets($varSocket, 4096);

if ($varSavePath != '')
{
// Save the File
$varFileHandle = @fopen($varSavePath,'w');
$varBytes = @fwrite($varFileHandle, $varBody);
}
else
{
//Download file
if(isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']) and strpos($HTTP_SERVER_VARS['HTTP_USER_AGENT'],'MSIE'))
Header('Content-Type: application/force-download');
else
Header('Content-Type: application/octet-stream');
if(headers_sent())
die('Some data has already been output to browser, can\'t send PDF file');
Header('Content-Length: '.strlen($varBody));
Header('Content-disposition: attachment; filename='.$varFileName);
echo $varBody;
}
return(true);
}


Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

PHP-Get a Value from XML Settings file

############################################################################
Function to Get a Value from XML Settings file provided as a second argument
Default is ../main/settings.xml: standard for all of our current projects
Usage: $objClass->fnGetProperty("SiteURL", "settings.xml");
############################################################################
function fnGetProperty($varPropName, $varXMLFile = '../main/settings.xml')
{
$objXML = new clsXML($varXMLFile);
$varValue = $objXML->evaluate("//" . $varPropName);
$varRetValue = $objXML->get_content($varValue[0]);
$objXML = NULL;
return($varRetValue);
}

Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

PHP-Generate Random Password

############################################################
Function to Generate Random Password of length n, Default = 6 characters
Usage: $objClass->fnRandomPasswordGenerator(16);
###########################################################
function fnRandomPasswordGenerator($length = 6)
{
$pass = '';
$new = '';

// all the chars we want to use
$all = explode(" ",
"a b c d e f g h i j k l m n o p q r s t u v w x y z "
."A B C D E F G H I J K L M N O P Q R S T U V W X Y Z "
."0 1 2 3 4 5 6 7 8 9");

for($i=0; $i < $length; $i++)
{
srand((double)microtime()*1000000);
$pass .= $all[rand(0,61)];
$arr[] = $all[rand(0,61)];
$new .= $arr[$i];
}

return $new;
}

Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

PHP- File Attachment

$fileatt = "file.txt"; // Path to the file
$fileatt_type = "application/octet-stream"; // File Type
$fileatt_name = "Report"; // Filename that will be used for the file as the attachment

$email_from = "test@hotmail.com"; // Who the email is from
$email_subject = "attachment"; // The Subject of the email
$email_txt = "attachment"; // Message that the email has in it

$email_to = "test@hotmail.com"; // Who the email is too

$headers = "From: ".$email_from;

$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);

$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";

$email_message .= "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$email_message . "\n\n";

$data = chunk_split(base64_encode($data));

$email_message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";

$ok = @mail($email_to, $email_subject, $email_message, $headers);

if($ok) {
echo "The file was successfully sent!";
} else {
die("Sorry but the email could not be sent. Please go back and try again!");
}
?>

Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

PHP- Calculate Elapsed time (in seconds!)

function calcElapsedTime($time)
{

$diff = time()-$time;
$yearsDiff = floor($diff/60/60/24/365);
$diff -= $yearsDiff*60*60*24*365;
$monthsDiff = floor($diff/60/60/24/30);
$diff -= $monthsDiff*60*60*24*30;
$weeksDiff = floor($diff/60/60/24/7);
$diff -= $weeksDiff*60*60*24*7;
$daysDiff = floor($diff/60/60/24);
$diff -= $daysDiff*60*60*24;
$hrsDiff = floor($diff/60/60);
$diff -= $hrsDiff*60*60;
$minsDiff = floor($diff/60);
$diff -= $minsDiff*60;
$secsDiff = $diff;
return (''.$yearsDiff.' year'.(($yearsDiff <> 1) ? "s" : "").', '.$monthsDiff.' month'.(($monthsDiff <> 1) ? "s" : "").', '.$weeksDiff.' week'.(($weeksDiff <> 1) ? "s" : "").', '.$daysDiff.' day'.(($daysDiff <> 1) ? "s" : "").', '.$hrsDiff.' hour'.(($hrsDiff <> 1) ? "s" : "").', '.$minsDiff.' minute'.(($minsDiff <> 1) ? "s" : "").', '.$secsDiff.' second'.(($secsDiff <> 1) ? "s" : "").'');
}

Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

PHP- Read contents of a text file

#############################################################################
# Function to Read contents of a text file
# Usage: $objClass->fnReadFromFile('filename.txt');# ############################################################################
function fnReadFromFile($sFileName)
{
$sReturn = '';
$fHandle = fopen($sFileName, "r");
while (!feof($fHandle))
$sReturn .= fread($fHandle, 4096);
fclose($fHandle);
return($sReturn);
}

Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

PHP-A Unique session id


function MakeSessionId() {
$day = date('d', time());
$month = date('m', time());
$year = date('Y', time());
$hour = date('H', time());
$min = date('i', time());
$sec = date('s', time());

return sprintf("%02d%04d%02d-%02d%02d%04d-%04d-%02d%04d", $sec, rand(0, 9999),
$hour, $month, $min, rand(0, 9999), rand(0, 9999), $day, $year);
}

?>

Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

Wednesday, May 30, 2007

PHP- Upload and convert avi, wmv, mov and mpg videos to FLV

Upload and convert avi, wmv, mov and mpg videos to FLV using PHP

1.First you have to create a page from where the user will upload a video lets
call it uploadvideo.php.

follow the code below..


<form name=”frm” action=”uploadvideopro.php” method
=”post” enctype="multipart/form-data" >

<input name="x_URL" type="file" class="form1"
size="26">

<input type="submit" name="submit" value="upload"
>

</form>




2.Secondly on the process page i.e. uploadvideopro.php . follow the following
code..




/***************Load FFMPEG *********************************/



$extension = "ffmpeg";

$extension_soname = $extension . "." . PHP_SHLIB_SUFFIX;

$extension_fullname = PHP_EXTENSION_DIR . "/" . $extension_soname;





// load extension

if (!extension_loaded($extension)) {

dl($extension_soname) or die("Can't load extension $extension_fullname\n");

}



/***********************************************************/




/*****************Get the path to Extention ****************/



$array_path = explode("/",$_SERVER['SCRIPT_FILENAME']);

$dynamic_path = "";

for ($i=0;$i<sizeof($array_path)-1;$i++)

if($array_path[$i]!="")

$dynamic_path =$dynamic_path."/".$array_path[$i];


/**********************************************************/



/******************set folders*****************************/

$flvpath = "flvfiles/";

$moviepath = "movies/" ;

chmod($moviepath,0777);

chmod($flvpath,0777);

/*********************************************************/



/******************Upload and convert video *****************************/




if(isset($_FILES["x_URL"]))

{

$fileName = $_FILES["x_URL"]["name"];

$fileNameParts = explode( ".", $fileName );

$fileExtension = end( $fileNameParts );

$fileExtension = strtolower( $fileExtension );


if($fileExtension=="avi" || $fileExtension=="wmv" || $fileExtension=="mpeg"
|| $fileExtension=="mpg" || $fileExtension=="mov" )

{

if ( move_uploaded_file($_FILES["x_URL"]["tmp_name"],$ moviepath.$_FILES["x_URL"]["name"])
)

{




if( $fileExtension == "wmv" ) {


exec("ffmpeg -i ".$dynamic_path."/".$ moviepath."".$fileName."
-sameq -acodec mp3 -ar 22050 -ab 32 -f flv -s 320x240 ".$dynamic_path."/".$flvpath."myflv.flv");

}


if( $fileExtension == "avi" || $fileExtension=="mpg" ||
$fileExtension=="mpeg" || $fileExtension=="mov" ) {


exec("ffmpeg -i ".$dynamic_path."/".$ moviepath."".$fileName."
-sameq -acodec mp3 -ar 22050 -ab 32 -f flv -s 320x240 ".$dynamic_path."/".$flvpath."myflv.flv");

}


/******************create thumbnail***************/

exec("ffmpeg -y -i ".$dynamic_path."/".$moviepath."".$fileName."
-vframes 1 -ss 00:00:03 -an -vcodec png -f rawvideo -s 110x90 ".$dynamic_path."/".$flvpath."myflv.png");



}

else

{

die("The file was not uploaded");

}


}



else

{

die("Please upload file only with avi, wmv, mov or mpg extension!");

}

}

else

{

die("File not found");

}






Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

Monday, May 28, 2007

PHP-IP Logger

/* SIMPLE IP LOGGER

ok. First off,start off by creating a text file named ip.txt.
Upload that to your server,and CHMOD it to 777.

We did that because that is where the IPS are going to be logged.
We CHMODED it to 777 because thats read,write,and executr persmissions. So that the file is ab;le to write to it.
Now, the actuall PHP script. Make a new document
In it,type this:
*/

$log_file = "ip.txt";
$ip = getenv('REMOTE_ADDR');
$fp = fopen("$log_file", "a");
fputs($fp, "$iprn");
flock($fp, 3);
fclose($fp);
PRINT("Your Ip was logged.....$ip");

/*
Now lets review some of this.
The $logfile is just what is sounds like.
The log file that the IPS will be logged to.
The $ip variable is confusing in this.
It should go like something like $ip = $REMOTE-ADDV.
But in this case it goes like $ip = getenv('REMOTE_ADDR');
Same thing. They both get the USERS IP.

$fp = fopen("$log_file", "a");
fputs($fp, "$iprn");
flock($fp, 3);
fclose($fp);

What that does is write to the script.
$fp= fopen then the log filevariable is to tell the script what it is writing to.


Then ya got PRINT("YOUR IP WAS LOGGED...$IP");
That tells the user there IP was logged,and shows it to them.
Well,there ya have it. A very simple IP logging script.
*/
?>

Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

Friday, May 25, 2007

PHP-Directories filenames to database

// a sinple function to create a database connection
function db_connect() {
$conn = mysql_connect("localhost", "user", "pass");
mysql_select_db("dbname", $conn);
}
// this function will open the chosen directory and returns and array with all filenames
function select_files($dir) {
if (is_dir($dir)) {
if ($handle = opendir($dir)) {
$files = array();
while (false !== ($file = readdir($handle))) {
if (is_file($dir.$file) && $file != basename($_SERVER['PHP_SELF'])) $files[] = $file;
}
closedir($handle);
if (is_array($files)) sort($files);
return $files;
}
}
}
// this function inserts the filename and the modification date of the current file
function insert_record($name, $mod_date) {
$sql = sprintf("INSERT INTO example SET filename = '%s', lastdate = '%s'", $name, $mod_date);
if (mysql_query($sql)) {
return true;
} else {
return false;
}
}
// establish database connection
db_connect();
// enter the table structure if not exists
mysql_query("
CREATE TABLE IF NOT EXISTS example (
id bigint(20) unsigned NOT NULL auto_increment,
filename varchar(255) NOT NULL default '',
lastdate datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (id),
FULLTEXT KEY domain (filename)
) TYPE=MyISAM;");

// creating the current path
$path = dirname(__FILE__);
// the trailing slash for windows or linux
$path .= (substr($path, 0, 1) == "/") ? "/" : "\\";
// get the filenames from the directory
$file_array = select_files($path);
// creating some controle variables and arrays
$num_files = count($file_array);
$success = 0;
$error_array = array();
// if the file array is not empty the loop will start
if ($num_files > 0) {
foreach ($file_array as $val) {
$fdate = date("Y-m-d", filectime($path.$val));
if (insert_record($val, $fdate)) {
$success++;
} else {
$error_array[] = $val;
}
}
echo "Copied ".$success." van ".$num_files." files...";
if (count($error_array) > 0) echo "\n\n
\n".print_r($error_array)."\n
";
} else {
echo "No files or error while opening directory";
}
?>

Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

PHP-Daily (random) banner

mysql_connect("localhost", "user", "password");
mysql_select_db("database_name");
// create table for the banners
mysql_query("
CREATE TABLE IF NOT EXISTS `banners` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(35) NOT NULL default '',
`link` varchar(150) NOT NULL default '',
`alt_title` varchar(100) NOT NULL default '',
`image` varchar(35) NOT NULL default '',
`ins_date` date NOT NULL default '0000-00-00',
`status` enum('on','off') NOT NULL default 'on',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=1");

// create the table for storing todays banner id
mysql_query("
CREATE TABLE `rand_banner` (
`id` int(11) NOT NULL auto_increment,
`date` date NOT NULL default '0000-00-00',
`todays_id` int(11) NOT NULL default '0',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=1");

// first check if todays banner id is already stored
$check_today_sql = "SELECT todays_id FROM rand_banner WHERE date = NOW()";
$check_today_res = mysql_query($check_today_sql);
if (mysql_num_rows($check_today_res) > 0) {
$id_today = mysql_result($check_today_res, 0, "todays_id");
} else {
// if not select a random id and store the id in the table with current date
$get_ids_sql = "SELECT id FROM banners WHERE status = 'on'";
$get_ids_res = mysql_query($get_ids_sql);
$get_ids_array = array();
while ($get_ids = mysql_fetch_object($get_ids_res)) {
$get_ids_array[] = $get_ids->id;
}
$num = count($get_ids_array);
// I use the function rand() because other random functions are not "really random"
$rand_num = rand(0, $num-1);
$id_today = $get_ids_array[$rand_num];
mysql_query("INSERT INTO rand_banner (id, date, todays_id) VALUES (NULL, NOW(), $id_today)");
}
// at least select the record with the todays ID
$result = mysql_query("SELECT link AS url, alt_title, image FROM banners WHERE id = $id_today");
$obj = mysql_fetch_object($result);

// this example will show the current banner
echo "url."\">image."\" alt=\"".$obj->alt_title."\" border=\"0\">";
?>

Disclaimer: Any code or advice
given is for instructional purposes only. We will not be responsible for
any loss or damage caused by using this script.

PHP-Get TemplateMonster data

// For more information: visit http://www.templatemonster.com/webapi/
$num_records = 4;
$aff_link = "http://www.all4yourwebsite.com/";
$tm_url = "http://www.templatemonster.com/";
$tm_url .= "webapi/templates_screenshots4.php";
$param['last_added'] = "Yes"; // this value is case sensitive
$param['full_path'] = "true";
$param['order'] = "asc";
$param['sort_by'] = "date";
$param['filter'] = "1";
// add additional filters / parameters here
// building querystring from the parameters
$qs = "?";
foreach ($param as $key => $val) {
$qs .= $key."=".$val."&";
}
$qs = rtrim($qs, "&");
// now get the records from the TM webapi
$request_from = $tm_url.$qs;
$all_rows = file($request_from);
// now split the data for each row into an multi dim. array
for ($i = 0; $i < $num_records; $i++) {
$data[$i] = explode("\t", $all_rows[$i]);
}
$t_row = "
\n";
foreach ($data as $row) {
// read the information about more attr.
$id = $row[0];
$price = $row[1];
$all_images = explode(",", trim($row[15], "{}"));
$t_row .= "
\n";
$t_row .= "
\n";
foreach ($all_images as $img) {
if (preg_match("/-m.jpg$/", $img)) {
$thumb = $img;
}
}
$thumb_size = getimagesize($thumb);
$t_row .= " ";
$t_row .= "\n";
$t_row .= "
\n";
$t_row .= "
\n";
$t_row .= "

Price: $".$price."

\n";
$t_row .= "
\n";
}
$t_row .= "
";
// How to use? Just "echo $t_row" inside the documents body.
?>

Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

Thursday, May 24, 2007

PHP-Text wrapper plus

function text_wrap($log_text, $limit, $divider=" ") {
$words = explode($divider, $log_text);
$word_count = count($words);
$char_counter = 0;
$block = "";
foreach ($words as $value) {
$chars = strlen($value);
$block .= $value;
$char_counter = $char_counter + $chars;
if ($char_counter >= $limit) {
$block .= " \\n ";
$char_counter = 0;
} else {
$block .= " ";
}
}
return rtrim($block);
} ?>

Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

PHP-URL / domain name splitter

$url_parts = parse_url("http://mail.finalwebsites.co.uk");
$domain = $url_parts['']
$res = mysql_query("SELECT tld FROM domain_info ORDER BY LENGTH(tld) DESC");
// "ORDER BY LENGTH(tld)" will give first the co.uk and then the uk
while ($arr = mysql_fetch_assoc($res)) {
$tmp_tld = substr($domain, -strlen(".".$arr['tld']));
if ($tmp_tld == ".".$arr['tld']) { // You found the tld
$tld = ltrim($arr['tld'], ".");
$domainLeft = substr($domain, 0, -(strlen($tld) + 1)); // It will left the whatever, without the extension and the .
if (strpos($domainLeft, ".") === false) { // It hasn't a subdomain
$subDomain = "";
$finalDomain = $domainLeft;
} else {
$domain_parts = explode(".", $domainLeft);
$finalDomain = array_pop($domain_parts); // select the domain and remove it from the array
$subDomain = implode(".", $domain_parts); // a subdomain can more then one parts seperated with dot's
}
echo "The tld is: ".$tld."
";
echo "the domain name is :".$finalDomain."
";
echo "the subdomain is: ";
echo (!empty($subDomain)) ? $subDomain : "n/a";
echo "
";
break;
}
}
?>

Disclaimer : Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

PHP-Simple attachment mail script

function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use diff. tyoes here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."--";
if (mail($mailto, $subject, "", $header)) {
echo = "mail send ... OK"; // or use booleans here
} else {
echo = "mail send ... ERROR!";
}
}
// how to use
$my_file = "somefile.zip";
$my_path = $_SERVER['DOCUMENT_ROOT']."/your_path_here/";
$my_name = "Olaf Lederer";
$my_mail = "my@mail.com";
$my_replyto = "my_reply_to@mail.net";
$my_subject = "This is a mail with attachment.";
$my_message = "Hallo,\r\ndo you like this script? I hope it will help.\r\n\r\ngr. Olaf";
mail_attachment($my_file, $my_path, "recipient@mail.org", $my_mail, $my_name, $my_replyto, $my_subject, $my_message);
?>

Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

Monday, April 2, 2007

PHP- Client URL Library Function


$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

Friday, March 30, 2007

Javascript-Sorting Dates in List Box

<html>
<head>
<title>Javascript-Sorting Dates in List Box</title>
<script language="JavaScript">
function Sort_Dates() {
var x, y, holder;
var list_box = document.frm.list_dates;

FirstDate = new Date();
SecondDate = new Date();

for(x = 0; x < list_box.options.length; x++)
{
for(y = 0; y < (list_box.options.length-1); y++)
{
array_first = list_box.options[y].value.split("/");
array_second = list_box.options[y+1].value.split("/");

FirstDate.setMonth(array_first[0]);
FirstDate.setDate(array_first[1]);
FirstDate.setYear(array_first[2]);

SecondDate.setMonth(array_second[0]);
SecondDate.setDate(array_second[1]);
SecondDate.setYear(array_second[2]);

if (FirstDate >SecondDate) //here you can modify the condition to work for ascending or descending
{
holder = list_box.options[y+1].value;
list_box.options[y+1].value = list_box.options[y].value;
list_box.options[y+1].text = list_box.options[y].value;
list_box.options[y].value = holder;
list_box.options[y].text = holder;
}
}
}

}
</script>
</head>
<body>
<form name="frm">
<select name="list_dates" id="list_dates" multiple size="10">
<option value="3/31/2007">3/31/2007</option>
<option value="2/15/2007">2/15/2007</option>
<option value="3/25/2007">3/25/2007</option>
<option value="2/6/2007">2/6/2007</option>
</select>
<input type="button" value="Sort Dates" onClick="Sort_Dates();">
</form>
</body>
</html>


Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

PHP-CURL and You

The first step in using CURL is to create a new CURL resource, by calling the curl_init() function, like so:
// create a new curl resource
$ch = curl_init();
?>

Now that you've got a curl resource, it's possible to retrieve a URL, by first setting the URL you want to retrieve using the curl_setopt() function:
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.google.com/");
?>

After that, to get the page, call the curl_exec() which will execute the retrieval, and automatically print the page:
// grab URL and pass it to the browser
curl_exec($ch);
?>

Finally, it's probably wise to close the curl resource to free up system resources. This can be done with the curl_close() function, as follows:
// close curl resource, and free up system resources
curl_close($ch);
?>

That's all there is to it, and the above code snippets together form the following working demo:

// create a new curl resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.google.nl/");

// grab URL and pass it to the browser
curl_exec($ch);

// close curl resource, and free up system resources
curl_close($ch);

?>


The only problem we have now is that the output of the page is immediately printed, but what if we want to use the output in some other way? That's no problem, as there's an option called CURLOPT_RETURNTRANSFER which, when set to TRUE, will make sure the output of the page is returned instead of printed. See the example below:

// create a new curl resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.google.nl/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// grab URL, and return output
$output = curl_exec($ch);

// close curl resource, and free up system resources
curl_close($ch);

// Replace 'Google' with 'PHPit'
$output = str_replace('Google', 'PHPit', $output);

// Print output
echo $output;

?>

Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.