Archive

Posts Tagged ‘code’

Hide And Unhide Code With PHP

April 27th, 2009 No comments

If you are selling a system the last thing you want is for people to copy the system and pass it on for free. There are numerous ways to implement parts of the system that will stop this from happening.

By far the easiest is to create a section of code that is hidden, the removal of which will cause the application to fall over. It could even be as simple as a link back to your site so that even if you give you application away for free, you will always have that link present.

This method involves the use of a function called eval(), which takes PHP code as a string and interprets it to produce output. Here is an example that prints a link to Talk In Code.

$code = "echo "<a href='http://www.talkincode.com/' title'Talk In Code'>Talk In Code</a>";";
eval($code);

So lets use some code to hide this from anyone who might be reading our source code. First we pass this string through our hiding function to produce non-human readable text. This function is called obfuscate() and works by taking each character in turn and converting it into the ascii equivalent.

function obfuscate($text) {
    $length = strlen($text);
    $scrambled = '';
    
    for ($i = 0; $i < $length; ++$i) {
        $scrambled .= ord($text[$i]). ' ';
    }
    
    return $scrambled;
}
$code = "echo "<a href='http://www.talkincode.com/' title'Talk In Code'>Talk In Code</a>";";
 
$obf = obfuscate($code);
echo $obf;

This will print out the following:

101 99 104 111 32 34 60 97 32 104 114 101 102 61 39 104 116 116 112 58 47 47 119 119 119 46 116 97 108 107 105 110 99 111 100 101 46 99 111 109 47 39 32 116 105 116 108 101 39 84 97 108 107 32 73 110 32 67 111 100 101 39 62 84 97 108 107 32 73 110 32 67 111 100 101 60 47 97 62 34 59

We can store this as a variable until we next need it. In order to run this code we need to convert it into something that eval() can understand, to do this we use the opposite of the obfuscate(), called unobfuscate(). This function works by taking a set of ascii values and converting them into their character equivalents, note that we also trim the text to remove the last space from the end of the code.

function unobfuscate($scrambled) {
    $text = '';
 
    $bits = explode(' ',$scrambled);
    
    foreach ( $bits as $bit ) {
        $text .= chr($bit);
    }
 
    return trim($text);
}

We can then transform our hidden code into PHP code, which is then passed to the eval() function and run.

$code = '101 99 104 111 32 34 60 97 32 104 114 101 102 61 39 104 116 116 112 58 47 47 119 119 119 46 116 97 108 107 105 110 99 111 100 101 46 99 111 109 47 39 32 116 105 116 108 101 39 84 97 108 107 32 73 110 32 67 111 100 101 39 62 84 97 108 107 32 73 110 32 67 111 100 101 60 47 97 62 34 59';
$code = unobfuscate($code);
eval($code);

This produces the following output.

<a href='http://www.talkincode.com/' title'Talk In Code'>Talk In Code</a>

Beware that doing this sort of thing will probably slow down your application, especially if you try to eval() a large block of code. A single link like this is probably as far as I would personally go as there are much better ways of verifying that a piece of software is properly licensed.

Categories: PHP Strings Tags: , , , , , , ,

Preparing HTML And PHP Code For Pubilishing On Websites

April 1st, 2009 No comments

I talked a while ago about Adding Code To WordPress Blogs And Comments, but I decided that it needed a bit of code to do this automatically.

So here it is, prepared by the text processor.

<form method="post" action="http://talkincode.com/examples/text-process/text.php">
    <textarea name="text" rows="10" cols="80" wrap="off"></textarea>
    <input type="submit" value="Process" />
</form>
 
