Short Tag – Web Development Blog

Get the values of PHP directives


echo ini_get("post_max_size");

This is the way you get the values of a PHP directive. It is a very handy function.
It can be used to:
* check if register globals is active on server or not: ini_get(“register_globals”)
* check what is the max upload and post size at upload: ini_get(“post_max_size”), ini_get(“upload_max_filesize”)
* check what is the max execution time for a script: ini_get(“max_execution_time”)
* get the include path: ini_get(“include_path”)
and plenty more. I just listed a few of the most common use of this function.

To change a directive use ini_set(). ini_set() is not enabled on every host, for security reasons, or it’s usage is limited to a few directives, so pay attention!!!

ini_get() documentation:
http://php.net/manual/en/function.ini-get.php

ini_set() documentation:
http://www.php.net/manual/en/function.ini-set.php

Connect to multiple Mysql databases with PHP

Sometimes we need to connect to multiple databases with our PHP script. Try not to connect to too many different hosts, this can increase considerably the execution time of your script.

First, I create the 2 connection with 2 hosts:


$user1 = "";
$pass1 = "";
$db1 = "";
$host1= "";
$conn1 = mysql_connect($host1, $user1, $pass1);

$user2 = "";
$pass2 = "";
$db2 = "";
$host2 = "";
$conn2 = mysql_connect($host2, $user2, $pass2);

mysql_select_db($db1, $conn1);
mysql_select_db($db2, $conn2);

The second parameters of the mysql_db_select() function will return the handler for the connection to the database. This way I can select the database to run my queries on.


$rez1 = mysql_query("SHOW TABLES FROM `database1`;",$db1);
$rez2 = mysql_query("SHOW TABLES FROM `database2`;",$db2);

2 examples of queries. mysql_fetch_array(), mysql_num_rows() and similar functions don’t need the handler because they work with the queries we ran against the wanted database.

In a similar manner you can connect to even more databases. If you can work with only one database it is recommended to use one. The less, the better.

Post to twitter with PHP, twitting with PHP

I wrote a post about using file_get_contents() in PHP with context stream a while ago. I thought I’d post a usage example. Below is a function that posts your message into your twitter profile directly from PHP.


function myTweet($username, $password, $msg)
{
$context = stream_context_create(array(
'http' =>  array(
'method'  =>  'POST',
'header'  =>  sprintf("Authorization: Basic %s\r\n", base64_encode($username.':'.$password)).
"Content-type:  application/x-www-form-urlencoded\r\n",
'content' =>  http_build_query(array('status' => $msg)),
'timeout' =>  5,
),
));
$ret = file_get_contents('<a rel="nofollow" href="http://twitter.com/statuses/update.xml" target="_blank">http://twitter.com/statuses/update.xml</a>', false, $context);

return false !==  $ret;
}

Function usage:


if(myTweet("I am finally home", "myuser", "mypass")</code>)
echo 'Tweet posted!';
else
echo 'Error posting tweet!';

Cancel action on a link (do not reload the window on click)

When you are developing using javascript it is often you get to the situation where you want to do something with javascript when the user clicks on the link. The problem is that when the user clicks on the link the browser will reload the window (and you don’t want that).

1.) Disable reload using HTML


<a href="#" onclick="myfunction();">do it</a>

With # start the on-page anchors, so this way you will specify that the link is an anchor (with no name) and the page will not be reloaded.

2.) The elegant way to disable links using javascript


<a href="javascript:return false;" onclick="if(confirm('Are you sure?'))myfunction();">do it</a>

For example these can be used to ask the user for deletion confirmation… and many other things of course.

Multidimensional arrays in Smarty, List menus

If you are working with template engines in PHP you probably heard of Smarty.
Official website: http://www.smarty.net

There is a situation that is not well documented on their site, so I thought I will explain it in my blog. As the title says, I am going to talk about listing multidimensional arrays in smarty. Let’s say you want to list a menu, you will probably use a 2 dimensional array, because you need the button’s title, link and maybe other data.

In PHP you will assign the array variable like any regular variable. Example:


$arr[0]['link'] = 'http://shorttag.info';
$arr[0]['title'] = 'Shorttag homepage';

$arr[1]['link'] = 'http://shorttag.info';
$arr[1]['title'] = 'Shorttag contact page';

//etc

$smarty->assign("menu", $arr);

In the template the listing of the two dimensional array will look like this:


{foreach from=$menu item=v}
<li><a href="{$v.link}.html">{$v.title}</a></li>
{/foreach}

The version above is for the case you don’t need to loop through the second level of the array. Looping through the second level would look like this:


{foreach from=$menu item=v}
{foreach from=$v item=v2}
<li>{$v2}</li>
{/foreach}
{/foreach}

The second example will display the links and titles in a list. This example is for those of you who use arrays with more levels than 2 (3 dimensional array and so on).

Get month, day, year from timestamp functions [PHP]

Today I thought I can share you a few of my functions. Today’s article is an easy one, but I use the functions in almost all my websites, so I thought they can be useful to you.

So here are a few functions that get the year,month,day,hour,minute,second from a time stamp, similar to the MYSQL functions. I like this approach a lot, that’s why I wrote these functions.


function day($ts)
{
return date("d", $ts);
}

function month($ts)
{
return date("m", $ts);
}

function year($ts)
{
return date("Y", $ts);
}

function hour($ts)
{
return date("H", $ts);
}

function minute($ts)
{
return date("i", $ts);
}

