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

This post is the second one in my geek series.

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; the other is the client’s computer where the viewing is taking place. 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, just put this code in your foo.php that computes the string $stylestr and you are done. 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. And the purpose of this post is to show that it doesn’t have to be a file on the server at all. 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, you use the WordPress API function, 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.

Humboldt’s Gift by Saul Bellow

I first found this modern-day classic in my father’s collection some thirty years ago, which meant that he bought it right around the time it was published. Looking back at it now, and after having read the book, as usual, many times over, I am surprised that he had actually read it. May be I am underestimating him in my colossal and unwarranted arrogance, but I just cannot see how he could have followed the book. Even after having lived in the USA for half a dozen years, and read more philosophy than is good for me, I cannot keep up with the cultural references and the pace of Charlie Citrine’s mind through its intellectual twists and turns. Did my father actually read it? I wish I could ask him.

Perhaps that is the point of this book, as it is with most classics — the irreversibility and finality of death. Or may be it is my jaundiced vision painting everything yellow. But Bellow does rage against this finality of death (just like most religions do); he comically postulates that it is our metaphysical denial that hides the immortal souls watching over us. Perhaps he is right; it certainly is comforting to believe it.

There is always an element of parternality in every mentor-protégé relationship. (Forgive me, I know it is a sexist view — why not maternality?) But I probably started this post with the memories of my father because of this perceived element in the Von Humboldt Fleischer – Charlie Citrine relationship, complete with the associated feelings of guilt and remorse on the choices that had to be made.

As a book, Humboldt’s Gift is a veritable tour de force. It is a blinding blitz of erudition and wisdom, coming at you at a pace and intensity that is hard to stand up to. It talks about the painted veil, Maya, the many colored glasses staining the white radiance of eternity, and Hegel’s phenomenology as though they are like coffee and cheerios. To me, this dazzling display of intellectual fireworks is unsettling. I get a glimpse of the enormity of what is left to know, and the paucity of time left to learn it, and I worry. It is the ultimate Catch-22 — by the time you figure it all out, it is time to go, and the knowledge is useless. Perhaps knowledge has always been useless in that sense, but it is still a lot of fun to figure things out.

The book is a commentary on American materialism and the futility of idealism in our modern times. It is also about the small things where a heart finds fulfillment. Here is the setting of the story in a nutshell. Charlie Citrine, a protégé to Von Humboldt Fleischer, makes it big in his literary career. Fleischer himself, full of grandiose schemes for a cultural renaissance in America, dies a failure. Charlie’s success comes at its usual price. In an ugly divorce, his vulturous ex-wife, Denise, tries to milk him for every penny he’s worth. His mercenary mistress and a woman-and-a-half, Renata, targets his riches from other angles. Then there is the boisterous Cantabile who is ultimately harmless, and the affable and classy Thaxter who is much more damaging. The rest of the story follows some predictable, and some surprising twists. Storylines are something I stay away from in my reviews, for I don’t want to be posting spoilers.

I am sure there is a name for this style of narration that jumps back and forth in time with no regard to chronology. I first noticed it in Catch-22 and recently in Arundhati Roy’s God of Small Things. It always fills me with a kind of awe because the writer has the whole story in mind, and is revealing aspects of it at will. It is like showing different projections of a complex object. This style is particularly suited for Humboldt’s Gift, because it is a complex object like a huge diamond, and the different projections show brilliant flashes of insights. Staining the white radiance of eternity, of course.

To say that Humboldt’s Gift is a masterpiece is like saying that sugar is sweet. It goes without saying. I will read this book many more times in the future because of its educational values (and because I love the reader in my audiobook edition). I would not necessarily recommend the book to others though. I think it takes a peculiar mind, one that finds sanity only in insane gibberish, and sees unreality in all the painted veils of reality, to appreciate this book.

In short, you have to be a bit cuckoo to like it. But, by the same convoluted logic, this negative recommendation is perhaps the strongest endorsement of all. So here goes… Don’t read it. I forbid it!

Bushisms

Bush has just left the building. Perhaps the world will be a kinder, gentler place now. But it will certainly be a less funny place. For life is stranger than fiction, and Bush was funnier than any stand-up comedian. Jon Stewart is going to miss him. So will I.

Self Image

“They misunderestimated me.”
Bentonville, Arkansas, 6 November, 2000

“I know what I believe. I will continue to articulate what I believe and what I believe – I believe what I believe is right.”
Rome, 22 July, 2001

“There’s an old saying in Tennessee – I know it’s in Texas, probably in Tennessee – that says, fool me once, shame on… shame on you. Fool me – you can’t get fooled again.”
Nashville, Tennessee, 17 September, 2002

