PHP eval equivalent to include

The PHP include statement includes and evaluates a specific file, not what if we want to modify that file first before including, i.e. a version template file.

Well this can be done with PHP eval.

I file is included as follows;

include myfile.php

Using eval, we can achieve the same as above as follows;

$inc = file_get_contents('myfile.php');
eval("?>".$inc);

PHP code to automatically bid/buy an eBay auction item

The following PHP code will automatically bid on an eBay item.

modify the following variables;

  • $username = “username”; //the eBay username
  • $password = “password”; //the eBay password
  • $item = 300712344201; //the item number
  • $bid =  0.01; //the  bid value in the item’s currency
<?php
	//modify the following

	$username = "username"; //the eBay username
	$password = "password"; //the eBay password

	$item = 300712344201; //the item number
	$bid =  0.01; //the  bid value in the item's currency

	//do not modify below

	//query the sign-in page
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20100101 Firefox/15.0.1");
	curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($curl, CURLOPT_COOKIEFILE, "cookies.txt");
	curl_setopt($curl, CURLOPT_COOKIEJAR, "cookies.txt");
	curl_setopt($curl, CURLOPT_URL,"http://signin.ebay.com/aw-cgi/eBayISAPI.dll?SignIn");
	$ret = curl_exec ($curl);
	curl_close ($curl);

	//sign-in
	$post = "MfcISAPICommand=SignInWelcome&siteid=0&co_partnerId=2&UsingSSL=0&ru=&pp=&pa1=&pa2=&pa3=&i1=-1&pageType=-1&userid={$username}&pass={$password}";

	$curl = curl_init();
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20100101 Firefox/15.0.1");
	curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS,$post);
	curl_setopt($curl, CURLOPT_COOKIEFILE, "cookies.txt");
	curl_setopt($curl, CURLOPT_COOKIEJAR, "cookies.txt");
	curl_setopt($curl, CURLOPT_REFERER, "http://signin.ebay.com/aw-cgi/eBayISAPI.dll?SignIn");
	curl_setopt($curl, CURLOPT_URL, "http://signin.ebay.com/aw-cgi/eBayISAPI.dll");
	$ret = curl_exec ($curl);
	curl_close ($curl);

	if (strpos($ret, "Member id {$username}") === FALSE) {
		echo "Failed signing in.\r\n";
	} else {
		echo "Success signing in.\r\n";
	}

	//place the inital bid
	$url = "http://offer.ebay.com/ws/eBayISAPI.dll?MakeBid&item={$item}&maxbid={$bid}";

	$curl = curl_init();
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20100101 Firefox/15.0.1");
	curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($curl, CURLOPT_COOKIEFILE, "cookies.txt");
	curl_setopt($curl, CURLOPT_COOKIEJAR, "cookies.txt");
	curl_setopt($curl, CURLOPT_URL, $url);
	$ret = curl_exec ($curl);
	curl_close ($curl);

	preg_match_all('/(?:value="([-0-9a-zA-Z]*)" *)?name="stok"(?: *value="([-0-9a-zA-Z]*)")?/', $ret, $regs);
	$stok = $regs[1][0];

	preg_match_all('/(?:value="([-0-9a-zA-Z]*)" *)?name="uiid"(?: *value="([-0-9a-zA-Z]*)")?/', $ret, $regs);
	$uiid = $regs[1][0];

	if (($stok) && ($uiid)) {
		echo "Success placing initial bid.\r\n";
	} else {
		echo "Failed placing initial bid.\r\n";
	}

	//confirm the bid
	$url = "http://offer.ebay.com/ws/eBayISAPI.dll?MfcISAPICommand=MakeBid&maxbid={$bid}&quant=1&mode=1&stok={$stok}&uiid={$uiid}&co_partnerid=2&user={$username}&fb=0&item={$item}";

	$curl = curl_init();
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20100101 Firefox/15.0.1");
	curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($curl, CURLOPT_COOKIEFILE, "cookies.txt");
	curl_setopt($curl, CURLOPT_COOKIEJAR, "cookies.txt");
	curl_setopt($curl, CURLOPT_URL, $url);
	$ret = curl_exec ($curl);
	curl_close ($curl);

	if (strpos($ret, "you're the first bidder") === FALSE) {
		echo "Failed placing final bid.\r\n";
	} else {
		echo "Success placing final bid.\r\n";
	}

	//for testing
	//$fh = fopen("testhtml.html", 'w');
	//fwrite($fh, $ret);
	//fclose($fh);
