Showing posts with label WEB PROGRAMMING. Show all posts
Showing posts with label WEB PROGRAMMING. Show all posts

Monday, November 12, 2012

PHP Script for Displaying Data in Tables with Color Line Hose-cross...


Wah is quite long too huh title of this article above ... For those of you who are still confused with the above title mean, just look at the picture below alone ... for details.

script php tabel data warna selang-seling


In the picture above you can see that each row of the table alternating color. Alternating colors can be easier for people to look at the data, particularly for distinguishing between lines. Well ... have understood it to mean?

OK ... this article will discuss how to make the display as above, with the data read from the MySQL database. Do not worry ... how to make it pretty easy anyway.

The basic idea creation data table rows with alternating colors is sufficient to use the concept of even and odd numbers. In the example above, the background color to be white lines on the odd lines, namely 1, 3, 5, ... and so on. While the gray lines given in even-numbered lines (2, 4, 6, ... etc.).

In PHP, to determine an even number is to use a modulo operation (%), if the number in modulo 2 result 0, then he is even, while if it is not equal to 0, then the odd.

For example, in this case, suppose we have a table structure


CREATE TABLE mhs (
  nim varchar(10),
  namaMhs varchar(30),
  alamat varchar(30),
  PRIMARY KEY (nim)
)
data OF Mahasiswa Table

INSERT INTO mhs VALUES ('M0197001', 'ROSIHAN ARI YUANA', 'Solo');
INSERT INTO mhs VALUES ('M0197002', 'DWI AMALIA FITRIANI', 'Kudus');
INSERT INTO mhs VALUES ('M0197003', 'FAZA FAUZAN KH.', 'Solo');
INSERT INTO mhs VALUES ('M0197004', 'NADA HASANAH', 'Solo');
INSERT INTO mhs VALUES ('M0197005', 'MUH. AHSANI TAQWIM', 'Solo');
Look this PHP script  below:
<?php

mysql_connect("namaHost","namaUser","password");
mysql_select_db("namaDB");
$warnaGenap = "#CCCCCC";   // warna abu-abu
$warnaGanjil = "#FFFFFF";  // warna putih
$warnaHeading = "#FF0000"; // warna merah untuk heading tabel

$query = "SELECT * FROM mhs";
$hasil = mysql_query($query);

echo "<table border='1'>";
echo "<tr bgcolor='".$warnaHeading."'>
      <td>NIM</td>
      <td>Nama Mahasiswa</td>
      <td>Alamat</td>
      </tr>";

$counter = 1;

while($data = mysql_fetch_array($hasil))
{

// cek apakah counternya ganjil atau genap

if ($counter % 2 == 0) $warna = $warnaGenap;
else $warna = $warnaGanjil;

echo "<tr bgcolor='".$warna."'>";
echo "<td>".$data['nim']."</td>";
echo "<td>".$data['namaMhs']."</td>";
echo "<td>".$data['alamat']."</td>";
echo "</tr>";

$counter++; // menambah counter
}
echo "</table>";

?>


PHP script to create WEB THUMBNAIL /SCREENSHOT


Do you want to make webthumbnail? What's that ya 'WebThumbnail'? Web thumbnail is a kind of image capture screen shots or the result of the appearance of a particular website. Thumbnail Web can actually be made ​​manually but very complicated because you have to open a web site that would captured zoom, then the software you need to capture a particular image zoom, and then save the results captured into an image file. Complicated right? But now you do not need to be complicated anymore, because there is already a PHP script to ease the process of making these thumbnails web.
To create a web thumbnails with PHP script, you do not bother him because it has provided a class that you can use for free or free. Give thanks to Lukasz Cepowski, which has made PHP class for web thumbnail. Feel free to download the script webthumnail.php diwww.phpclasses.org
Script Class webthumbnail made ​​by Lukasz Cepowski utilizes APIs from services webthumbnail.org a site that lets generate a screen shot of a web site.
Once the file has been downloaded webthumbnail.php, then how to use them?
Here is an example script to create web thumbnail or view website capturing and storing the file into a directory capturenya.

