Tag: snippet

Updated API code samples

We’ve just made things even easier for all developers out there who wish to integrate Spin Rewriter’s incredible power of ENL Semantic Spinning into their applications.

We’ve updated our (almost famous) working code samples, along with the brand-new Spin Rewriterย API SDK (PHP Library & Examples), version 4.1.0.

With all this code ready to go, you can now integrate Spin Rewriter’s article spinning technology into your own software products with — literally! —ย 3 lines of code!

Of course our API developer documentation still tells you everything about all the features that are available through the API (which is all of them), and how to use them: http://www.SpinRewriter.com/api

Enjoy! ๐Ÿ˜‰

Spin Rewriter API documentation

Okay, we just launched the Spin Rewriter API, and we thought – we should get developers on board as effortlessly as possible!

So we prepared a ton of stuff for all of you developers out there, and our efforts should enable you to integrate the Spin Rewriter API into your own apps in 10 minutes or so. Among other things you’ll find:

  • A thorough documentation of all API (HTTP POST) requests and API (JSON) responses. This will give you an idea about the inner workings of our API.
  • 100% functioning code samples (in PHP):
    – a script that will get the remaining number (quota) of API calls
    – a script that will spin your article and return the spun text (with spintax in place)
    – a script that will spin your article and return one of the possible unique variations
  • We prepared an actual official Spin Rewriter API SDK (Standard Development Kit) that’s also available in PHP. This kit comes with a number of examples, and allows you to spin your articles using the Spin Rewriter API with as little as 3 lines of code. ๐Ÿ˜‰
  • A short “Q&A” section that should provide the answers to the most common questions.

You can find everything over at http://www.SpinRewriter.com/api ๐Ÿ˜€

We love developers just as much as Steve Ballmer (the Microsoft guy), and we want to make everything as easy as possible for you. Oh, and here’s a funny clip of him going just a little bit crazy. ๐Ÿ˜€

Prevent users from accidentally leaving the page [JavaScript]

Sometimes your users might lose important information that they’ve been working on by accidentally leaving the page. They can either press the “previous page” or “next page” button by accident, or they can hit the “backspace” key on their keyboard, inadvertently click a link etc.

Luckily you can prevent them from losing their progress by using the following bit of JavaScript code:

window.onbeforeunload = function() {
    if (your_users_might_lose_their_work) {
        dialog_text = "IMPORTANT: Are you sure you want to leave this page?\n\n";
        dialog_text += "WARNING: If you leave this page, you will lose all your current progress.";
        return dialog_text;
    }
};

This code works perfectly fine with all modern browsers, with one small disclaimer: Firefox will not show your custom warning to your users, instead it will simply state “This page is asking you to confirm that you want to leave – data you have entered may not be saved.” However, that’s exactly what you usually want to say in this situation anyway.

Creating an array of all dates between 2 specified dates [PHP]

I’ll just cut to the chase.

/**
 * create an array of all dates between two specified dates
 * @param datetime $strDateFrom
 * @param datetime $strDateTo
 * @return array
 */
function createDateRangeArray($strDateFrom, $strDateTo) {		
	$aryRange = array();
	$iDateFrom = mktime(1, 0, 0, substr($strDateFrom, 5, 2), substr($strDateFrom, 8, 2), substr($strDateFrom, 0, 4));
	$iDateTo = mktime(1, 0, 0, substr($strDateTo, 5, 2), substr($strDateTo, 8, 2), substr($strDateTo, 0, 4));
	if ($iDateTo >= $iDateFrom) {
		array_push($aryRange, date("Y-m-d", $iDateFrom));			
		while ($iDateFrom < $iDateTo) {
			$iDateFrom = $iDateFrom + 86400;
			array_push($aryRange, date("Y-m-d", $iDateFrom));
		}
	}
	return $aryRange;
}

Is this a valid URL? [PHP]

If your users link to some URL, it’s always nice to check if their input actually represents a valid URL. You can do just that with this function:


/**
 * return true if the passed variable is a valid URL address
 * @param $url
 * @return boolean
 */
function isValidURL($url) {
	$pattern  = '/^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/';
	return preg_match($pattern, $url);
}