?>

RegexBuddy – a solution to the Regular Expressions (Regex) nightmare

For the last few months I have been using RegexBuddy, software designed to help with Regular Expressions.

After using it to create and test more than one extremely complex regular expression, I thought it was time I gave RegexBuddy some ‘big ups’.

So what is so good about RegexBuddy,

Firstly, it allows you to create regular expressions using layman’s terms, “Non printable character”, “Match between zero and unlimited times”, “Create back-reference”, etc, no longer is there a need to remember the regular expression syntax.

Secondly, I can test my regular expression with extreme ease, I can show the full matched text and any matched groupings.

Thirdly, I can directly translate the regular expression to the programming language of choice, VB, PHP, JavaScript, etc, and not have to worry about the specifics of how to form a regular expression for that specific language.

I use RegexBuddy for PHP and JavaScript, I no longer need to ‘guess’ what the regular expression will be and constantly have to upload my code to the server to try it out.

Here’s an example expression I recently used in my WordPress plugin Slimbox2 Slideshow;

Convert from Google KML to GPS Exchange Format GPX with PHP

Here is a quick post on converting from KML files used in Google Earth/Maps to GPX Exchange Format (GPX) with PHP.

Code is quite explanatory, change $u with the location of the KML file, code will output GPX XML.

Alternatively, download the code here.

