Category Archives: WordPress

Of PHP, Wordpress and other geeky stuff.

How to Start an Internet Business

Starting a business online is easier than you think. Succeeding in one is another story, of course. First of all, you need a product or service, which had better be something that people want. In my experience, what people want most is to make money. Anything that helps them make money is a good product. Second, you need a way of collecting money and delivering the product or providing the service in return for payment. Third, you need to get visibility.

Continue reading

MySQL on Mac OSX Yosemite

If you use XAMPP for dev work on your Mac at home, and updated your OS to Yosemite, you may be temporarily distressed when you find that your MySQLd doesn’t start up. The fix is fairly simple.

Edit /Applications/XAMPP/xamppfiles/xampp. (You may have to use sudo to do this.)

Look for:

$XAMPP_ROOT/bin/mysql.server start > /dev/null &

And add unset DYLD_LIBRARY_PATH on top of it. It should look like:

unset DYLD_LIBRARY_PATH
$XAMPP_ROOT/bin/mysql.server start > /dev/null &

Restart MySQLd and you it should work.

Back to Blogging

As you may have noticed, I haven’t been writing much in the last couple of months. It was because of one of my regularly scheduled writer’s blocks. When I’m blocked, I usually find other things to do, and convince myself that they are really important and urgent. One such thing this time around was a revamping of my blog backend. The original design was dated, and it really needed an upgrade. Or so I told myself and worked on it for a few weeks. If you are reading this post, you can see the fruits of my labor. And I hope you like it.

Continue reading

High Performance Blogs and Websites

Do you have a website or a blog and feel that it is getting bogged down with heavy traffic? First of all, congratulations — it is one of those problems that webmasters and bloggers would love to have. But how would you solve it? The first thing to do is to enable PHP acceleration, if your site/blog is PHP based. Although it should be straightforward (in theory), it might take a while to get it right. You know what they say — In theory, theory and practice are the same. In practice, they are not. Acceleration, however, is a low-hanging fruit, and will go a long way in solving your problems.

Once you have extracted all the mileage out of the accelerator solution, it is time to incorporate a Content Delivery Network or CDN. What a CDN does is to serve all your static files (images, style sheets, javascript files, and even cached blog pages) from a network of servers other than your own. These servers are strategically placed around the continent (and around the globe) so that your readers receive the content from a location geographically close to him. In addition to reducing the latency due to distance, CDN also helps you by reducing the load on your server.

Continue reading

Learn to Play Blackjack

Here is an online Blackjack game that will teach you how to play it. If you don’t know what to do, just ask the program! This post hopefully teaches you sound strategies in playing Blackjack. But you should know that even with the soundest of strategies, Blackjack is a losing game. The house always holds a small edge. The best any strategy can do for you is to increase your staying powerthe time it takes you to lose your shirt.

Continue reading

Battles Too Small to Fight

A few years ago, I had significant income from online advertising because of my networked business model that worked extremely well at that time. At one point the ad serving company decided to cancel my account because some sites in my network violated their terms and conditions. They told me that they couldn’t pay me for the last two months because they had already refunded the money to the advertisers who were outraged at my T & C violations. Mind you, it was a small fortune. But a couple of months later, they decided to reinstate me. The first thing they did after reactivating my account was to pay me my outstanding balancethe money they hadrefundedto their disgruntled advertisers. I, of course, was quite gruntled about the outcome. But the joy didn’t last; they banned me again a month later.

Continue reading

We Are Moving

Unreal Blog has moved to a more powerful server at Arvixe. [Disclosure: All the server links in this article are affiliate links.] For those interested in moving your hosting to a new server, I thought I would describe thegotchasinvolved.

This gotcha got me during a test migration of my old posts to the new server. I had over 130 posts to migrate. When I moved them to the new blog on the new server, they looked like new posts. To the unforgiving logic of a computer (that defies common sense and manages to foul up life), this pronouncement of newness is accurate, I have to admitthey were indeed new posts on the new server. So, on the 10th of January, my regular readers who had signed up for updates received over 100 email notifications aboutnew postson my blog. Needless to say I started getting angry emails from my annoyed regulars demanding that I remove their names from mylist.excessive” (as one of them put it). If you were one of those who got excessive emails, please accept my apologies. Rest assured that I have turned off email notifications, and I will look and hard into the innards of my blog before turning it back on. And when I do turn it on, I will prominently provide a link in each message to subscribe or unsubscribe yourself.

As you grow your web footprint and your blog traffic, you are going to have to move to a bigger server. In my case, I decided to go with Arvixe> because of the excellent reviews I found on the web. The decision of what type of hosting you need makes for an interesting topic, which will be my next post.

Blank Screen after Hibernate or Sleep?

Okay, the short answer, increase your virtual memory to more than the size of your physical memory.

Long version now. Recently, I had this problem with my PC that it wouldn’t wake up from hibernation or sleep mode properly. The PC itself would be on and churning, but the screen would switch to power save mode, staying blank. The only thing to do at that point would be to restart the computer.

