<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Coding My Thoughts &#187; PHP</title>
	<atom:link href="http://marianoiglesias.com.ar/category/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://marianoiglesias.com.ar</link>
	<description>A glimpse at a coder&#039;s troubled mind</description>
	<lastBuildDate>Wed, 06 Jan 2010 19:25:16 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Let your MySQL partition breathe</title>
		<link>http://marianoiglesias.com.ar/php/let-your-mysql-partition-breathe/</link>
		<comments>http://marianoiglesias.com.ar/php/let-your-mysql-partition-breathe/#comments</comments>
		<pubDate>Sat, 28 Feb 2009 22:34:00 +0000</pubDate>
		<dc:creator>mariano</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://marianoiglesias.com.ar/1/let-your-mysql-partition-breathe/</guid>
		<description><![CDATA[<p>
Today I noticed my MySQL partition was taking over 86 GB of the available 120 GB. So I got worried and I wrote this little script to tell me how much space each DB I have is taking:
&#8230;</p>


No related posts.]]></description>
			<content:encoded><![CDATA[<p>
Today I noticed my MySQL partition was taking over 86 GB of the available 120 GB. So I got worried and I wrote this little script to tell me how much space each DB I have is taking:
</p>
<pre name="code" class="php">&lt;?php
function format($size) {
	$unit = 'B';
	$units = array(
		'GB' =&gt; 1024 * 1024 * 1024
		, 'MB' =&gt; 1024 * 1024
		, 'KB' =&gt; 1024
	);

	foreach($units as $currentUnit =&gt; $value) {
		if ($size &gt; 2 * $value) {
			$size /= $value;
			$unit = $currentUnit;
			break;
		}
	}

	return number_format($size, 1) . ' ' . $unit;
}

$settings = array(
	'host' =&gt; 'localhost'
	, 'user' =&gt; 'root'
	, 'password' =&gt; 'password'
);

$databases = array();

mysql_connect($settings['host'], $settings['user'], $settings['password']);

$result = mysql_query('show databases');
while($row = mysql_fetch_array($result)) {
	$databases[] = $row['Database'];
}

foreach($databases as $database) {
	$sizes[$database] = 0;

	mysql_select_db($database);
	$result = mysql_query('show table status');
	while($row = mysql_fetch_array($result)) {
		$sizes[$database] += $row['Data_length'] + $row['Index_length'];
	}
}

mysql_close();

foreach($sizes as $database =&gt; $size) {
	echo $database . ' = ' . format($size) . '&lt;br /&gt;';
}

echo '&lt;br /&gt;TOTAL: ' . format(array_sum($sizes));

?&gt;</pre>
<p>
When I ran it, I saw all my DBs where taking a total of 10.8 GB, much less than the 86 GB occupied in the partition. So it hit me, it has to be the binary logs, a set of files that store log events (<a href="http://dev.mysql.com/doc/refman/5.0/en/binary-log.html" rel="nofollow" >more about them here</a>). Indeed, if you would list the contents of /var/lib/mysql I would find a ton of .bin files, a lot of them as old as from 2007. Therefore, I realized I had to flush the logs.
</p>
<p>
In order to flush the binary logs, I logged in to the MySQL console as an administrator, and issued (if you are on a server with replication, you want to <a href="http://dev.mysql.com/doc/refman/5.0/en/purge-binary-logs.html" rel="nofollow" >purge the binary logs</a> instead):
</p>
<pre name="code" class="sql">FLUSH LOGS;
RESET MASTER;</pre>
<p>After doing so, the MySQL partition is now taking a total of 12 GB. Much better!</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://marianoiglesias.com.ar/php/let-your-mysql-partition-breathe/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>MSN Search API PHP Client</title>
		<link>http://marianoiglesias.com.ar/php/msn-search-api-php-client/</link>
		<comments>http://marianoiglesias.com.ar/php/msn-search-api-php-client/#comments</comments>
		<pubDate>Thu, 15 Sep 2005 19:34:00 +0000</pubDate>
		<dc:creator>mariano</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://marianoiglesias.com.ar/1/msn-search-api-php-client/</guid>
		<description><![CDATA[<p>
Microsoft has recently published their own <a href="http://msdn.microsoft.com/msn/msnsearch/" rel="nofollow" >MSN Search API</a> (now competing with Google and Yahoo) implemented as a SOAP Web Service. After some deliberation on the MSN Search API forums, I managed to develop a small&#8230;</p>


Related posts:<ol><li><a href='http://marianoiglesias.com.ar/php/get-a-taste-of-ajax-with-php/' rel='bookmark' title='Permanent Link: Get a taste of AJAX with PHP'>Get a taste of AJAX with PHP</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>
Microsoft has recently published their own <a href="http://msdn.microsoft.com/msn/msnsearch/" rel="nofollow" >MSN Search API</a> (now competing with Google and Yahoo) implemented as a SOAP Web Service. After some deliberation on the MSN Search API forums, I managed to develop a small PHP class to handle the API (thanks to <a href="http://www.quodlibet.be/" rel="nofollow" >quodlibet</a> for his help identifying a small bug.)
</p>
<p>
The class uses <a href="http://dietrich.ganx4.com/nusoap/" rel="nofollow" >nuSOAP</a> for interacting with the SOAP server. You will need to download nuSOAP and copy it inside a folter named <code>nusoap</code>, located in the same location as this class&#8217; file.
</p>
<p><span id="more-55"></span></p>
<p>
The source code for the class is the following (save it as <code>MSNWebSearch.class.php</code>):
</p>
<pre name="code" class="php">&lt;?php

define ('NUSOAP_PATH', dirname(__FILE__) . '/nusoap');
define ('MSN_API_KEY', 'Insert here your default MSN API key');
define ('MSN_API_ENDPOINT', 'http://soap.search.msn.com/webservices.asmx');
define ('MSN_API_NAMESPACE', 'http://schemas.microsoft.com/MSNSearch/2005/09/fex');

require_once(NUSOAP_PATH . '/nusoap.php');

class MSNWebSearch
{
	var $apiKey;
	var $filterAdult;
	var $languages;
	var $page;
	var $pages;
	var $query;
	var $records;
	var $recordsPerPage;

	function &amp;MSNWebSearch($apiKey = null)
	{
		$this-&gt;apiKey = isset($apiKey) ? $apiKey : MSN_API_KEY;
		$this-&gt;filterAdult = false;
		$this-&gt;languages = 'en-US';
		$this-&gt;recordsPerPage = 10;
		$this-&gt;page = 1;
	}

	function getApiKey()
	{
		return $this-&gt;apiKey;
	}

	function setApiKey($apiKey)
	{
		$this-&gt;apiKey = $apiKey;
	}

	function getErrorMessage()
	{
		return $this-&gt;errorMessage;
	}

	function getFilterAdult()
	{
		return $this-&gt;filterAdult;
	}

	function setFilterAdult($filterAdult)
	{
		$this-&gt;filterAdult = $filterAdult;
	}

	function getLanguages()
	{
		return $this-&gt;languages;
	}

	function setLanguages($languages)
	{
		$this-&gt;languages = $languages;
	}

	function getPage()
	{
		return $this-&gt;page;
	}

	function setPage($page)
	{
		if ($page &lt; 1)
		{
			$page = 1;
		}

		$this-&gt;page = $page;
	}

	function getPages()
	{
		return $this-&gt;pages;
	}

	function getQuery()
	{
		return $this-&gt;query;
	}

	function setQuery($query)
	{
		$this-&gt;query = $query;
	}

	function getRecords()
	{
		return $this-&gt;records;
	}

	function getRecordsPerPage()
	{
		return $this-&gt;recordsPerPage;
	}

	function setRecordsPerPage($recordsPerPage)
	{
		$this-&gt;recordsPerPage = is_int($recordsPerPage) &amp;&amp; $recordsPerPage &gt; 0 ? $recordsPerPage : 10;
	}

	function get()
	{
		$startIndex = ($this-&gt;page - 1) * $this-&gt;recordsPerPage;
		$elementsCount = $this-&gt;recordsPerPage;

		$parameters = array(
			'AppID' =&gt; $this-&gt;apiKey,
			'Query' =&gt; $this-&gt;query,
			'CultureInfo' =&gt; $this-&gt;languages,
			'SafeSearch' =&gt; ($this-&gt;filterAdult ? 'Strict' : 'Off'),
			'Requests' =&gt; array (
				'SourceRequest' =&gt; array (
					'Source' =&gt; 'Web',
					'Offset' =&gt; $startIndex,
					'Count' =&gt; $elementsCount,
					'ResultFields' =&gt; 'All'
				)
			)
		);

		if (isset($this-&gt;country))
		{
			$parameters['Location'] = $this-&gt;country;
		}

		$soapClient =&amp; new soapclient(MSN_API_ENDPOINT);

		$soapResult = $soapClient-&gt;call('Search', array ('Request' =&gt; $parameters), MSN_API_NAMESPACE );

		if ($soapClient-&gt;getError())
		{
			$this-&gt;errorMessage = $soapClient-&gt;getError();

			return false;
		}

		$this-&gt;records = $soapResult['Responses']['SourceResponse']['Total'];
		$this-&gt;pages = ceil($this-&gt;records / $this-&gt;recordsPerPage);

		if (is_array($soapResult['Responses']['SourceResponse']['Results']))
		{
			$result = array();

			foreach ($soapResult['Responses']['SourceResponse']['Results'] as $item)
			{
				$result[] = array (
					'url' =&gt; $item['Url'],
					'urlDisplay' =&gt; $item['DisplayUrl'],
					'urlCache' =&gt; $item['CacheUrl'],
					'title' =&gt; isset($item['Title']) &amp;&amp; trim($item['Title']) != '' ? $item['Title'] : $item['DisplayUrl'],
					'snippet' =&gt; $item['Description']
				);
			}
		}
		else
		{
			$result = array();
		}

		return $result;
	}
}
?&gt;</pre>
<p>
The usage of this class is quite simple. Take a look at the following <code>index.php</code> file to see an example. You can see it <a href="http://www.cricava.com/blogs/media/el_eternauta/sources/msn/index.php" rel="nofollow" >working here</a>. Please note that where it says <code>'My MSN API Key'</code>, you need to insert your own MSN API Key. If you don&#8217;t have one, <a href="http://search.msn.com/developer/appids.aspx?FORM=PMPD2" rel="nofollow" >get one now</a>.
</p>
<pre name="code" class="php">&lt;?php
require_once(dirname(__FILE__) . '/MSNWebSearch.class.php');

if (isset($_GET) &amp;&amp; isset($_GET['query']) &amp;&amp; trim($_GET['query']) != '')
{
	$currentPage = 1;

	if (isset($_GET['page']))
	{
		$currentPage = $_GET['page'];
	}

	$msnSearch =&amp; new MSNWebSearch();

	$msnSearch-&gt;setApiKey('My MSN API Key');
	$msnSearch-&gt;setQuery($_GET['query']);
	$msnSearch-&gt;setPage($currentPage);

	$result =&amp; $msnSearch-&gt;get();

	if ($result !== false)
	{
		if ($msnSearch-&gt;getPages() &gt; 1)
		{
			$navigation = array();

			$navigation['pages'] = $msnSearch-&gt;getPages();

			if ($msnSearch-&gt;getPage() &gt; 1)
			{
				$navigation['back'] = $PHP_SELF . '?page=' . ($msnSearch-&gt;getPage() - 1) . '&amp;query=' . urlencode($msnSearch-&gt;getQuery());
			}

			if ($msnSearch-&gt;getPage() &lt; $msnSearch-&gt;getPages())
			{
				$navigation['next'] = $PHP_SELF . '?page=' . ($msnSearch-&gt;getPage() + 1) . '&amp;query=' . urlencode($msnSearch-&gt;getQuery());
			}
		}
	}
}
?&gt;
&lt;html&gt;
	&lt;head&gt;
		&lt;titlevMSN Web Search&lt;/title&gt;
	&lt;/head&gt;
	&lt;body&gt;
		&lt;center&gt;&lt;p&gt;
			&lt;form action="&lt;?php echo $PHP_SELF; ?&gt;" method="GET"&gt;
				Search:
				&lt;input type="text" name="query" size="70" value="&lt;?php echo isset($_GET['query']) ? $_GET['query'] : ''; ?&gt;" /&gt;
				&lt;input type="submit" value="Search" /&gt;
				&lt;?php
				if (isset($msnSearch) &amp;&amp; $result !== false)
				{
				?&gt;
				&lt;br /&gt;
				&lt;b&gt;&lt;?php echo $msnSearch-&gt;getRecords(); ?&gt;&lt;/b&gt; records matched your query.
				&lt;?php
				}
				?&gt;
			&lt;/form&gt;
		&lt;/p&gt;&lt;/center&gt;
		&lt;?php
		if (isset($msnSearch) &amp;&amp; $result === false)
		{
			?&gt;
			There was an error with your search. Error message: &lt;b&gt;&lt;?php echo $msnSearch-&gt;getErrorMessage(); ?&gt;&lt;/b&gt;.
			&lt;?php
		}
		else if (isset($msnSearch))
		{
			if (isset($navigation))
			{
			?&gt;
			&lt;center&gt;&lt;p&gt;
				Pages: &lt;b&gt;&lt;?php echo $msnSearch-&gt;getPages(); ?&gt;&lt;/b&gt;
				&lt;?php
				if (isset($navigation['back']))
				{
				?&gt;
				&lt;a href="&lt;?php echo $navigation['back']; ?&gt;"&gt;Previous&lt;/a&gt;
				&lt;?php
				}

				if (isset($navigation['back']) &amp;&amp; isset($navigation['next']))
				{
				?&gt;
				|
				&lt;?php
				}

				if (isset($navigation['next']))
				{
				?&gt;
				&lt;a href="&lt;?php echo $navigation['next']; ?&gt;"&gt;Next&lt;/a&gt;
				&lt;?php
				}
				?&gt;
			&lt;/p&gt;&lt;/center&gt;
			&lt;?php
			}
			?&gt;
			&lt;ul&gt;
			&lt;?php
			foreach ($result as $item)
			{
			?&gt;
			&lt;li&gt;
				&lt;a href="&lt;?php echo $item['url']; ?&gt;"&gt;&lt;?php echo $item['title']; ?&gt;&lt;/a&gt;: &lt;?php echo $item['snippet']; ?&gt;
				&lt;br /&gt;
				&lt;font color="#008000"&gt;&lt;?php echo $item['urlDisplay']; ?&gt;&lt;/font&gt; - &lt;a href="&lt;?php echo $item['urlCache']; ?&gt;"&gt;Cache&lt;/a&gt;
			&lt;/li&gt;
			&lt;?php
			}
			?&gt;
			&lt;/ul&gt;
			&lt;?php
		}
		?&gt;
	&lt;/body&gt;
&lt;/html&gt;</pre>
<p>
Hope this helps anyone.
</p>
<p>
<b>UPDATE [Aug 20, 2006]</b>: After receiving some emails saying that the class didn&#8217;t work (which in fact does), I decided to publish a ZIP file that contains a working MSN Search Based Page. It includes nuSOAP as of July 19, 2006. First, <a href="http://www.cricava.com/blogs/media/el_eternauta/sources/msn.zip" rel="nofollow" >download the ZIP file</a>. Then, uncompress to a new directory on your webserver and EDIT the file index.php, looking for line 3. Insert your MSN API KEY there. After specifying your API key, you should be good to go for testing.</p>


<p>Related posts:<ol><li><a href='http://marianoiglesias.com.ar/php/get-a-taste-of-ajax-with-php/' rel='bookmark' title='Permanent Link: Get a taste of AJAX with PHP'>Get a taste of AJAX with PHP</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://marianoiglesias.com.ar/php/msn-search-api-php-client/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Get a taste of AJAX with PHP</title>
		<link>http://marianoiglesias.com.ar/php/get-a-taste-of-ajax-with-php/</link>
		<comments>http://marianoiglesias.com.ar/php/get-a-taste-of-ajax-with-php/#comments</comments>
		<pubDate>Fri, 19 Aug 2005 18:57:00 +0000</pubDate>
		<dc:creator>mariano</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://marianoiglesias.com.ar/1/get-a-taste-of-ajax-with-php/</guid>
		<description><![CDATA[<p>Some of you may have heard of Ajax, while some may have not. The truth of the matter is that Ajax (Asynchronous JavaScript and XML) is a technology to be followed. Furthermore, a technology to be used! To give a&#8230;</p>


Related posts:<ol><li><a href='http://marianoiglesias.com.ar/php/msn-search-api-php-client/' rel='bookmark' title='Permanent Link: MSN Search API PHP Client'>MSN Search API PHP Client</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Some of you may have heard of Ajax, while some may have not. The truth of the matter is that Ajax (Asynchronous JavaScript and XML) is a technology to be followed. Furthermore, a technology to be used! To give a little background about it, let&#8217;s see what <a href="http://en.wikipedia.org/wiki/AJAX" rel="nofollow" >wikipedia</a> has to say about it: &#8220;term describing a web development technique for creating interactive web applications using a combination of: HTML (or XHTML) and CSS for presenting information; The Document Object Model manipulated through JavaScript to dynamically display and interact with the information presented; and The XMLHttpRequest object to exchange data asynchronously with the web server. (XML is commonly used, although any text format will work, including preformatted HTML, plain text, and JSON)&#8221;.</p>
<p>For Gmail (Google Mail) or GMaps (Google Maps) users, you have already experienced the power of Ajax. Notice how when you switch from page to page in GMail the browser page does not reload? That&#8217;s the power of Ajax.</p>
<p>In this post, I&#8217;ll give you an introduction to Ajax using a yet in beta stage, but very powerful open source PHP library called <a href="http://xajax.sourceforge.net/" rel="nofollow" >XAJAX</a>. I&#8217;ll get right down to the coding (more information about this library can be obtained from <a href="http://xajax.sourceforge.net/" rel="nofollow" >its sourceforge site</a>.)</p>
<p>As an example, I&#8217;ll develop the classic Country / State combo box combination. Normally, if we wanted the State combo to be updated by the current selected country, we would make one of two choices:</p>
<ul>
<li>Use Javascript by sending all countries and their respective provinces to the client browser, and update State combobox choosing those states that belong to the selected country.</li>
<li>Reload the page when a different country has been selected, including only that country&#8217;s states in the State combo box.</li>
</ul>
<p>With Ajax, we&#8217;ll do none of those. We&#8217;ll have the list of states per country on a server-side PHP script. When the country selection changes, we&#8217;ll use Xajax to update the list of available states based on the country selection. To simplify, I&#8217;ll do all this on the same PHP file.</p>
<p>We start by including the xanax library, and declaring a PHP function that will be called via Ajax when the country selection changes.</p>
<pre name="code" class="php">require_once(dirname(__FILE__) . '/xajax.inc.php');

function setCountry($countryCode)
{
        $provinces = array();

        switch($countryCode)
        {
                case 'AR':

                        $provinces['BA'] = 'Buenos Aires';
                        $provinces['CO'] = 'Cordoba';
                        $provinces['SL'] = 'Salta';
                        $provinces['SF'] = 'Santa Fe';

                        break;

                case 'US':

                        $provinces['CA'] = 'California';
                        $provinces['WA'] = 'Washington';

                        break;
        }

        $objResponse =&amp; new xajaxResponse();

        if (count($provinces) &gt; 0)
        {
                $objResponse-&gt;addScript("document.getElementById('province').disabled = false;");
                $objResponse-&gt;addScript("document.getElementById('province').options.length = 0;");

                foreach ($provinces as $id =&gt; $province)
                {
                        $objResponse-&gt;addScript("addOption('province','" . $province . "','" . $id . "');");
                }
        }
        else
        {
                $objResponse-&gt;addScript("document.getElementById('province').options.length = 0;");
                $objResponse-&gt;addScript("addOption('province','-- Select a Country first -','');");
                $objResponse-&gt;addScript("document.getElementById('province').disabled = true;");
        }

        return $objResponse-&gt;getXML();
}</pre>
<p>The first few lines are quite easy to follow. The first interesting thing that we see here is when we start by creating the Xajax response (<code>$objResponse =&amp; new xajaxResponse();</code>) After that, if there are states to be inserted, we enable the state control, reset the state combo box (by setting its option length to 0), and for each state we call a client side javascript function called <code>addOption()</code> that will insert the specified option in the combo box. If no states are to be inserted, then we empty the combo box, inserting only a dummy option, and disable the element.</p>
<p><span id="more-58"></span></p>
<p>Now, let&#8217;s see the next few server-side lines of code:</p>
<pre name="code" class="php">$xajax =&amp; new xajax();

$xajax-&gt;registerFunction("setCountry");

$xajax-&gt;processRequests();</pre>
<p>Here, we instantiate the main xajax handler, registering the function we&#8217;ve just created, and telling xajax to process any request. From here on, all the remaining code is client side (HTML). What we need to pay special attention to is the client side javascript function we already mentioned, which is included here, and the insertion of xajax generated javascript code, all of this is done within the <code>header</code> tag of the HTML document:</p>
<pre name="code" class="php">&lt;?php
$xajax-&gt;printJavascript();
?&gt;
&lt;script type="text/javascript"&gt;
&lt;!--
function addOption(selectId, txt, val)
{
        var objOption = new Option(txt,val);

        document.getElementById(selectId).options.add(objOption);
}
// --&gt;
&lt;/script&gt;</pre>
<p>Finally, the code that dispatches xajax when the country selection changes:</p>
<pre name="code" class="html">&lt;select name="country" id="country" onchange="xajax_setCountry(document.getElementById('country').value);"&gt;
&lt;option value=""&gt;-- Select a Country --&lt;/option&gt;
&lt;option value="AR"&gt;Argentina&lt;/option&gt;
&lt;option value="US"&gt;United States&lt;/option&gt;
&lt;/select&gt;</pre>
<p>You can see the code <a href="http://cricava.com/blogs/media/el_eternauta/sources/xajax/index.php" rel="nofollow" >working here</a>, and download the <a href="http://cricava.com/blogs/media/el_eternauta/sources/xajax/example-xajax.txt" rel="nofollow" >source file here</a>.</p>


<p>Related posts:<ol><li><a href='http://marianoiglesias.com.ar/php/msn-search-api-php-client/' rel='bookmark' title='Permanent Link: MSN Search API PHP Client'>MSN Search API PHP Client</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://marianoiglesias.com.ar/php/get-a-taste-of-ajax-with-php/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk
Database Caching 39/109 queries in 0.184 seconds using disk

Served from: marianoiglesias.com.ar @ 2010-07-30 05:26:01 -->