<?php
	//enter location of KML file here
	$u = "http://code.google.com/apis/kml/documentation/KML_Samples.kml";
	
	
	function utcdate() {
		return gmdate("Y-m-d\Th:i:s\Z");
	}

	
	$u_parts = pathinfo($u); //array of url parts
	$u_ext = strtoupper($u_parts['extension']);
	if ($u_ext== "KML") {

		$dom_kml = new DOMDocument();
		$dom_kml->load($u);

		$dom_gpx = new DOMDocument('1.0', 'UTF-8');
		$dom_gpx->formatOutput = true;
		
		//root node
		$gpx = $dom_gpx->createElement('gpx');
		$gpx = $dom_gpx->appendChild($gpx);
		
		$gpx_version = $dom_gpx->createAttribute('version');
		$gpx->appendChild($gpx_version);
		$gpx_version_text = $dom_gpx->createTextNode('1.0');
		$gpx_version->appendChild($gpx_version_text);
		
		$gpx_creator = $dom_gpx->createAttribute('creator');
		$gpx->appendChild($gpx_creator);
		$gpx_creator_text = $dom_gpx->createTextNode('http://thydzik.com');
		$gpx_creator->appendChild($gpx_creator_text);
		
		$gpx_xmlns_xsi = $dom_gpx->createAttribute('xmlns:xsi');
		$gpx->appendChild($gpx_xmlns_xsi);
		$gpx_xmlns_xsi_text = $dom_gpx->createTextNode('http://www.w3.org/2001/XMLSchema-instance');
		$gpx_xmlns_xsi->appendChild($gpx_xmlns_xsi_text);
		
		$gpx_xmlns = $dom_gpx->createAttribute('xmlns');
		$gpx->appendChild($gpx_xmlns);
		$gpx_xmlns_text = $dom_gpx->createTextNode('http://www.topografix.com/GPX/1/0');
		$gpx_xmlns->appendChild($gpx_xmlns_text);
		
		$gpx_xsi_schemaLocation = $dom_gpx->createAttribute('xsi:schemaLocation');
		$gpx->appendChild($gpx_xsi_schemaLocation);
		$gpx_xsi_schemaLocation_text = $dom_gpx->createTextNode('http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd');
		$gpx_xsi_schemaLocation->appendChild($gpx_xsi_schemaLocation_text);
		
		$gpx_url = $dom_gpx->createElement('url');
		$gpx_url = $gpx->appendChild($gpx_url);
		$gpx_url_text = $dom_gpx->createTextNode($u_parts['dirname']);
		$gpx_url->appendChild($gpx_url_text);
		
		$gpx_time = $dom_gpx->createElement('time');
		$gpx_time = $gpx->appendChild($gpx_time);
		$gpx_time_text = $dom_gpx->createTextNode(utcdate());
		$gpx_time->appendChild($gpx_time_text);
		
		// placemarks
		$names = array();
		foreach ($dom_kml->getElementsByTagName('Placemark') as $placemark) {
			//name
			foreach ($placemark->getElementsByTagName('name') as $name) {
				$name  = $name->nodeValue;
				//check if the key exists
				if (array_key_exists($name, $names)) {
					//increment the value
					++$names[$name];
					$name = $name." ({$names[$name]})";
				} else {
					$names[$name] = 0;
				}
			}
			//description
			foreach ($placemark->getElementsByTagName('description') as $description) {
				$description  = $description->nodeValue;
			}
			foreach ($placemark->getElementsByTagName('Point') as $point) {
				foreach ($point->getElementsByTagName('coordinates') as $coordinates) {
					//add the marker
					$coordinate = $coordinates->nodeValue;
					$coordinate = str_replace(" ", "", $coordinate);//trim white space
					$latlng = explode(",", $coordinate);
					
					if (($lat = $latlng[1]) && ($lng = $latlng[0])) {
						$gpx_wpt = $dom_gpx->createElement('wpt');
						$gpx_wpt = $gpx->appendChild($gpx_wpt);

						$gpx_wpt_lat = $dom_gpx->createAttribute('lat');
						$gpx_wpt->appendChild($gpx_wpt_lat);
						$gpx_wpt_lat_text = $dom_gpx->createTextNode($lat);
						$gpx_wpt_lat->appendChild($gpx_wpt_lat_text);
						
						$gpx_wpt_lon = $dom_gpx->createAttribute('lon');
						$gpx_wpt->appendChild($gpx_wpt_lon);
						$gpx_wpt_lon_text = $dom_gpx->createTextNode($lng);
						$gpx_wpt_lon->appendChild($gpx_wpt_lon_text);
						
						$gpx_time = $dom_gpx->createElement('time');
						$gpx_time = $gpx_wpt->appendChild($gpx_time);
						$gpx_time_text = $dom_gpx->createTextNode(utcdate());
						$gpx_time->appendChild($gpx_time_text);
						
						$gpx_name = $dom_gpx->createElement('name');
						$gpx_name = $gpx_wpt->appendChild($gpx_name);
						$gpx_name_text = $dom_gpx->createTextNode($name);
						$gpx_name->appendChild($gpx_name_text);
						
						$gpx_desc = $dom_gpx->createElement('desc');
						$gpx_desc = $gpx_wpt->appendChild($gpx_desc);
						$gpx_desc_text = $dom_gpx->createTextNode($description);
						$gpx_desc->appendChild($gpx_desc_text);
						
						//$gpx_url = $dom_gpx->createElement('url');
						//$gpx_url = $gpx_wpt->appendChild($gpx_url);
						//$gpx_url_text = $dom_gpx->createTextNode($ref);
						//$gpx_url->appendChild($gpx_url_text);
						
						$gpx_sym = $dom_gpx->createElement('sym');
						$gpx_sym = $gpx_wpt->appendChild($gpx_sym);
						$gpx_sym_text = $dom_gpx->createTextNode('Waypoint');
						$gpx_sym->appendChild($gpx_sym_text);
					}
				}
			}
			foreach ($placemark->getElementsByTagName('LineString') as $lineString) {
				foreach ($lineString->getElementsByTagName('coordinates') as $coordinates) {
					//add the new track
					$gpx_trk = $dom_gpx->createElement('trk');
					$gpx_trk = $gpx->appendChild($gpx_trk);
					
					$gpx_name = $dom_gpx->createElement('name');
					$gpx_name = $gpx_trk->appendChild($gpx_name);
					$gpx_name_text = $dom_gpx->createTextNode($name);
					$gpx_name->appendChild($gpx_name_text);
					
					$gpx_trkseg = $dom_gpx->createElement('trkseg');
					$gpx_trkseg = $gpx_trk->appendChild($gpx_trkseg);
				
					$coordinates = $coordinates->nodeValue;
					$coordinates = preg_split("/[\s\r\n]+/", $coordinates); //split the coords by new line
					foreach ($coordinates as $coordinate) {
						$latlng = explode(",", $coordinate);
						
						if (($lat = $latlng[1]) && ($lng = $latlng[0])) {
							$gpx_trkpt = $dom_gpx->createElement('trkpt');
							$gpx_trkpt = $gpx_trkseg->appendChild($gpx_trkpt);

							$gpx_trkpt_lat = $dom_gpx->createAttribute('lat');
							$gpx_trkpt->appendChild($gpx_trkpt_lat);
							$gpx_trkpt_lat_text = $dom_gpx->createTextNode($lat);
							$gpx_trkpt_lat->appendChild($gpx_trkpt_lat_text);
							
							$gpx_trkpt_lon = $dom_gpx->createAttribute('lon');
							$gpx_trkpt->appendChild($gpx_trkpt_lon);
							$gpx_trkpt_lon_text = $dom_gpx->createTextNode($lng);
							$gpx_trkpt_lon->appendChild($gpx_trkpt_lon_text);
							
							$gpx_time = $dom_gpx->createElement('time');
							$gpx_time = $gpx_trkpt->appendChild($gpx_time);
							$gpx_time_text = $dom_gpx->createTextNode(utcdate());
							$gpx_time->appendChild($gpx_time_text);
						}
					}
				}
			}
		}
		header("Content-Type: text/xml");
		echo $dom_gpx->saveXML();
	}