Like the good netizen that I am, I trawled the Internet for a solution. But didn’t find any. Some suggested upgrading the BIOS, replacing the graphics card and so on. Then I saw this mentioned in a Linux group, saying that the size of the swap file should be more than the physical memory, and decided to try it on my Windows XP machine. And it solved the problem!

So the solution to this issue of blank screen after waking up is to set the size of the virtual memory to something larger than the memory in your system. If you need more information, here is how, in step-by-step form. These instructions apply to a Windows XP machine.

  1. Right-click on “My Computer” and hit “Properties.”
  2. Take a look at the RAM size, and click on the “Advanced” tab.
  3. Click on the “Setting” button under the “Performance” group box.
  4. In the “Performance Options” window that comes up, select the “Advanced” tab.
  5. In the “Virtual Memory” group box near the bottom, click on the “Change” button.
  6. In the “Virtual Memory” window that pops up, set the “Custom Size” to something more than your RAM size (that you saw in step 2). You can set it on any hard disk partition that you have, but if you are going through all these instructions, chances are you have only “C:”. In my case, I chose to put it on “M:”.

How to save a string to a local file in PHP?

Esta postagem é a segunda da minha série geek,,en,Ao programar meu Tema Tweaker,,en,Me deparei com esse problema,,en,Eu tinha uma string no meu servidor no meu programa php,,en,a folha de estilo ajustada,,en,e eu queria dar ao usuário a opção de salvá-lo em um arquivo em seu computador,,en,Eu teria pensado que esse era um problema comum,,en,e todos os problemas comuns podem ser resolvidos no Google,,en,vejam só,,en,Eu simplesmente não conseguia encontrar uma solução satisfatória,,en,Eu encontrei o meu próprio,,en,e pensei em compartilhar aqui,,en,para o benefício de todos os futuros Googlers que ainda virão e partirão,,en,Antes de entrarmos na solução,,en,vamos entender qual é o problema,,en,O problema está na divisão de trabalho entre dois computadores,,en,um é o servidor,,en,onde seu WordPress e PHP estão sendo executados,,en.

While programming my Theme Tweaker, I came across this problem. I had a string on my server in my php program (the tweaked stylesheet, in fact), and I wanted to give the user the option of saving it to a file his computer. I would’ve thought this was a common problem, and all common problems can be solved by Googling. But, lo and behold, I just couldn’t find a satisfactory solution. I found my own, and thought I would share it here, for the benefit of all the future Googlers yet to come and go.

Before we go into the solution, let’s understand what the problem is. The problem is in the division of labor between two computers — one is the server, where your WordPress and PHP are running; o outro é o computador do cliente onde a visualização está ocorrendo,,en,A string de que estamos falando está no servidor,,en,Queremos salvá-lo em um arquivo no computador do cliente,,en,A única maneira de fazer isso é servindo a string como uma resposta html,,en,isso não parece ser um grande problema,,en,servidores enviam regularmente strings e dados para clientes,,en,é assim que vemos qualquer coisa no navegador,,en,incluindo o que você está lendo,,en,Se fosse qualquer programa PHP que deseja salvar a string,,en,não seria um problema,,en,Você pode simplesmente despejar a string em um arquivo no servidor e servir o arquivo,,en,Mas o que você faz se não quiser dar ao mundo uma maneira de despejar strings para arquivos em seu servidor,,en,você poderia fazer algo assim,,en. The string we are talking about is on the server. We want to save it in a file on the client’s computer. The only way to do it is by serving the string as an html reply.

At first glance, this doesn’t look like a major problem. After all, servers regularly send strings and data to clients — that’s how we see anything on the the browser, including what you are reading. If it was just any PHP program that wants to save the string, it wouldn’t be a problem. You could just dump the string into a file on the server and serve the file.

But what do you do if you don’t want to give the whole world a way of dumping strings to files on your server? Well, you could do something like this:

<?php
header('Content-Disposition: attachment; filename="style.css"');
header("Content-Transfer-Encoding: ascii");
header('Expires: 0');
header('Pragma: no-cache');
print $stylestr ;
?>

