Allowing googlebot to crawl a password protected page
Is this viable

Of course it is viable but as I am pretty sure somehow everyone can fake a googlebot without a detection by your script I don't recommend it. Another aspect is mentioned by 200_success. Google policies dislike such behaviour and it is highly recommend to follow their recommendations. At the end of the answer is a sample of my idea of implementation

Is this code solid/safe

General

It looks like you are developing procedural which is not recommend. OOP (object orientend programming) is the better way to go as it is a modular approach of developing software. In oop there are classes and each has specific task to solve. Wikipedia - Object-oriented-programming

Closing php tag

In the embedded source code you close the php tag which is not recommend. It might happen that a space is after a closing php tag and if you receive a headers already sent error it can be time consuming to identifiy the file where a space is after a closing php tag.

My idea of implementation

Independent of the google policies and that only x of y details should be indexed I would not make a google check but display the x of y details always and the z of y only if a function (e.g. userHasAccess($userid); ) returns true.

Sample

&lt;!DOCTYPE HTML&gt;
&lt;html lang="en"&gt;
    &lt;head&gt;
        &lt;title&gt;Detail&lt;/title&gt;
        &lt;meta name="robots" content="index"&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;h2&gt;User: John Doe&lt;/h2&gt;
        &lt;p&gt;
            A description about John Doe.
        &lt;/p&gt;
        &lt;?php
            if (userHasAccess(2))
            {
                echo "&lt;p&gt;Age: 18&lt;/p&gt;";
            }
        ?&gt;
    &lt;/body&gt;
&lt;/html&gt;


Such an implementation allows other search engines to crawl the x of y details while the z of y details are hidden for every search engine. You don't have to implement a googlebot verfication either.

Of course this sample has to be extended.