“There’s no question that the minute I got elected, the storm clouds on the horizon were getting nearly directly overhead.”
Washington DC, 11 May, 2001

“I want to thank my friend, Senator Bill Frist, for joining us today. He married a Texas girl, I want you to know. Karyn is with us. A West Texas girl, just like me.”
Nashville, Tennessee, 27 May, 2004

Statemanship

“For a century and a half now, America and Japan have formed one of the great and enduring alliances of modern times.”
Tokyo, 18 February, 2002

“The war on terror involves Saddam Hussein because of the nature of Saddam Hussein, the history of Saddam Hussein, and his willingness to terrorise himself.”
Grand Rapids, Michigan, 29 January, 2003

“Our enemies are innovative and resourceful, and so are we. They never stop thinking about new ways to harm our country and our people, and neither do we.”
Washington DC, 5 August, 2004

“I think war is a dangerous place.”
Washington DC, 7 May, 2003

“The ambassador and the general were briefing me on the – the vast majority of Iraqis want to live in a peaceful, free world. And we will find these people and we will bring them to justice.”
Washington DC, 27 October, 2003

“Free societies are hopeful societies. And free societies will be allies against these hateful few who have no conscience, who kill at the whim of a hat.”
Washington DC, 17 September, 2004

“You know, one of the hardest parts of my job is to connect Iraq to the war on terror.”
CBS News, Washington DC, 6 September, 2006

Education

“Rarely is the question asked: Is our children learning?”
Florence, South Carolina, 11 January, 2000

“Reading is the basics for all learning.”
Reston, Virginia, 28 March, 2000

“As governor of Texas, I have set high standards for our public schools, and I have met those standards.”
CNN, 30 August, 2000

“You teach a child to read, and he or her will be able to pass a literacy test.”
Townsend, Tennessee, 21 February, 2001

Economics

“I understand small business growth. I was one.”
New York Daily News, 19 February, 2000

“It’s clearly a budget. It’s got a lot of numbers in it.”
Reuters, 5 May, 2000

“I do remain confident in Linda. She’ll make a fine Labour Secretary. From what I’ve read in the press accounts, she’s perfectly qualified.”
Austin, Texas, 8 January, 2001

“First, let me make it very clear, poor people aren’t necessarily killers. Just because you happen to be not rich doesn’t mean you’re willing to kill.”
Washington DC, 19 May, 2003

Health

“I don’t think we need to be subliminable about the differences between our views on prescription drugs.”
Orlando, Florida, 12 September, 2000

“Too many good docs are getting out of the business. Too many OB/GYN’s aren’t able to practice their love with women all across the country.”
Poplar Bluff, Missouri, 6 September, 2004

Internet

“Will the highways on the internet become more few?”
Concord, New Hampshire, 29 January, 2000

“It would be a mistake for the United States Senate to allow any kind of human cloning to come out of that chamber.”
Washington DC, 10 April, 2002

“Information is moving. You know, nightly news is one way, of course, but it’s also moving through the blogosphere and through the Internets.”
Washington DC, 2 May, 2007

What the…?

“I know the human being and fish can coexist peacefully.”
Saginaw, Michigan, 29 September, 2000

“Families is where our nation finds hope, where wings take dream.”
LaCrosse, Wisconsin, 18 October, 2000

“Those who enter the country illegally violate the law.”
Tucson, Arizona, 28 November, 2005

“That’s George Washington, the first president, of course. The interesting thing about him is that I read three – three or four books about him last year. Isn’t that interesting?”
Speaking to reporter Kai Diekmann, Washington DC, 5 May, 2006

Leadership

“I have a different vision of leadership. A leadership is someone who brings people together.”
Bartlett, Tennessee, 18 August, 2000

“I’m the decider, and I decide what is best.”
Washington DC, 18 April, 2006

“And truth of the matter is, a lot of reports in Washington are never read by anybody. To show you how important this one is, I read it, and [Tony Blair] read it.”
On the publication of the Baker-Hamilton Report, Washington DC, 7 December, 2006

“All I can tell you is when the governor calls, I answer his phone.”
San Diego, California, 25 October, 2007

Famous Last Words

“I’ll be long gone before some smart person ever figures out what happened inside this Oval Office.”
Washington DC, 12 May, 2008

The Razor’s Edge by W Somerset Maugham

May be it is only my tendency to see philosophy everywhere, but I honestly believe Maugham’s works are the classics they are because of their deep philosophical underpinnings. Their strong plots and Maugham’s masterful storytelling help, but what makes them timeless is the fact that Maugham gives voice to the restlessness of our hearts, and puts in words the stirring uncertainties of our souls. Our questions have always been the same. Where do we come from? What are we doing here? And where are we headed? Quo vadis?