capture1.php
<?php
require 'webthumbnail.php';

// path file hasil capture
$path = 'd:/images/thumb.jpg';

$thumb = new Webthumbnail("http://blog.rosihanari.net");
$thumb
    ->setWidth(512)
    ->setHeight(512)
    ->captureToFile($path);

echo "Thumbnail sudah disimpan di ".$path;
?>
Examples of the above script when executed will capture views of the site and then save the file http://blog.rosihanari.net capturenya in d :/ images / thumb.jpg. The results captured image size is 512 x 512 pixels. Anyway, make sure his script webthumbnail.php located in the same folder as the capture1.php.
or you can also view results capturenya image directly into the browser, simply by making the script as follows:

capture2.php
<?php
require 'webthumbnail.php';

$thumb = new Webthumbnail("http://blog.rosihanari.net");
$thumb
    ->setWidth(512)
    ->setHeight(512)
    ->captureToBrowser();
?>
Image types generated from the above script is PNG image.
OK, easy right? good luck with ya ...:

PHP Script Export Data MySQL to Excel Multiple Sheet


For the purposes of export data to multiple excel sheet, I am using Spreadsheet_WriteExcel class that is already available. Please you downloadi class here.
However, unfortunately the manual or instructions for using the class is minimal, so I had to dissect the class for any method or facility that can be used in this class.
In this article, I will try to peel a way to export data in MySQL into Excel file using Spreadsheet_WriteExcel class. For example, suppose we have a student data in MySQL as shown below

Export MySQL ke Excel
Next we want to export student data into Excel file with 2 sheets, the first sheet to display data male students, and the second sheet for female student data, as shown in the second image below.
Export MySQL ke Excel
Export MySQL ke Excel
Here is a PHP script that would generate an Excel file with 2 sheets when the script is executed in the browser.
export.php
<?php
  require_once('Worksheet.php');
  require_once('Workbook.php');

  // koneksi ke mysql
  mysql_connect('dbhost', 'dbuser', 'dbpass');
  mysql_select_db('dbname');

  // function untuk membuat header file excel
  function HeaderingExcel($filename) {
      header("Content-type: application/vnd.ms-excel");
      header("Content-Disposition: attachment; filename=$filename" );
      header("Expires: 0");
      header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
      header("Pragma: public");
      }

  // membuat header file excel dan nama filenya
  HeaderingExcel('mhs.xls');

  // membuat workbook baru
  $workbook = new Workbook("");
  // membuat worksheet ke-1 (data laki-laki)
  $worksheet1 =& $workbook->add_worksheet('Laki-laki');

  // setting format header tabel data
  $format =& $workbook->add_format();
  $format->set_align('vcenter');
  $format->set_align('center');
  $format->set_color('white');
  $format->set_bold();
  $format->set_italic();
  $format->set_pattern();
  $format->set_fg_color('red');

  // membuat header tabel dengan format
  $worksheet1->set_row(0, 15);
  $worksheet1->set_column(0, 0, 10);
  $worksheet1->write_string(0, 0, "NIM", $format);
  $worksheet1->set_column(0, 1, 30);
  $worksheet1->write_string(0, 1, "NAMA", $format);
  $worksheet1->set_column(0, 2, 20);
  $worksheet1->write_string(0, 2, "TINGGI BADAN (cm)", $format);

  // menampilkan data mhasiswa laki-laki

  $query = "SELECT * FROM mhs WHERE jns_kelamin = 'L'";
  $hasil = mysql_query($query);
  $baris = 1;
  while ($data = mysql_fetch_array($hasil))
  {
        $worksheet1->write_string($baris, 0, $data['nim']);
        $worksheet1->write_string($baris, 1, $data['nama']);
        $worksheet1->write_number($baris, 2, $data['tinggi']);
        $baris++;
  }

  // membuat worksheet ke-2 untuk data mhs perempuan
  $worksheet2 =& $workbook->add_worksheet('Perempuan');

  // membuat header tabel
  $worksheet2->set_row(0, 15);
  $worksheet2->set_column(0, 0, 10);
  $worksheet2->write_string(0, 0, "NIM", $format);
  $worksheet2->set_column(0, 1, 30);
  $worksheet2->write_string(0, 1, "NAMA", $format);
  $worksheet2->set_column(0, 2, 20);
  $worksheet2->write_string(0, 2, "TINGGI BADAN (cm)", $format);

  // menampilkan data mhasiswa perempuan

  $query = "SELECT * FROM mhs WHERE jns_kelamin = 'P'";
  $hasil = mysql_query($query);
  $baris = 1;
  while ($data = mysql_fetch_array($hasil))
  {
        $worksheet2->write_string($baris, 0, $data['nim']);
        $worksheet2->write_string($baris, 1, $data['nama']);
        $worksheet2->write_number($baris, 2, $data['tinggi']);
        $baris++;
  }

  $workbook->close();