function second($ts)
{
return date("s", $ts);
}

function this_year()
{
return date("Y");
}

function this_month()
{
return date("m");
}

function this_day()
{
return date("d");
}

function this_hour()
{
return date("H");
}

function this_minute()
{
return date("i");
}

function this_second()
{
return date("s");
}

And now, for the OOP gurus here is a class with static members, that can be used in your applications.


class MyDate
{
public static function day($ts)
{
return date("d", $ts);
}

public static function month($ts)
{
return date("m", $ts);
}

public static function year($ts)
{
return date("Y", $ts);
}

public static function hour($ts)
{
return date("H", $ts);
}

public static function minute($ts)
{
return date("i", $ts);
}

public static function second($ts)
{
return date("s", $ts);
}

function this_year()
{
return date("Y");
}

function this_month()
{
return date("m");
}

function this_day()
{
return date("d");
}

function this_hour()
{
return date("H");
}

function this_minute()
{
return date("i");
}

function this_second()
{
return date("s");
}

function addZero($ent)
{
if((int)trim($ent)<10)
return "0".(int)trim($ent);
else return trim($ent);
}
}

The addZero function adds a ‘0′ in front of number smaller than 10. It is useful when you get the month, or the day and it has no ‘0′. It is used mostly for displaying date.

Usage:


$time = time();
$day = day($time);
//for the OOP fans
$day = MyDate::day($time);

AS3 get file contents, load and work with XML

As3 has a few classes that ease our work with external files (for example with XMLs).
First I will show you how to load an external file:


var file:string = "myfile.txt";
var ur:URLRequest = new URLRequest(file);
var ul:URLLoader = new URLLoader();
ul.addEventListener(Event.COMPLETE, loaded);
ul.load(ur);

function loaded(e:Event):void
{
var str:String = e.target.data;
trace('Loaded data is:'+str);
}

In the example above str variable will hold the content of a file. This file can be a local file, a remote file, xml, json… any kind of a text file.

First, we create an URLRequest object, than an URLLoader object (and a ‘COMPLETE’ event listener), we make the request using the ‘load’ function and passing the URLRequest object instance. In the ‘loaded’ function we get the returned data using the event’s target: the loader.

Now, if you want to work width an XML you have to load the file as I’ve shown you and after that use AS3’s XML class to parse the data:


var file:string = "myfile.xml";
var ur:URLRequest = new URLRequest(file);
var ul:URLLoader = new URLLoader();
ul.addEventListener(Event.COMPLETE, loaded);
ul.load(ur);

function loaded(e:Event):void
{
var str:String = e.target.data;
var xml:XML = new XML(str);
trace(xml.email[0].toString());
}

In the ‘loaded’ function I created an XML object from the loaded string and than I accessed one of the xml’s members, called ‘email’. In this case the XML would look like this:


<emails>
<email>john@example.com</email>
<email>nick@example.com</email>
<email>tracy@example.com</email>
</emails>

Using the XML object you can access the members of an XML structure as the members(attributes) of a regular AS3 Object. More about the XML class on Adobe’s website:
http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/XML.html

ActionScript 3 getURL()

Among the big changes in AS3 is the change of getURL() function. This function has been eliminated from AS3, since this language has became an Object Oriented programming language and it followes the rules of ECMAScript.

In AS2 to open a url (to create a link in flash) we had to use getURL function.

In AS3 we have to use a few objects, the code is longer, but it’s more elegant and the debugging is easier.
So, here is the code:


var my_url:String = "http://www.myurl.com";
var request:URLRequest = new URLRequest(my_url);
try {
navigateToURL(request, '_blank'); // second argument is target
} catch (e:Error) {
trace("Error occurred!");
}

First, we create an URLRequest object from the url string, and we pass this object to the navigateToURL() function, along with one parameter, the target of the url.

To link this action to a button you just have to use an event listener. Let’s say our button is named: ‘mybutton’.
The would be like this:


mybutton.addEventListener(MouseEvent.CLICK, openURL);

function openURL(e:MouseEvent):void
{
var my_url:String = "http://www.myurl.com";
var request:URLRequest = new URLRequest(my_url);

try {
navigateToURL(request, '_blank'); // second argument is target
}
catch (e:Error) {
trace("Error occurred!");
}

}

AS3 random range

As3’s Math.random() function returns a random decimal number between 0 and 1. Here is a function that uses Math.rand() to generate a random number within a specified range:


function rand(minNum:Number, maxNum:Number):Number
{
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}

This function return a random number within a range. It is much like PHP’s rand() function.
Usage:


var i:Number = rand(1,10);

This will return a random number between 1 and 10.

AS3 string replace function


function replace(input:String, replace:String, replaceWith:String):String
{
var sb:String = new String();
var found:Boolean = false;

var sLen:Number = input.length;
var rLen:Number = replace.length;

for (var i:Number = 0; i < sLen; i++)
{
if(input.charAt(i) == replace.charAt(0))
{
found = true;
for(var j:Number = 0; j < rLen; j++)
{
if(!(input.charAt(i + j) == replace.charAt(j)))
{
found = false;
break;
}
}

if(found)
{
sb += replaceWith;
i = i + (rLen - 1);
continue;
}
}
sb += input.charAt(i);
}
return sb;
}

This function is the equivalent of str_replace in PHP.
Usage:


var str:String = "abcdefgh123";
str = replace(str, '123', 'ijk');
trace(str);

The result will be: abcdefghijk