So, basta colocar este código em seu foo.php que calcula a string $ stylestr e está feito,,en,Mas nosso problema é que estamos trabalhando na estrutura de plug-ins do WordPress,,en,e não pode usar o cabeçalho,,en,chamadas,,en,Quando você tenta fazer isso,,en,você receberá a mensagem de erro dizendo que o cabeçalho já está feito cara,,en,Para este problema,,en,Encontrei a solução engenhosa em um dos plug-ins que uso,,en,Esqueci qual,,en,mas acho que é uma técnica comum,,en,A solução é definir um iFrame vazio e definir sua fonte para o que a função PHP escreveria,,en,Como o iFrame espera uma fonte HTML completa,,en,você esta autorizado,,en,obrigado,,en,dar o cabeçalho,,en,diretivas,,en,O snippet de código é parecido com,,en,Agora a questão é,,en,qual deveria ser a fonte,,en,o que é $ styleurl,,en,Claramente,,en,não vai ser um arquivo estático em seu servidor,,en. But our trouble is that we are working in the WordPress plugin framework, and cannot use the header() calls. When you try to do that, you will get the error message saying that header is already done dude. For this problem, I found the ingenious solution in one of the plugins that I use. Forgot which one, but I guess it is a common technique. The solution is to define an empty iFrame and set its source to what the PHP function would write. Since iFrame expects a full HTML source, you are allowed (in fact, obliged) to give the header() directives. The code snippet looks something like:

<iframe id="saveCSS" src="about:blank" style="visibility:hidden;border:none;height:1em;width:1px;"></iframe>
<script type="text/javascript">
var fram = document.getElementById("saveCSS");
<?php echo 'fram.src = "' . $styleurl .'"' ;
?>

Now the question is, what should the source be? In other words, what is $styleurl? Clearly, it is not going to be a static file on your server. E o objetivo desta postagem é mostrar que não precisa ser um arquivo no servidor,,en,É uma resposta em duas partes,,en,Você tem que lembrar que está trabalhando dentro da estrutura do WordPress,,en,e você não pode criar arquivos php independentes,,en,A única coisa que você pode fazer é adicionar argumentos aos arquivos php existentes,,en,ou os plug-ins que você criou,,en,Então você primeiro cria um botão de envio da seguinte maneira,,en,Observe que o atributo de nome do botão é,,en,saveCSS.,,en,na parte do código que lida com os envios,,en,você faz algo como,,en,Este é o $ styleurl que você forneceria como a fonte do seu iFrame,,en,frente,,sv,Observe que é o mesmo que o URL da página de plug-in,,en,exceto que você conseguiu adicionar,,en,Salve ,,en,no final disso,,en,O próximo truque é capturar esse argumento e lidar com ele,,en,Por isso,,en. It is a two-part answer. You have to remember that you are working within the WordPress framework, and you cannot make standalone php files. The only thing you can do is to add arguments to the existing php files, or the plugins you have created. So you first make a submit button as follows:

<form method="post" action="<?php echo $_SERVER["REQUEST_URI"]?>">
<div class="submit">
<input type="submit" name="saveCSS" title="Download the tweaked stylesheet to your computer" value="Download Stylesheet" />
</div>

Note that the name attribute of the button is “saveCSS.” Now, in the part of the code that handles submits, you do something like:

<?php
if (isset($_POST['saveCSS']))
$styleurl = get_option('siteurl') . '/' . "/wp-admin/themes.php?page=theme-tweaker.php&save" ;

?>

This is the $styleurl that you would give as the source of your iFrame, fram. Note that it is the same as your pluging page URL, except that you managed to add “?save” at the end of it. The next trick is to capture that argument and handle it. For that, você usa a função API do WordPress,,en,add_action as,,en,Isto adiciona uma função saveCSS à parte init do seu plugin,,en,Agora você tem que definir esta função,,en,Agora estamos quase em casa livres,,en,A única coisa a entender é que você,,en,Faz,,en,precisa do dado,,en,Se sua função não morrer,,en,ele vai vomitar o resto do material gerado pelo WordPress em seu arquivo salvo,,en,anexando-o à sua string $ stylestr,,en,Pode parecer complicado,,en,Eu acho que é um pouco complicado,,en,mas depois de implementá-lo e colocá-lo em execução,,en,você pode,,en,e fazer,,en,esqueça isso,,en,eu faço,,en,É por isso que postei aqui,,en,para que da próxima vez eu precise fazer isso,,en,Eu posso pesquisar,,en,php,,en,plugins,,en,corda,,en,wordpress,,en,Presente de Humboldt por Saul Bellow,,en, add_action as:

<?php
if (isset($_GET['save'] ))
add_action('init', array(&$thmTwk, 'saveCSS'));
else
remove_action('init', array(&$thmTwk, 'saveCSS'));
?>

This adds a function saveCSS to the init part of your plugin. Now you have to define this function:

<?php
function saveCSS() {
header('Content-Disposition: attachment; filename="style.css"');
header("Content-Transfer-Encoding: ascii");
header('Expires: 0');
header('Pragma: no-cache');
$stylestr = "Whatever string you want to save";
ob_start() ;
print $stylestr ;
ob_end_flush() ;
die() ;
}
?>

Now we are almost home free. The only thing to understand is that you do need the die(). If your function doesn’t die, it will spew out the rest of the WordPress generated stuff into your save file, appending it to your string $stylestr.

It may look complicated. Well, I guess it is a bit complicated, but once you implement it and get it running, you can (and do) forget about it. At least, I do. That’s why I posted it here, so that the next time I need to do it, I can look it up.