?>
In the script above, there are a few commands that I need to explain here, namely:
$worksheet1 =& $workbook->add_worksheet('Laki-laki');
The above command is used to create a sheet or a worksheet with the name 'man' (worksheet1). Further orders associated with $ worksheet1 is always preceded by a $ worksheet1-> ... Similarly, when making a second worksheet (worksheet2).
The advantages of this class is able to format the text display and cellnya. In the above example, given the following command:

$format =& $workbook->add_format();
$format->set_align('vcenter');
$format->set_align('center');
$format->set_color('white');
$format->set_bold();
$format->set_italic();
$format->set_pattern();
$format->set_fg_color('red'); 
with the above command, we will make the text formatting properties: bold, italic, red background, centered vertical, horizontal centerd, and the font color white. The format will be given in the header of the cell which is the student data table. For example, suppose we want to format the cell header table 'NAME' with the above property on sheet 2, then the command:
$ worksheet2-> write_string (0, 1, "NAME", $ format);
where the parameter 0 and 1 are the coordinates of his cell.
The method set_row (x, y) is used to set the line width in the column x, y pixel wide. While the method set_column (x, y, z) to set the column width in pixels by z-y column. To write data into a cell, can use the method write_string () or write_number (). The difference between the two is if the method write_string () will be generated string in the cell, whereas write_number () data is written in the form of cell 

Sunday, November 11, 2012

Display Calendar on web pages using PHP and Javascript


Source code is to display the calendar on web pages using PHP and Javascript, PHP With the merger, the time display does not follow
time on the browser client, but following the time available at the current server.




<?
$jan = "Januari";
$feb = "Februari";
$mar = "Maret";
$apr = "April";
$mei = "Mei";
$jun = "Juni";
$jul = "Juli";
$agu = "Agustus";
$sep = "September";
$okt = "Oktober";
$nov = "November";
$des = "Desember";
?>



<div style="width:200px;">

<SCRIPT LANGUAGE="JavaScript">



<!-- Begin
monthnames = new Array(
<?echo("\"{$jan}\"");?>,
<?echo("\"{$feb}\"");?>,
<?echo("\"{$mar}\"");?>,
<?echo("\"{$apr}\"");?>,
<?echo("\"{$mei}\"");?>,
<?echo("\"{$jun}\"");?>,
<?echo("\"{$jul}\"");?>,
<?echo("\"{$agu}\"");?>,
<?echo("\"{$sep}\"");?>,
<?echo("\"{$okt}\"");?>,
<?echo("\"{$nov}\"");?>,
<?echo("\"{$des}\"");?>);
var linkcount=0;
function addlink(month, day, href) {
var entry = new Array(3);
entry[0] = month;
entry[1] = day;
entry[2] = href;
this[linkcount++] = entry;
}
Array.prototype.addlink = addlink;
linkdays = new Array();
monthdays = new Array(12);
monthdays[0]=31;
monthdays[1]=28;
monthdays[2]=31;
monthdays[3]=30;
monthdays[4]=31;
monthdays[5]=30;
monthdays[6]=31;
monthdays[7]=31;
monthdays[8]=30;
monthdays[9]=31;
monthdays[10]=30;
monthdays[11]=31;