?>

Let me know if you find any issues.

Convert Relative Links to Absolute Links with PHP Regex

Here is a quick post on how to find and replace relative links with absolute links using PHP Regular Expressions (regex).

$url = "http://myabsoluteurl.com/";
$ret = preg_replace('/((?:href|src) *= *[\'"](?!(http|ftp)))/i', "$1$url", $ret);

Online RSVP form and database with PHP, JavaScript and MySQL

Requirements

Recently, I needed an online RSVP system for a reception I was hosting, all the options out there didn’t meet my requirements;

  • Customisable and able to self-host
  • No need for tracking codes/numbers to be sent with invitation
  • Able to RSVP additional guests
  • Able to modify an existing RSVP

Implementation

As usual, I decided to implement my own online RSVP solution, which has the following functionality;
  • PHP/JavaScript front-end
  • MySQL back-end
  • Sleek CSS (borrowed from WordPress)
  • Client-side checking with JavaScript
  • Server-side checking with PHP
  • Very basic submission viewing in HTML, wasn’t a real requirement as I could browse the database with phpMyAdmin, but it was good to have some visibility without the need of logging in

Installation

  • You will need PHP installed and a MySQL database.
  • Import the following SQL query to create a RSVP table with required fields.
  • Create a folder on your web hosting.
  • Extract the following zip file contents to this newly created folder.
  • Edit rsvp.php and configure your database settings, including database name, user name, password and host.
  • If using the optional email confirmation, configure the email from address and email body contents.
  • On your website, create an iframe to show the RSVP form.
Testing
  • Navigate to rsvp.php and submit a test response.
  • Navigate to res.php and confirm you can see your test response.
  • Alternatively, view the MySQL table directly (with phpMyAdmin)