Of all the books of this kind that I have read, and I have read many, The Razor’s Edge takes on the last question most directly. When Larry says, out of the blue, “The dead look so awfully dead.” we get an idea of what his quest, and indeed the inquiry of the book, is going to be.

Larry Darrell is as close to human flawlessness as Maugham ever gets. His cynical disposition always produced vivid characters that were flawed human beings. We are used to snobbishness in Elliott Templeton, fear and hypocrisy in the vicar of Blackstable, self-loathing even in the self-image of Philip Carey, frivolity in Kitty Garstin, undue sternness in Walter Fane, the ludicrous buffoonery of Dirk Stroeve, abysmal cruelty in Charles Strickland, ultimate betrayal in Blanche Stroeve, fatal alcoholism in Sophie, incurable promiscuity in Mildred — an endless parade of gripping characters, everyone of them as far from human perfection as you and me.

But human perfection is what is sought and found in Larry Darrell. He is gentle, compassionate, single-mindedly hardworking, spiritually enlightened, simple and true, and even handsome (although Maugham couldn’t help but bring in some reservations about it). In one word, perfect. So it is only with an infinite amount of vanity that anybody can identify himself with Larry (as I secretly do). And it is a testament to Maugham’s mastery and skill that he could still make such an idealistic character human enough for some people to see themselves in him.

As I plod on with these review posts, I’m beginning to find them a bit useless. I feel that whatever needed to be said was already well said in the books to begin with. And, the books being classics, others have also said much about them. So why bother?

Let me wind up this post, and possibly this review series, with a couple of personal observations. I found it gratifying that Larry finally found enlightenment in my native land of Kerala. Written decades before the hippie exodus for spiritual fulfillment in India, this book is remarkably prescient. And, as a book on what life is all about, and how to live it to its spiritual fullness in our hectic age, The Razor’s Edge is a must read for everybody.

House of Cards

We are in dire straits — no doubt about it. Our banks and financial edifices are collapsing. Those left standing also look shaky. Financial industry as a whole is battling to survive. And, as its front line warriors, we will bear the brunt of the bloodbath sure to ensue any minute now.

Ominous as it looks now, this dark hour will pass, as all the ones before it. How can we avoid such dark crises in the future? We can start by examining the root causes, the structural and systemic reasons, behind the current debacle. What are they? In my series of posts this month, I went through what I thought were the lessons to learn from the financial crisis. Here is what I think will happen.

The notion of risk management is sure to change in the coming years. Risk managers will have to be compensated enough so that top talent doesn’t always drift away from it into risk taking roles. Credit risk paradigms will be reviewed. Are credit limits and ratings the right tools? Will Off Balance Sheet instruments stay off the balance sheet? How will we account for leveraging?

Regulatory frameworks will change. They will become more intrusive, but hopefully more transparent and honest as well.

Upper management compensation schemes may change, but probably not much. Despite what the techies at the bottom think, those who reach the top are smart. They will think of some innovative ways of keeping their perks. Don’t worry; there will always be something to look forward to, as you climb the corporate ladder.

Nietzsche may be right, what doesn’t kill us, may eventually make us stronger. Hoping that this unprecedented financial crisis doesn’t kill us, let’s try to learn as much from it as possible.

Sections

Free Market Hypocrisy

Markets are not free, despite what the text books tell us. In mathematics, we verify the validity of equations by considering asymptotic or limiting cases. Let’s try the same trick on the statement about the markets being free.

If commodity markets were free, we would have no tariff restrictions, agricultural subsidies and other market skewing mechanisms at play. Heck, cocaine and heroine would be freely available. After all, there are willing buyers and sellers for those drugs. Indeed, drug lords would be respectable citizens belonging in country clubs rather than gun-totting cartels.

If labor markets were free, nobody would need a visa to go and work anywhere in the world. And, “equal pay for equal work” would be a true ideal across the globe, and nobody would whine about jobs being exported to third world countries.

Capital markets, at the receiving end of all the market turmoil of late, are highly regulated with capital adequacy and other Basel II requirements.

Derivatives markets, our neck of the woods, are a strange beast. It steps in and out of the capital markets as convenient and muddles up everything so that they will need us quants to explain it to them. We will get back to it in future columns.

So what exactly is free about the free market economy? It is free — as long as you deal in authorized commodities and products, operate within prescribed geographies, set aside as much capital as directed, and do not employ those you are not supposed to. By such creative redefinitions of terms like “free,” we can call even a high security prison free!

Don’t get me wrong. I wouldn’t advocate making all markets totally free. After all, opening the flood gates to the formidable Indian and Chinese talent can only adversely affect my salary levels. Nor am I suggesting that we deregulate everything and hope for the best. Far from it. All I am saying is that we need to be honest about what we mean by “free” in free markets, and understand and implement its meaning in a transparent way. I don’t know if it will help avoid a future financial meltdown, but it certainly can’t hurt.

