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:

$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 power — the 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 balance — the money they had “refunded” to 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 the “gotchas” involved.

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 admit — they 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 about “new posts” on my blog. Needless to say I started getting angry emails from my annoyed regulars demanding that I remove their names from my “list.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?

Этот пост является вторым в моей серии Компьютерщик,,en,Во время программирования моего Theme Tweaker,,en,Я сталкивался с этой проблемой,,en,У меня была строка на моем сервере в моей программе PHP,,en,измененная таблица стилей,,en,и я хотел дать пользователю возможность сохранить его в файл своего компьютера,,en,Я бы подумал, что это общая проблема,,en,и все общие проблемы могут быть решены с помощью Google,,en,и вот,,en,Я просто не мог найти удовлетворительное решение,,en,Я нашел свой,,en,и думал, что я поделюсь этим здесь,,en,на благо всех будущих Googlers еще впереди,,en,Прежде чем мы перейдем к решению,,en,давайте разберемся, в чем проблема,,en,Проблема в разделении труда между двумя компьютерами,,en,один это сервер,,en,где работает ваш WordPress и PHP,,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; другой - клиентский компьютер, на котором происходит просмотр,,en,Строка, о которой мы говорим, находится на сервере,,en,Мы хотим сохранить его в файл на компьютере клиента,,en,Единственный способ сделать это - предоставить строку в виде ответа html.,,en,это не похоже на серьезную проблему,,en,серверы регулярно отправляют строки и данные клиентам,,en,вот как мы видим что-то в браузере,,en,в том числе то, что вы читаете,,en,Если бы это была просто любая PHP-программа, которая хочет сохранить строку,,en,это не будет проблемой,,en,Вы можете просто записать строку в файл на сервере и подать файл,,en,Но что вы делаете, если вы не хотите, чтобы весь мир получал дамп строк в файлы на вашем сервере?,,en,Вы могли бы сделать что-то вроде этого,,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:

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

So, просто поместите этот код в ваш foo.php, который вычисляет строку $ stylestr, и все готово,,en,Но наша проблема в том, что мы работаем в рамках плагина WordPress,,en,и не может использовать заголовок,,en,звонки,,en,Когда вы пытаетесь это сделать,,en,вы получите сообщение об ошибке, говорящее, что заголовок уже сделан чувак,,en,Для этой проблемы,,en,Я нашел гениальное решение в одном из плагинов, которые я использую,,en,Забыл какой,,en,но я думаю, что это обычная техника,,en,Решение состоит в том, чтобы определить пустой iFrame и установить его источник в том, что написала бы функция PHP,,en,Поскольку iFrame ожидает полный исходный код HTML,,en,тебе разрешено,,en,обязан,,en,дать заголовок,,en,директивы,,en,Фрагмент кода выглядит примерно так,,en,Теперь вопрос,,en,каким должен быть источник,,en,что такое $ styleurl,,en,это не будет статический файл на вашем сервере,,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. И цель этого поста - показать, что он вообще не должен быть файлом на сервере.,,en,Это ответ из двух частей,,en,Вы должны помнить, что вы работаете в рамках WordPress,,en,и вы не можете сделать отдельные файлы PHP,,en,Единственное, что вы можете сделать, это добавить аргументы в существующие файлы php,,en,или плагины, которые вы создали,,en,Таким образом, вы сначала делаете кнопку отправки следующим образом,,en,Обратите внимание, что атрибут имени кнопки,,en,saveCSS.,,en,в части кода, которая обрабатывает отправляет,,en,ты делаешь что-то вроде,,en,Это $ styleurl, который вы бы указали в качестве источника вашего iFrame.,,en,фронт,,sv,Обратите внимание, что он совпадает с URL вашей страницы,,en,кроме того, что вам удалось добавить,,en,спасти,,en,в конце этого,,en,Следующий трюк - захватить этот аргумент и обработать его,,en,Для этого,,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" />

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

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, вы используете функцию WordPress API,,en,add_action as,,en,Это добавляет функцию saveCSS в часть инициализации вашего плагина.,,en,Теперь вы должны определить эту функцию,,en,Теперь мы почти дома свободны,,en,Единственное, что нужно понять, это то, что вы,,en,делать,,en,нужно умереть,,en,Если ваша функция не умирает,,en,он выбросит остальную часть сгенерированного WordPress материала в ваш файл сохранения,,en,добавив его в вашу строку $ stylestr,,en,Это может выглядеть сложно,,en,Я думаю, это немного сложно,,en,но как только вы реализуете его и запускаете,,en,и делай,,en,забудь об этом,,en,Вот почему я разместил это здесь,,en,так что в следующий раз мне нужно это сделать,,en,Я могу посмотреть это,,en,PHP,,en,строка,,en,Дар Гумбольдта от Саула Беллоу,,en, add_action as:

if (isset($_GET['save'] ))
add_action('init', array(&$thmTwk, 'saveCSS'));
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:

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.