<?
$saiki = date("d M Y");
?>;
saiki="<? echo $saiki ?>";

todayDate=new Date(saiki);

thisday=todayDate.getDay();
thismonth=todayDate.getMonth();
thisdate=todayDate.getDate();
thisyear=todayDate.getYear();
thisyear = thisyear % 100;
thisyear = ((thisyear < 50) ? (2000 + thisyear) : (1900 + thisyear));
if (((thisyear % 4 == 0) 
&& !(thisyear % 100 == 0))
||(thisyear % 400 == 0)) monthdays[1]++;
startspaces=thisdate;
while (startspaces > 7) startspaces-=7;
startspaces = thisday - startspaces + 1;
if (startspaces < 0) startspaces+=7;
document.write("<table border=0 cellspacing=1 cellpadding=0 ");
document.write("bordercolor=#666666 width=100%><font color=black>");
document.write("<tr><td colspan=7><center><strong><font size=1>" 
+ monthnames[thismonth] + " " + thisyear 
+ "</font></strong></center></font></td></tr>");
document.write("<tr>");

document.write("<td align=center><font size=1 color=red>M</font></td>");
document.write("<td align=center><font size=1>S</font></td>");
document.write("<td align=center><font size=1>S</font></td>");
document.write("<td align=center><font size=1>R</font></td>");
document.write("<td align=center><font size=1>K</font></td>");
document.write("<td align=center><font size=1 color=green>J</font></td>");
document.write("<td align=center><font size=1>S</font></td>");

document.write("</tr>");
document.write("<tr>");
for (s=0;s<startspaces;s++) {
document.write("<td> </td>");
}
count=1;
while (count <= monthdays[thismonth]) {
for (b = startspaces;b<7;b++) {
linktrue=false;
document.write("<td align=center><font size=1>");
for (c=0;c<linkdays.length;c++) {
if (linkdays[c] != null) {
if ((linkdays[c][0]==thismonth + 1) && (linkdays[c][1]==count)) {
document.write("<a href=\"" + linkdays[c][2] + "\">");
linktrue=true;
    }
    }
}
if (count <= monthdays[thismonth]) {
if (b==0) {
document.write("<font color=red>");}
if (b==5) {
document.write("<font color=green>");}
if (count==thisdate) {
document.write("<font size=2 color=blue><strong>");}

document.write(count);

if (count==thisdate) {
document.write("</strong></font>");}
if (b==0){
document.write("</font>");}
if (b==5){
document.write("</font>");}

}
else {
document.write(" ");
}
if (linktrue)
document.write("</a>");
document.write("</font></td>");
count++;
}
document.write("</tr>");
document.write("<tr>");
startspaces=0;
}
document.write("</table>");
// End -->
</SCRIPT>
</div>

Source Code to Page Forward