Sections

Quant Culprits

Much has been said about the sins of the quants in their inability to model and price credit derivatives, especially Collateralized Debt Obligations (CDOs) and Mortgage Backed Securities (MBSs). In my opinion, it is not so much of a quant failure. After all, if you have the market data (especially default correlations) credit derivatives are not all that hard to price.

The failure was really in understanding how much credit and market risks were inter-related, given that they were independently managed using totally different paradigms. I think an overhauling is called for here, not merely in modeling and pricing credit risks, also in the paradigms and practices used in managing them.

Ultimately, we have to understand how the whole lifecycle of a trade is managed, and how various business units in a financial institution interact with each other bearing one common goal in mind. It is this fascination of mine with the “big picture” that inspired me to write The Principles of Quantitative Development, to be published by Wiley Finance in 2010.

Sections

Where Credit is Due

While the market risk managers are getting grilled for the financial debacle we are in, the credit controllers are walking around with that smug look that says, “Told you so!” But systemic reasons for the financial turmoil hide in our credit risk management practices as well.

We manage credit risk in two ways — by demanding collateral or by credit limit allocation. In the consumer credit market, they correspond to secure lending (home mortgages, for instance) and unsecured loans (say, credit lines). The latter clearly involves more credit risk, which is why you pay obscene interests on outstanding balances.

In dealing with financial counterparties, we use the same two paradigms. Collateral credit management is generally safe because the collateral involved cannot be used for multiple credit exposures. But when we assign each counterparty a credit limit based on their credit ratings, we have a problem. While the credit rating of a bank or a financial institution may be accurate, it is almost impossible to know how much credit is loaded against that entity (because options and derivatives are “off balance sheet” instruments). This situation is akin to a bank’s inability to check how much you have drawn against your other credit lines, when it offers you an overdraft facility.

The end result is that even in good times, the leverage against the credit rating can be dangerously high without counterparties realizing it. The ensuing painful deleveraging takes place when a credit event (such as lowering of the credit rating) occurs.

Sections

Hedging Dilemma

Ever wonder why those airfares are quick to climb, but slow to land? Well, you can blame the risk managers.

When the oil price hit $147 a barrel in July ’08, with all the pundits predicting sustained $200 levels, what would you have done if you were risk managing an airline’s exposure to fuel? You would have ran and paid an arm and a leg to hedge it. Hedging would essentially fix the price for your company around $150 level, no matter how the market moved. Now you sit back and relax, happy in the knowledge that you saved your firm potentially millions of dollars.

Then, to your horror, the oil price nosedives, and your firm is paying $100 more than it should for each barrel of oil. (Of course, airlines don’t buy WTI, but you know what I mean.) So, thanks to the risk managers’ honest work, airlines (and even countries) are now handing over huge sums of money to energy traders. Would you rather be a trader or a risk manager?

And, yes, the airfares will come down, but not before the risk managers take their due share of flak.

Sections

Risky Business

Just as 9/11 was more of an intelligence failure rather than a security lapse, the subprime debacle is a risk management breakdown, not merely a regulatory shortcoming. To do anything useful with this rather obvious insight, we need to understand why risk management failed, and how to correct it.

Risk management should be our first line of defense — it is a preventive mechanism, while regulatory framework (which also needs beefing up) is a curative, reactive second line.

The first reason for the inadequacy of risk management is the lack of glamour the risk controllers in a financial institution suffer from, when compared to their risk taking counterparts. (Glamour is a euphemism for salary.) If a risk taker does his job well, he makes money. He is a profit centre. On the other hand, if a risk controller does his job well, he ensures that the losses are not disproportionate. But in order to limit the downside, the risk controller has to limit the upside as well.

In a culture based on performance incentives, and where performance is measured in terms of profit, we can see why the risk controller’s job is sadly under-appreciated and under-compensated.

This imbalance has grave implications. It is the conflict between the risk takers and risk managers that enforces the corporate risk appetite. If the gamblers are being encouraged directly or indirectly, it is an indication of where the risk appetite lies. The question then is, was the risk appetite a little too strong?

The consequences of the lack of equilibrium between the risk manager and the risk taker are also equally troubling. The smarter ones among the risk management group slowly migrate to “profit generating” (read trading or Front Office) roles, thereby exacerbating the imbalance.

The talent migration and the consequent lack of control are not confined merely within the walls of a financial institution. Even regulatory bodies could not compete with the likes of Lehman brothers when hunting for top talent. The net result was that when the inevitable meltdown finally began, we were left with inadequate risk management and regulatory defenses.

Sections