If this function returns true, you might want to actually open the URL (using file_get_contents() or some other function) to see if it works.

Convert large numbers into a more readable format

It can be tricky to really understand the value of 7312946 or 983217 at the first glance. Saying 7.3M and 983k seems like a much better option. How to convert numbers into a nicer format? Like this:

/**
 * create a nicely formatted number
 * @param $number a large number
 * @param $shorten default true = append k or M, false = format with commas and dots
 * @return int
 */
function createHumanReadableInteger($number, $shorten = true) {
	if (is_numeric($number)) {
		if ($shorten) {
			if ($number < 100000) {
				$return_int = number_format($number, 0);
			} else {
				$number_proc = $number;
				$units = explode(" ", "B k M G T P");
				for ($i = 0; $number_proc > 1000; $i++) {
					$number_proc = $number_proc / 1000;
				}
				if ($number > 1000000) {
					$return_int = round($number_proc, 2) . " " . $units[$i];
				} else {
					$return_int = round($number_proc, 1) . " " . $units[$i];	
				}
			}
		} else {
			$return_int = number_format($number, 0);
		}
		return $return_int;	
	} else {
		return 0;
	}
}

Converting a DATETIME variable into a UNIX timestamp

Here’s how:

/**
 * convert a datetime value (Y-m-d H:i:s) to UNIX timestamp value
 * @param datetime $datetime
 * @return timestamp
 */
function datetime_to_timestamp($datetime) {
    list($date, $time) = explode(" ", $datetime);
    list($year, $month, $day) = explode("-", $date);
    list($hour, $minute, $second) = explode(":", $time);
    return mktime($hour, $minute, $second, $month, $day, $year);
}

Using subkey to sort an array in PHP

It’s a bit tricky to sort multidimensional arrays in PHP by one of array’s subkeys, but it can absolutely be done. Check it out:

/**
 * USING POINTER TO ARRAY - sort an array of arrays with associative indeces by one of those associative values
 * @param $array pointer to our array
 * @param $subkey associative index that we want to order by
 * @param $sort_type [SORT_ASC|SORT_DESC]
 * @return void
 */
function sortBySubkey(&$array, $subkey, $sort_type = SORT_ASC) {
   foreach ($array as $subarray) {
      $keys[] = $subarray[$subkey];
   }
   array_multisort($keys, $sort_type, $array);
}

Creating absolutely safe strings

Sometimes you are given a string (someone’s name, or some title, or something completely different) and you cannot afford to use this string if you’re not completely sure what to expect. For instance, sometimes you need to convert a string into something that consists only of alphanumerical characters and spaces. You can always use the following function:

/**
 * create a string that only consists of alphanumerical characters and spaces
 * @param $string
 * @return string
 */
function createSafeString($string) {
	$string = strtolower($string);
        $output = "";
	for ($i = 0; $i < strlen($string); $i++) {
		$ord = ord($string[$i]);
		if (($ord >= 48 && $ord <= 57) || ($ord >= 65 && $ord <= 90) || ($ord >= 97 && $ord <= 122) || ($ord == 32)) {
			$output .= $string[$i];
		}
	}
	return $string;
}

Don’t manually escape all your variables

Let’s start with something fairly simple, shall we?

I’ve seen way too many programmers escaping all $_POST and $_GET variables like this:

$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);

I suggest you simply use something like this from now on:

$post = array();
$get = array();
foreach ($_POST as $key => $value) {
	$post[$key] = escape_string($value);
}
foreach ($_GET as $key => $value) {
	$get[$key] = escape_string($value);
}
/**
 * escape given variable so we can use it in an SQL query
 * @param anything $value
 * @return anything $escaped_value
 */
function escape_string($value) {
	if (get_magic_quotes_gpc()) {
		$value = stripslashes($value);
	}	
	if (!is_numeric($value)) {
		$value = mysql_real_escape_string($value);
	}	
	return $value;
}

This way you can always use $post instead of $_POST and $get instead of $_GET if you need escaped values. And you can always access the original values in the original $_POST and $_GET variables. Pretty neat, huh? ๐Ÿ™‚