<?php
if ( isset($_POST["text"]) ) {
    $text   = $_POST["text"];
    $text   = stripslashes( $text );
    $input  = array ( "/&/", "/'/", "/"/", "/</", "/>/", "/t/", "/(?<=s)x20|x20(?=s)/", "/^\s$/m", "/&/", "/rn/" );
    $output = array ( "&amp;", "&#39;", "&quot;", "&lt;", "&gt;", "&nbsp;&nbsp;&nbsp;&nbsp;", "&nbsp;", "&nbsp;<br />", "&amp;", "<br />" );
    $temp = preg_replace($input, $output, $text);
    echo '<div style="border:1px solid grey;">'.$temp.'</div>';
}
?>

There seems to be rather a lot going on here, but the process is quite simple. The preg_replace() function can take an array as an argument for the input and output parameters. When you do this the arrays will be matched up so that the second item in the input array will be replaced by the second item in the output array.

So here is a list of the things I am matching for and what they are replaced with.

  • /&/ This matches for any ampersand, we replace this with the encoded variant of &amp;.
  • /&#39;/ Find single quotes and encode them with &#39;.
  • /\"/ Find double quotes and encode them with &quot;.
  • /
  • />/ Same as above but the other way around, in this case the equivalent is &gt;.
  • /\t/ Next we start matching for white space, the first is to find all tab characters and replace them with four &nbsp; characters, like this &nbsp;&nbsp;&nbsp;&nbsp;
  • /(?<=\s)\x20|\x20(?=\s)/ Next we look for any space character that has white space characters before and after it and replace with a single white space character &nbsp;.
  • /^\s$/m This matches for any line with nothing on it. These must be replaced with a single &nbsp; character, but in order to keep the code as it was posted we add a <br /> tag, the final output would be &nbsp;<br />.
  • /&/ Now that we have all of our tags encoded we need to re encode all of the & characters so that when the script prints out the content to a HTML page with all & translated to &amp;.
  • /\r\n/ Finally, we find all of the new line characters and convert them to <br /> tags. You might want to change this to just \n if you are using a Linux format.

Before we do any of this we pass the text through the stripslashes() function. This is because sending the text over POST might add slashes to the " and ' characters. This call just removes them.

You can try out the processor if you want by copying some code into the following text box.

This will output to the text process example page. You can also visit this page directly and play around with the tool.

Display JavaScript Source Programatically

March 23rd, 2009 2 comments

If you are running a JavaScript example page you can use the following function that will take the last script element on the page and print it out in a code tag. It uses JQuery to do the work, so you will need to include that library before using this function.

<script type="text/javascript">//<![CDATA[
 function displaySource(name) {
  $('<code>'
   + $('#display-' + name).prevAll('script').eq(0).html()
   .replace(/^\s*|\s*$/g, '')
   .split('\n').slice(1, -1).join('\n')
   .replace(/(^|\n) /g, '$1')
   .replace(/('[^']*')/g, '<em>$1</em>')
  + '</code>')
  .insertAfter('#display-' + name);
 }
//]]></script>

The function works by selecting the current script tag and finding all script elements before it. It then selects the first one it finds and outputs the contents to a code tag. It uses a few regular expressions to convert some of the characters to a more human readable format. The function is called like this.

<script type="text/javascript" id="display-test">displaySource("test");</script>

WordPress Post Friendly Code With JavaScript Replace

February 12th, 2009 No comments

I recently talked about adding code to blogs and comments to WordPress and making sure that certain characters are encoded properly. So to simplify things I thought I would create a little set of regular expressions that takes a sample of code and convert it into a Wordress friendly format. It consists of the following function, which takes the value of a text area called tochange and runs some regular expression replace functions on it. I have kept the expressions as simple as possible so they are quite easy to understand. The g argument for each expression means that the replace will be done for all of the text.

<script type="text/javascript">
function changeIt(){
  var text = document.getElementById('tochange').value;
  text = text.replace(/&/g,'&amp;');
  text = text.replace(/"/g,'&quot;');
  text = text.replace(/'/g,'&#39;');
  text = text.replace(/</g,'&lt;');
  text = text.replace(/>/g,'&gt;');
  text = text.replace(/^\s+/mg,'&nbsp;&nbsp;');
  document.getElementById('changed').value = text;
  document.getElementById('preTag').innerHTML = text;
}
</script>

The only one which might cause an issue is the last one with the expression ^\s+. This simply matches for 1 or more white space characters at the beginning of a line. The m argument means that the ^ symbol will be used to mean the start of a line. You can test this function with the following HTML tags.

  <textarea id="tochange" cols="50" rows="10"></textarea>
  <input type="submit" onclick="changeIt()" />
  <textarea id="changed" cols="50" rows="10"></textarea>
  <pre id="preTag"></pre>

The first textarea is what you want to alter, the second is the altered text and the pre tag displays what the altered text will look like in your browser.

Adding Code To WordPress Blogs And Comments

February 5th, 2009 No comments

WordPress is a pretty neat blogging platform, but it falls over quite spectacularly when trying to write code in posts. I write a lot of code for Talk In Code and so I have understand what needs to be encoded to make code examples work.

For code example on Talk In Code I use the <code> tag and I encode the following characters.

  • < into &lt;
  • > into &gt;
  • " into &quot;
  • ' into &#39;

Note: You must be in HTML mode in your WordPress editor or everything will be double encoded.

If these characters are left in then WordPress will either keep them "as is" (ie, a <br /> will cause a line break) or it will convert them into non standard characters. For example, typing a ' (single quote) is straightforward, but when your users come to copy and paste the code to try it for themselves they find that the characters WordPress gives them cause the examples to fail. So every time you type a ' you have to encode it using &#39;. The following example shows why typing a single quote will break your code examples.

echo ‘Hello World’;

The same thing applies to double quotes, as in the following example.

echo “Hello World”;

WordPress will also try to guess what you are doing and add in tags where you don’t want them. The effect of this is to break your code tags if you leave any space in them. Take the following example of a 4 line snippet of code, with a blank line between line 2 and line 4.

line 1
line 2

line 4

This is because WordPress will see the blank line and try to add some tags in to make it look like it thought you wanted it. In order to stop this you need to put in a &nbsp; (non breaking space) character on any blank lines that you have. The following example fixes the previous example.

line 1
line 2
 
line 4