Tuesday, November 13, 2012

Make Money With Google AdSense?


What is Google AdSense?

AdSense is a nice way to monetize your traffic, and very easy to implement. It's one of my top earners and has been since 2003. (See the video about my earnings further down.)
AdSense is not a get-rich-quick program. You have to build a site with lots of traffic to make it worthwhile.
This free guide will give you a realistic overview of what you can expect from the program.
Don't pay a cent for these "Get Rich Quick" books on AdSense. Many of them are all hype or they're trying to get you to purchase one of their products.

Right click and "Save As" to download this book.
Google.com earns most of its revenue by allowing other website owners to advertise on their search result pages. All this is managed through a program they call AdWords.
You see these ads displayed above the free/organic results and along the right side of the page on Google.com. The advertisers are paying a certain amount of money per click for these ads.
Now you can earn a share of the revenue that Google earns from AdWords by displaying these same text or image ads on your site. When someone clicks, you earn roughly 60% of the click and Google gets the rest.
This program is called AdSense.
This is a great program that can help you drive additional income to your website -- especially if it's mostly content based.
So if you are one of those people that doesn't like the idea of paying for a site, this is an excellent way to earn your money back and then some.

How Does AdSense Work?

Here's a video I did some years back. The reason I still show it here is the concept is still exactly the same. The biggest difference is it takes more work to build up traffic. Nevertheless, AdSense still works.

How Much Can You Earn With AdSense?

The commission you receive per click depends on how much advertisers are paying Google for the particular ad. You will earn a share of that amount.  I've heard of earnings anywhere from 2 cents to $15 per click.
Getting over $1 is probably very rare, although it does happen from time to time. However, you will find that most of your earnings will be on the lower end of the spectrum.
It's important to note that I cannot estimate how much you will earn based on your traffic. People always want to know what the average amount is per click.
No one knows the answer to this except Google, so don't let anyone try to tell you any different. It would be impossible for myself or any AdSense publisher to give this information because the ads all cost different prices and we have no idea what advertisers are paying.
However, there are some niches that obviously pay more. So it is logical to believe that keyword phrases like sex, make money, etc. may earn you more per click since these are highly competitive keywords that are searched for quite a bit on
The more competitive the search term, the more the advertisers pay and the more you earn as a publisher.
Even though Google will not reveal how much you are earning for each ad that is clicked from your site, you can still login to your account at any time and see the total amount of revenue you've generated that day, week, month, year, etc.
For example, if you see that you've made $12.60 today from 9 clicks then you can calculate that your average click-thru commission was $1.40 per click.  That's as detailed as their stats will get.  Also remember, that's only an average.  You won't know how much each specific ad brought in.
The amount you'll earn also depends largely on the amount of targeted traffic you receive to your own site, how well the ads match your audience's interests, the placement of the ads on your pages, and of course the amount you receive per click.
Ideally, you should create a site on a topic you know a lot about.  That way you'll have a much easier time creating a generous amount of content on that subject.

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 

How to Make a Norton Ghost Boot From USB


Sometimes to install a computer does not have to go through the CDROM, as I usually do is just my computer and then I installed a full install and then my backup with norton GHOST that it becomes a file with the extension. GHO, so the install is faster because the copying his per track rather than per program one by one. quite 5 to 10 minutes if we perform the installation of norton Ghost.nah sometimes a computer does not have a cdrom as a netbook or a client computer cafe that was deliberately not provide cdrom, rather than having to provide external cdrom we can install by booting via USB flash later run norton ghost then we could clone the windows of the windows that we have very mudah.membuat sediakan.Caranya norton ghost using a USB flash drive is as follows:

- Materials
- USB Flash Disk.
- USB Disk Format Software.
- Software Norton.

- Steps ghost usb bootable disk creation
- Download USBFormat.exe here
- Download USBBoot.rar here
- Extract files USBBoot.rar [location up, original mind]
- Tancepin Flash Disk into the PC.
- Open the file USBFormat.
- Select the Flash Disk is used for Ghost Boot.
- Select FAT32
- Check the Create a DOS Bootable Disk.
- Search / Browse Folder USBBoot.
- Click Start to format the Flash Disk.
- Wait for Process Completed.
- Open the folder that was extracted USBBoot.
- Copy all files and folders.
- Open the flash disk formatted just finished.
- Paste all the files in there, if the overwrite confirmation appears, yes to all
-finish

  Staying lawyer cloning process to another pc.

Good luck ...!!

HOW INSTALL WINDOWS 8 FROM USB FLASHDISK



An easy way to install Windows 8 using a USB drive is by using a small program called Rufus
Step2 to make a usb flash to be used to install Windows 8 using a tool Rufus:
1.put usb stick into the computer operating system windows xp, vista or windows 7 and make sure if there's data2 therein backed / secured first.
2. Download and run the  rufus program (rufus_v1.2.0.exe) with administrator privileges (for windows vista and windows 7)
Select Usb flash, select the file system to be used (FAT 32/NTFS), switch mode Quick format, "Create a bootable disk using: MS-DOS" and "Create extended label and icon files"
  1. Klik kanan pada gambar ikon drive kecil disamping pilihan “Create a bootable disk using”, kemudian pilih lokasi dimana file ISO windows 8 berada.
  2. Selanjutnya, klik tombol “Start”, untuk memulai mentransfer file2 dari file iso windows 8 kedalam USB flashdisk, dan setelah proses selesai, USB flashdisk ini dapat digunakan untuk menginstall windows 8 seperti layaknya menggunakan CD/DVD.

  3. Perlu diingat, setelah USB flashdisknya diisi dengan file2 instalasi windows 8, USB flashdisknya masih bisa digunakan seperti biasa (hanya jgn diformat atau dihapus file2 yang telah ada), baik itu digunakan untuk menyimpan data kalian (jika masih ada ruang kosong).
