title: Detect in-app browser (WebView) with PHP / Javascript
body: <p>I developed an app for iOS and Android which accesses an HTML file from my webserver using the in-app browser (Webview).</p>
  
  <p>I don't want that a user can access this file without using the app. Is there a possibility to detect, if the user is accessing the file with the app or directly via a browser on this smartphone / tablet / computer? I think that a solution with PHP is much better, because Javascript can be switched off. At least Google Analytics can differentiate between Safari and Safari (in-app). It should work with every version of iOS and Android.</p>
  
  <p>Thanks for your help.</p>
  
  <hr>
  
  <p><strong>Solution</strong></p>
  
  <p>After many attempts I finally found a working solution for me!</p>
  
  <p><strong>iOS:</strong>
  You can detect the difference between Safari and the in-app browser using the user agent. Probably there's a nicer solution, but it works.</p>
  
  <pre><code>// Safari (in-app)
  if ((strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile/') !== false) &amp;&amp; (strpos($_SERVER['HTTP_USER_AGENT'], 'Safari/') == false) {
      echo 'Safari (in-app)';
  }
  </code></pre>
  
  <p><strong>Android:</strong>
  The package name from the app is stored in the PHP variable <code>$_SERVER['HTTP_X_REQUESTED_WITH']</code>.</p>
  
  <pre><code>// Android (in-app)
  if($_SERVER['HTTP_X_REQUESTED_WITH'] == "com.company.app") {
      echo 'Android (in-app)';
  }
  </code></pre>
  
  <p>As Tim van Elsloo already noted HTTP headers can be faked and this is not absolutely secure.</p>