<?
/*

* CHANGELOG:
* 01/15/05: PF v1.1-Initial Public Release.
* 10/05/05: PF v1.2-Fixed erratic '302 Moved' errors appearing when certain sites were viewed with the proxy.
* 10/25/05: PF v1.3-Improved CSS2 support; sites like msn.com and urbandictionary.com now work.
*
* README:
* This program is a modified, simplified version of Simple Browser Proxy (located at http://sbp.sf.net.)
* The author of this program felt SBP had a lot of potential but had a few flaws that needed ironing out.
* PF is a PHP program that will let you surf the web through a makeshift proxy (through the web server the
* program runs on) to bypass things like internet filters.
*
* INSTALLATION AND USAGE:
* Change the first two uncommented lines (the ones that start with dollar signs) below this information if
* you need to. Upload this file to a web server running PHP. Make sure the program has proper execute permissions.
* The program is used by going to http://your.webserver.com/PageForward.php?url=x in a browser where x is the
* URL of a site that you wish to view through the proxy. Any links on the original page will be edited and
* 'redirected' through the proxy; things typed in the address bar of your browser will not (unless they appear
* after the 'url='. PageForward will still work if you change the name of the file to something besides
* PageForward.php.
*
* KNOWN BUGS:
* PageForward still has some trouble with CSS as well as forms (anything with text fields and a 'submit' button)
* depending on how some sites are coded--some sites will display/work fine, and others will not. Fixes for these
* issues are planned in a future release.
*
* OTHER INFO:
* This program is released under the GNU Lesser GPL. It is a modified version of Simple Browser Proxy
* (located at http://sbp.sf.net) and I'd like to thank the original author for writing and freely distributing
* SBP and its source code.
*/

//**BEGIN USER CONFIG**
//Page to display by default (if no URL is supplied)
$default_url = "http://www.google.com";
//Tag to prepend page titles
$title_tag = "PF--";
//**END USER CONFIG**

$start_time = microtime();

//Finds the nth position of a string within a string (stolen from http://us3.php.net/strings)
function strnpos($haystack, $needle, $occurance, $pos = 0) {

for ($i = 1; $i <= $occurance; $i++) {
$pos = strpos($haystack, $needle, $pos) + 1;
}
return $pos - 1;
}

//URL parser that works better than PHP's built-in function
function parseURL($url)
{
//protocol(1), auth user(2), auth password(3), hostname(4), path(5), filename(6), file extension(7) and query(8) //
$pattern = "/^(?:(http[s]?):\/\/(?:(.*):(.*)@)?([^\/]+))?((?:[\/])?(?:[^\.]*?)?(?:[\/])?)?(?:([^\/^\.]+)\.([^\?]+))?(?:\?(.+))?$/i";
preg_match($pattern, $url, $matches);

$URI_PARTS["scheme"] = $matches[1];
$URI_PARTS["host"] = $matches[4];
$URI_PARTS["path"] = $matches[5];

return $URI_PARTS;
}

//Turns any local URLs into fully qualified URLs
function completeURLs($HTML, $url)
{
$URI_PARTS = parseURL($url);
$path = trim($URI_PARTS["path"], "/");
$host_url = trim($URI_PARTS["host"], "/");

//$host = $URI_PARTS["scheme"]."://".trim($URI_PARTS["host"], "/")."/".$path; //ORIGINAL
$host = $URI_PARTS["scheme"]."://".$host_url."/".$path."/";
$host_no_path = $URI_PARTS["scheme"]."://".$host_url."/";

//make sure the host doesn't end in '//'
$host = rtrim($host, '/')."/";

//replace '//' with 'http://'
$pattern = "#(?<=\"|'|=)\/\/#"; //the '|=' is experimental as it's probably not necessary
$HTML = preg_replace($pattern, "http://", $HTML);

//matches [src|href|background|action]="/ because in the following pattern the '/' shouldn't stay
$pattern = "#(src|href|background|action)(=\"|='|=(?!'|\"))\/#i";
$HTML = preg_replace($pattern, "\$1\$2".$host_no_path, $HTML);

$pattern = "#(href|src|background|action)(=\"|=(?!'|\")|=')(?!http|ftp|https|\"|'|javascript:|mailto:)#i";
$HTML = preg_replace($pattern, "\$1\$2".$host, $HTML);

//TODO: need to be able to clean off the crap after the action.
$pattern = "#action=(.*?)>#is";
$replace = "action=".$_SERVER['PHP_SELF']."><input type=\"hidden\" name=\"original_url\" value=\"\$1\">";
$HTML = preg_replace($pattern, $replace, $HTML);

//mathces '/[any assortment of chars or nums]/../'
$pattern = "#\/(\w*?)\/\.\.\/(.*?)>#ims";
$replace = "/\$2>";
$HTML = preg_replace($pattern, $replace, $HTML);

//matches '/./'
$pattern = "#\/\.\/(.*?)>#ims";
$replace = "/\$1>";
$HTML = preg_replace($pattern, $replace, $HTML);

//Handle CSS2 imports of CSS files (EXAMPLE: <style type="text/css" media="screen">@import /themes/blue/blue.css";</style>)
if (strpos($HTML, "import url(\"http") == false && (strpos($HTML, "import \"http") == false) && strpos($HTML, "import url(\"www") == false && (strpos($HTML, "import \"www") == false)) {
$pattern = "#import .(.*?).;#ims";
$mainurl = substr($host, 0, strnpos($host, "/", 3));
$replace = "import '".$mainurl."\$1';";
$HTML = preg_replace($pattern, $replace, $HTML);
}
return $HTML;
}