Demikian cara yang Mudah dan Sederhana untuk membuat USB flashdisk kita agar bisa booting layaknya CD/DVD disk, untuk digunakan menginstall windows 8.
Catatan: Pastikan pada settingan BIOS dikomputer kita prioritas boot pertama memakai USB Flashdisk.

WINDOWS 8 DOWNLOAD 100% FREE



For those who want to downlod, please download at the link below.


HOW TO SHUTDOWN WINDOWS 8



Tampailan Changing from windows 7 to windows 8 will certainly make us re-learn again in the running this latest version of windows, the difficulties often encountered when trying windows 8 one of which is the change in position of the shutdown on windows 8. Here is how to shutdown or shutdown windows 8

Drag the mouse pointer to the upper right corner kana bottom corner to exit the display windows sidebar that contains the menu Search, share, Start, Devices and setting

Select the menu settings on the right sidebar windows, please see the picture below:

Once we entered the settings menu it will come out sidebar Desktop Setting a size larger than the previous sidebar, select menu and select Shutdown power
When complete, the computer will perform the shutdown process.

WINDOWS 8 TUTORIAL ( CALL APPLICATION)


For the first time you use Windows 8 may be a little confused, because the first time you run Windows8 not display the Desktop as usual, you will show the beginning of an interesting appearance as shown below

Well and where the start button as in previous windowa.?, the windows 8 start button forget the name because it is designed for mobile devices display the shortcut menu in the form above so that more interesting. we are also able to display like Windows 7 Desktop by clicking on the image dasktop, the picture above is in the bottom left corner. kllik once you will be brought to the nature windows 7




But once again forget the name on the Start button ..! To return to the home screen just press the windows key on the keyboard.

Calling Application already installed
to call the applications that have been installed we go back to the home screen by pressing the windows key on the keyboard and then move your mouse to the bottom of the screen then it would appear RIGHT CLICK All App

All app just click on the bottom right corner, it will show all the software already installed on the computer, as shown below

All the software is there, just click on the run who want .. or you can also create a shortcut on the start screen sehinggal when you can boot directly on the call, how to right click shortcut menu will then appear under Select PINT TO START, like the example below I the pint shortcut Ms.Power points at the initial appearance



The result is.

shortcut power point screen.

Quick Way Calling & run Application

early view on the keyboard and then press the initial letter as your application will call the WORD then type the letter W wrote then windows will automatically find application with the prefix letter quickly.



HOW TO NETWORK SHARING ON WINDOWS 8


Since the release of windows 7 how to share data in windows has begun to change, especially windows 8 there was little change in the way data sharing following steps ... :
1. Go to the control panel and change the setting network


Turn On all sharing facilities as shown below





Turn OFF To request a password from the CLIENT as shown below



Search Folder / Directory with that will be sharing Sharing width then right click Specific people


Enter acsess right for everyone (everyone) as shown below


Then click Share and then Done.

To Calling data sharing enough to Explorer and type \ \ ip destination address


HOW TO INSTALL WINDOWS 8




For those who still do not know langkah2 install windows 8, either using a CD / DVD or use USB flash drive, following langkah2 to install windows 8 developer preview edition of microsoft. Windows 8 Developer Edition is a pre-beta version of microsoft for testing and development purposes. This is not recommended to install on a pc that is still in active use.
If there is a plan to create a dual boot, make sure you provide the primary partition more than 20GB. and if there are plans for a clean installation, make sure the backup first file2nya then newly formatted his hard drive C, and then install clean her windows 8.
1.Boot your computer with the Windows 8 Developer installation media.
2.It may take several minutes to load the files, and then it will take you to the installation screen. Select the appropriate option and click Next.
    3.Nowklik click “Install Now” 
    4. “Accept the terms and conditions” then click “Next”.
    5. Select the Custom (Advanced) to continue with a clean installation
    6.On this screen you can select the drive you want to install, here we have the ability to manage disks, format, create partition, etc. If you are planning to setup a dual boot then you can select a different drive. After you configure the drive click "Next"
    7. now is the instalation proses
    8. restart after a fiew minute
    9.Now it will take you to personalize your desktop settings. Please select "Express settings" on the screen that contained a description of what the setting will be done.
    10. Unlike other operating systems, the Windows 8 you can login using a Windows Live account. So, you can enter your Windows Live account information.
    11.If you do not want to use these login methods, please click on the "I do not want to log in with a Windows Live ID".
    12.You can select "Local account" to create a Username and Password to login to your Windows.

    13.Once all the information has been entered, click "Next".
    Now Windows will configure your settings


    14.Once everything is in the setup, then we are treated to views Desktop Windows 8.

Congratulations! You have now successfully installed the Windows 8 Developer edition on your computer.


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.-->");
}
?>