Tag Archives: plugins

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:

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" />

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, 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:

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.


I have been doing a bit of geeky stuff latelywriting WordPress plugins. Okay, it is because I’m suffering from a terrible writer’s block.

You see, I’m supposed to be working on my next book. I foolishly promised a couple of chapters of The Principles of Quantitative Development to my commissioning editor at John Wiley & Sons within a month; now I find myself writing everything other than those darned chapters! Including plugins. Coming to think of it, writing those chapters wouldn’t be any less geeky, would it?

That made me wonderWe all started off as geeks, didn’t we? No use denying it. Remember how our teachers loved us, and the sexy cheerleaders, well, didn’t? Later in life, due to exigencies of circumstances, we may have tried to lose our techie halo and simulate a managerial posture. But, in our moments of panic, we go back to our geek roots. At least, I do.

You think you don’t? Well, check out these geek jokes. If you find them funny, chances are your roots are not too different from mine.

Heisenberg was driving down the highway when he was pulled over for speeding. The officer says, “Do you know how fast you were going?” Heisenberg says, “No, but I do know where I am!”

Two Hydrogen atoms walk into a bar. One says, “I’ve lost my electron!” The other says, “Are you sure?” The first replies, “Yes, I’m positive…”

Geek Pickup Lines:

  • Tell me of this thing you humans call [dramatic pause] love.
  • If you turn me down now, I will become more drunk than you can possibly imagine.
  • They don’t call me Bones because I’m a doctor.
  • Your name is Leslie? Look, I can spell your name on my calculator!
  • What’s a nice girl like you doing in a wretched hive of scum and villainy like this?
  • You must be Windows 95 because you got me so unstable.
  • My ‘up-timeis better than BSD.
  • I can tell by your emoticons that you’re looking for some company.
  • Is that an iPod mini in your pocket or are you just happy to see me.
  • Want to see my Red Hat?
  • If you won’t let me buy you a drink, at least let me fix your laptop.
  • You had me atHello World.
  • Mind if I run a sniffer to see if your ports are open?
  • You make me want to upgrade my Tivo.
  • By looking at you I can tell you’re 36-25-36, which by the way are all perfect squares.
  • Jedi Mind Trick: “This is the geek you’re looking for.[Waves hand]
  • You can put a Trojan on my Hard Drive anytime.
  • Have you ever Googled yourself?
  • How about we do a little peer-to-peer saliva swapping?
  • With my IQ and your body we could begin a race of genetic superchildren to conquer the earth.
  • What’s a girl like you doing in a place like this when there’s a Farscape marathon on right now on the Sci Fi channel.
  • I’m attracted to you so strongly, scientists will have to develop a fifth fundamental force.

What Makes 100%?

What does it mean to give MORE than 100%? Ever wonder about those people who say they are giving more than 100%? We have all been to those meetings where someone wants you to give over 100%. How about achieving 103%? What makes up 100% in life? Here’s a little mathematical formula that might help you answer these questions:


A B C D E F G H I J K L M N O P Q R S T U V W X Y Z are represented as:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

then H-A-R-D-W-O-R-K = 8+1+18+4+23+15+18+11 = 98%

and K-N-O-W-L-E-D-G-E = 11+14+15+23+12+5+4+7+5 = 96%

but A-T-T-I-T-U-D-E = 1+20+20+9+20+21+4+5 = 100%

and B-U-L-L-S-H-I-T = 2+21+12+12+19+8+9+20 = 103%

but look how far ass kissing will take you.

A-S-S-K-I-S-S-I-N-G = 1+19+19+11+9+19+19+9+14+7 = 118%

So, one can conclude with mathematical certainty that While Hard work and Knowledge will get you close, and Attitude will get you there, it’s the Bullshit and Ass kissing that will put you over the top.