//Redirects link targets through this proxy
function proxyURLs($HTML)
{
$edited_tag = "PF"; //used to check if the link has already been modified by the proxy

//BASE tag needs to be removed for sites like yahoo.com
//OR make the proxy insert the FULL URL to itself
$pattern = "#\<base(.*?)\>#ims";
$replacement = "<!-- <base\$1> -->"; //comment it out for now//
$HTML = preg_replace($pattern, $replacement, $HTML);

//edit <link tags so that 'edited="$edit_tag" ' is just before 'href'
$pattern = "#\<link(.*?)(\shref=)#ims";
$HTML = preg_replace($pattern, "<link\$1 edited=\"".$edited_tag."\"\$2", $HTML);

//matches everything with a </a> after it on the same line....fails to match when that is on another line.
$pattern = "#(?<!edited=\"".$edited_tag."\"\s)(href='|href=\"|href=(?!'|\"))(?=(.+)\</a\>)(?!mailto:|http://ftp|ftp|javascript:|'|\")#ims";
$HTML = preg_replace($pattern, "edited=\"".$edited_tag."\" \$1".$_SERVER['PHP_SELF'].'?url=', $HTML);

return $HTML;
}

//Calculates the differences in microtime captures
function microtime_diff($a, $b)
{

list($a_dec, $a_sec) = explode(" ", $a);
list($b_dec, $b_sec) = explode(" ", $b);

return $b_sec - $a_sec + $b_dec - $a_dec;
}

//Get ready to display data...

$url = $_GET['url'];
if(empty($url)) $url = $default_url;

//Check the URL for protocol, etc....
if(substr($url, 0, 7) != "http://") //didn't start with 'http://'...we have a problem.
{
$url = "http://".$url;
}

//Checks if there was a form redirected to this proxy.
if(!empty($_POST['original_url']))
{
$form_submission = true;
}
else if(!empty($_GET['original_url']))
{
//have to strip off any unwanted stuff from original_url
$url = explode(" ", $_GET['original_url']);
$url = $url[0];

$form_submission = false;
$url = urldecode($url)."?".str_replace("original_url=".urlencode($_GET['original_url'])."&", "", $_SERVER['QUERY_STRING']);
}
if(!$form_submission) //OK, no redirected form so go ahead and fetch a page.
{

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$page = curl_exec($ch);
curl_close($ch);
$HTML = $page;
//$HTML = preg_replace("#\<TITLE\>#i", "<TITLE>".$title_tag, $HTML, 1);
$HTML = preg_replace("#\<(title|TITLE)\>#", "<\$1>".$title_tag, $HTML, 1);
$HTML = completeURLs($HTML, $url); //Complete local links so that they are fully qualified URIs
$HTML = proxyURLs($HTML);  //Complete links so that they pass through this proxy
print_r($HTML); //Output the page using print_r so that frames at least partially are written
flush();

//Calculate execution time and add HTML comment with that info
$duration = microtime_diff($start_time, microtime());
$duration = sprintf("%0.3f", $duration);
echo ("\n<!-- PageForward took $duration seconds to render the page.-->");
}
?>