Downloads

Improvements

Two small things I would have added, known after it’s use;

  • Client-side checking for ‘and’ in the full name field, few guests still tried to add themselves and their partner in that field.
  • Improved response email that would be addressed to all guests not just the first name.

Dynamic Google Maps circle markers/icons with PHP

A while back I posted on how to create dynamic Google maps markers which allow for any colour and any text in the classic Google map style.

Recently, I have had a need to do the same with circular markers. It uses the ‘Image Smooth Arc‘ function provided by Ulrich Mierendorff.

Similarly, I provide a little demo of some PHP code that does this that I quickly whipped up. Here are some example markers:
DefaultAZ110PQ69%BEΩ$
(Have a look at the image name)

Now that gets a little boring, how about some color:
DefaultAZ110PQ69%BEΩ$
(Again, have a look at the image name)

Again, you will need to download the modified arial font and host it in the same directory.

Have a look at the PHP source code below:

<?php
	include ("imageSmoothArc_optimized.php");

	$color = $_GET['color'];
	if (!$color) {$color = "ff776b";} //default google map color
	$color = str_replace("#", "", $color);
	$string = $_GET['text'];

	$font = realpath('arial.ttf');

	//unfortunately we still must do some offsetting
	switch (ord(substr($string,0,1))) {
		case 49: //1
			$offset = -2;
			break;
		case 55: //7
			$offset = -1;
			break;
		case 65: //A
			$offset = 1;
			break;
		case 74: //J
			$offset = -1;
			break;
		case 84: //T
			$offset = 1;
			break;
		case 99: //c
			$offset = -1;
			break;
		case 106: //j
			$offset = 1;
			break;
	}
	if (strlen($string) == 1) {
		$fontsize = 10.5;
	} else if (strlen($string) == 2) {
		$fontsize = 9;
	} else {
		$fontsize = 10.5;
		$offset = 0; //reset offset
		$string = chr(149);
	}

	$bbox = imagettfbbox($fontsize, 0, $font, $string);
	$width = $bbox[2] - $bbox[0] + 1;
	$height = $bbox[1] - $bbox[7] + 1;

	$im = imagecreatetruecolor(20, 20);

	//add the alpha
	$trans_colour = imagecolorallocatealpha($im, 0, 0, 0, 127);
	imagefill($im, 0, 0, $trans_colour);

	imageAlphaBlending($im, true);
	imageSaveAlpha($im, true);

	$bord_ellipse = array (0, 0, 0, 0);
	imageSmoothArc($im, 9, 10, 17, 17, $bord_ellipse, 0, 2*M_PI); //x, y, width, hegiht

	$fill_ellipse = array (hexdec(substr($color,0,2)), hexdec(substr($color,2,2)), hexdec(substr($color,4,2)), 0);
	imageSmoothArc($im, 9, 10, 16, 16, $fill_ellipse, 0, 2*M_PI); //x, y, width, hegiht

	$black = imagecolorallocate($im, 0, 0, 0);
	imagettftext($im, $fontsize, 0, 11 - $width/2 + $offset, 9 + $height/2, $black, $font, $string);

	header("Content-type: image/png");
	imagepng($im);
	imagedestroy($im);
?>

EDIT: 8 September 2014
Fixed a “Call-time pass-by-reference has been removed” error with ‘imageSmoothArc_optimized.php’. If you are experiencing the same with imageSmoothArc simple replace all instances of ‘&$’ with ‘$’.

PHP Factorial and Combination functions

A quick post on two functions for PHP that provide factorial and combination support.

function factorial($n) {
	if ($n <= 1) {
		return 1;
	} else {
		return factorial($n - 1) * $n;
	}
}

function combinations($n, $k) {
	//note this defualts to 0 if $n < $k
	if ($n < $k) {
		return 0;
	} else {
		return factorial($n)/(factorial($k)*factorial(($n - $k)));
	}
}