<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>AskApache &#187; Search Results  &#187;  umask</title>
	<atom:link href="http://www.askapache.com/search/umask/feed/rss2/" rel="self" type="application/rss+xml" />
	<link>http://www.askapache.com</link>
	<description>Advanced Web Development</description>
	<lastBuildDate>Sun, 29 Jan 2012 12:04:08 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Enhanced printenv Script for Server Debugging</title>
		<link>http://www.askapache.com/hosting/enhanced-printenv.html</link>
		<comments>http://www.askapache.com/hosting/enhanced-printenv.html#comments</comments>
		<pubDate>Thu, 14 Apr 2011 19:05:17 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[Hosting]]></category>

		<guid isPermaLink="false">http://www.askapache.com/?p=4920</guid>
		<description><![CDATA[<p>A souped-up version of the Apache printenv script for hard-core server environment debuggery.</p>
<pre>
#!/bin/sh
echo -e "Content-type: text/plain\n\n"
...
  __T "CURRENT PROCESS CMDLINE"
  {
   for p in `echo /proc/[0-9]*/cmdline`;
   do
    pid=${p:6:$((${#p}-13))}
    [[ $pid == $PPID &#124;&#124; $pid == $$ ]] &#38;&#38; continue;
    __M "[ /proc/$pid ]";
    sed 's/\x00/ /g;G' $p 2>/dev/null
   done
  }
 fi</pre>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.askapache.com/hosting/enhanced-printenv.html"></a><a href="http://www.askapache.com/hosting/enhanced-printenv.html"><cite>AskApache.com</cite></a></p><p>Every Apache server comes pre-shipped with an old cgi script named <tt>printenv</tt>.  It's useful and used for printing out the environment variables from your servers point of view.  Basically you save this file where you can then call it from your browser, like <code>site.com/printenv.cgi</code> -- then it will be executing as the user running the web server, <tt>nobody</tt>, <tt>apache</tt>, etc..   So this tells you all sorts of interesting things about your server, especially if you want/need to know about the users, groups, and file permissions.</p>

<h2>Enabling CGI</h2>
<p>You need to do 1 of 2 things to use this:</p>
<ol><li>Make it executable and in your server directory</li>
<li>Use a trick to cause your server to execute it regardless</li></ol>

<h2>Htaccess CGI</h2>
<p>If you have htaccess then you most likely can get this to work by giving it an execute bit with chmod or from your ftp client, and then use htaccess like this:</p>
<pre>Options +ExecCGI Indexes +FollowSymLinks
AddHandler cgi-script .cgi .pl .sh
&nbsp;
Order Deny,Allow
Deny from All
Allow from 127.0.0.1 ADDYOURIPHERE env=REDIRECT_STATUS
Satisfy All</pre>
<p>Search around on this site for php.cgi tricks if you can't seem to get it.  Basically you can try stuff like making it an errordocument, using other directives like forcetype, AddType, and even try stuff like mod_security's upload binary setting.</p>

<p class="cnote">You do not want anyone other than you ever looking at the output of this.  It's so full of details about your machine that it would be a huge security problem.</p>

<h2>The AskApache Printenv</h2>
<pre>#!/bin/sh
echo -e "Content-type: text/plain\n\n"
&nbsp;
# FUNCTIONS
################################################################################################################
function __A ()
{ local __a __i __z;for __a;do __z=\${!${__a}*};for __i in `eval echo "${__z}"`;do echo -e "$__i: ${!__i}";done;done; }
&nbsp;
function __S ()
{ local L IFS=&#039;;&#039;;while read -r L;do builtin printf "${#L}@%s\n" "$L";done|sort -n|sed -u &#039;s/^[^@]*//&#039;; }
&nbsp;
function __P ()
{ local l=`builtin printf %${2:-$__WIDTH}s` &amp;&amp; echo -e "${l// /${1:-=}}"; }
&nbsp;
function __T ()
{ echo -e "\n\n+`__P -`+\n| $*\n+`__P &#039;=&#039;`+"; }
&nbsp;
function __M ()
{ echo -e " &gt;&gt;&gt; $M" $*; }
&nbsp;
function __H ()
{ command builtin type $1 &amp;&gt;/dev/null &amp;&amp; local a="yes" || return 1; }
&nbsp;
function LE ()
{
 [[ ! -r /proc/${1:-$$}/limits ]] &amp;&amp; return;
 sed -e &#039;1z;s/ *$//;:a;$!N;s/\nM.. [a-z]* [a-z]* [a-z]* \{1,\}\([^ ]*\) *\([^ ]*\) *[a-z]* */\1:\2 /;ta;s/u\w\+d/u/g;s/ *$//;s/ / | /g;s/\([^:]\+\):\1/\1:=/g&#039; /proc/${1:-$$}/limits;
}
function LH ()
{
 [[ ! -r /proc/${1:-$$}/limits ]] &amp;&amp; return;
 sed -e &#039;1z;s/ *$//;:a;$!N;s/\nM.. \([a-z]\+ [a-z]* [a-z]*\) \{1,\}\([^ ]*\) *\([^ ]*\) *\([a-z]*\) */:\1/;ta;s/ *:/:/g;s/size/sz/g;s/file/f/g;s/ p\w\+y/ pri/g;s/memory/mem/g;s/p\w\+s/procs/g;s/^://;s/:/ | /g&#039; /proc/${1:-$$}/limits
}
&nbsp;
# CUSTOM SETTINGS
################################################################################################################
__WIDTH=170
LC_COLLATE=C LC_CTYPE=C LC_ALL=C
&nbsp;
# RUNTIME SETUP
#################################################################################################################
shopt -s dotglob nocaseglob extglob
&nbsp;
# -C If set, disallow existing regular files to be overwritte
# -f Disable file name generation (globbing
# -e Exit immediately if a command exits with a non-zero status
# -B enable brace expansion
# +H disable History
set -C +f +H -B
&nbsp;
# make sure we dont create any files
umask 0177
&nbsp;
# redirect everything to output (no logs or stderr is used)
exec 2&gt;/dev/null
&nbsp;
# MAIN EXECUTION
#################################################################################################################
{
 __T "EXPANDING PATH"
 {
  __M "ORIG PATH:$PATH"
  PATH=$PATH:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/usr/libexec:/usr/local/apache/bin
  for t in ${PATH//:/ };
  do
   [[ -d "$t" ]] &amp;&amp; sed -n -e "/:${t//\//\\/}:/Q1" &lt;&lt;&lt; ":${p:=}:" &amp;&amp; p=$p:$t || continue;
  done
  PATH=${p/:/}:.
  __M "NEW PATH:$PATH"
 }
&nbsp;
 __T "USER INFO"
 {
  __M "UMASK: `(umask 2&gt;/dev/null)` ( `(umask -S 2&gt;/dev/null)` )"
  __H uname &amp;&amp; __M "UNAME: `eval echo $(uname -a 2&gt;/dev/null)`"
  __H whoami &amp;&amp; __M "WHOAMI: `(whoami 2&gt;/dev/null)`"
  __H id &amp;&amp; __M "ID: `(id 2&gt;/dev/null)`"
  __H logname &amp;&amp; __M "LOGNAME: `(logname 2&gt;/dev/null)`"
  __H groups &amp;&amp; __M "GROUPS: `(groups 2&gt;/dev/null)`"
  echo -e "\n\n"
 }
&nbsp;
 if __H who;
 then
  __T "LOGGED ON USERS"
  {
   (who -a 2&gt;/dev/null)
  }
 fi;
&nbsp;
 if [[ -r /etc/passwd ]];
 then
  __T "/etc/passwd"
  {
   (cat /etc/passwd)
  }
 fi;
&nbsp;
 if __H ulimit;
 then
  __T "USER LIMITS"
  {
   ulimit -a
  }
 fi
&nbsp;
 if [[ -d /dev ]] &amp;&amp; __H ls;
 then
  __T "/dev Directory"
  {
   ( ls -vlaph /dev 2&gt;/dev/null )
  }
 fi;
&nbsp;
 if [[ -d /proc ]];
 then
  __T "CURRENT PROCESS LIMITS"
  {
   for p in `echo /proc/[0-9]*/limits`
   do
    pid=${p:6:$((${#p}-13))}
    [[ $pid == $PPID || $pid == $$ ]] &amp;&amp; continue;
    echo -e "\n/proc/$pid:"
    sed &#039;1s/\x00/ /g;n;s/\x00/\n/g;/.\{2,\}/!d&#039; /proc/$pid/cmdline $p 2&gt;/dev/null
   done
  }
&nbsp;
  __T "CURRENT PROCESS CMDLINE"
  {
   for p in `echo /proc/[0-9]*/cmdline`;
   do
    pid=${p:6:$((${#p}-13))}
    [[ $pid == $PPID || $pid == $$ ]] &amp;&amp; continue;
    __M "[ /proc/$pid ]";
    sed &#039;s/\x00/ /g;G&#039; $p 2&gt;/dev/null
   done
  }
 fi
&nbsp;
 __T "IP INFORMATION"
 {
  __H ip &amp;&amp; __M "IP:" &amp;&amp; (ip -o -f inet addr 2&gt;/dev/null) | sed &#039;s/^.*inet \([0-9.]*\).*$/\1/g&#039;;
  __H nmap &amp;&amp; __M "NMAP:" &amp;&amp; (nmap --iflist 2&gt;/dev/null) | sed 1,4d | sed -n &#039;/ethernet/s/^.*) \([0-9.]*\).*$/\1/gp&#039;;
  __H ifconfig &amp;&amp; __M "IFCONFIG:" &amp;&amp; (ifconfig -a 2&gt;/dev/null) | sed -n &#039;/inet a/s/^.*addr:\([0-9.]*\).*$/\1/gp&#039;;
  [[ -f "$HOME/.cpanel/datastore/_sbin_ifconfig_-a" ]] &amp;&amp; __M "CPANEL CACHE:" &amp;&amp; sed -e &#039;/inet/!d; s/.*addr:\([0-9\.]*\).*/\1/g&#039; "$HOME/.cpanel/datastore/_sbin_ifconfig_-a" | sort -u
 }
&nbsp;
 __T "ROUTE / INTERFACE INFO"
 {
  __H route &amp;&amp; __M "ROUTE" &amp;&amp; (route -nv 2&gt;/dev/null)
  __H ip &amp;&amp; ( ip rule &amp;&amp; ip route &amp;&amp; ip address ) 2&gt;/dev/null
  __H ifconfig &amp;&amp; (ifconfig -a 2&gt;/dev/null)
 }
&nbsp;
 __T "CGI/1.0 test script report:"
 {
  __A SERVER REQUEST GET SERVER PATH REMOTE AUTH CONTENT HTTP TZ GATEWAY QUERY MO
  echo -e "\n\n"
 }
&nbsp;
 __T "HIDDEN VARIABLES"
 {
  __A {a..z} {A..Z} _{0..9} _{A..Z} _{a..z} | cat -Tsv 2&gt;/dev/null
  echo -e "\n\n"
 }
&nbsp;
 __T "DECLARE INFO"
 {
  for i in "r" "i" "a" "x" "t" "-";
  do
   builtin eval declare -$i &amp;&amp; echo;
  done | sed &#039;s/^declare //&#039; | cat -Tsv 2&gt;/dev/null
  echo -e "\n\n"
 }
&nbsp;
 __T "SHELL OPTIONS"
 {
  __A SHELLOPTS BASHOPTS
  echo -e "\$-: $-"
  __P &#039;-&#039; &amp;&amp; builtin shopt -s -p
  __P &#039;-&#039; &amp;&amp; builtin shopt -u -p
  echo -e "\n\n"
 }
&nbsp;
 __T "ENV AND EXPORT"
 {
  __H env &amp;&amp; command env | cat -Tsv 2&gt;/dev/null &amp;&amp; __P &#039;-&#039;
  builtin export | cat -Tsv 2&gt;/dev/null
  echo -e "\n\n"
 }
&nbsp;
 if __H perl;
 then
  __T "PERL VARIABLES"
  {
   perl -e&#039;foreach $v (sort(keys(%ENV))) {$vv = $ENV{$v};$vv =~ s|\n|\\n|g;$vv =~ s|"|\\"|g;print "${v}=\"${vv}\"\n"}&#039; | cat -Tsv 2&gt;/dev/null
   echo -e "\n\n"
  }
 fi
&nbsp;
} | fold - -w$(($__WIDTH+3))
exit $?</pre><p><a href="http://www.askapache.com/hosting/enhanced-printenv.html"></a><a href="http://www.askapache.com/hosting/enhanced-printenv.html">Enhanced printenv Script for Server Debugging</a> originally appeared on <cite>AskApache.com</cite> </p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/hosting/enhanced-printenv.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Creating an Offline Version of Page</title>
		<link>http://www.askapache.com/php/scrape-offline-page-curl.html</link>
		<comments>http://www.askapache.com/php/scrape-offline-page-curl.html#comments</comments>
		<pubDate>Fri, 22 Oct 2010 20:06:49 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.askapache.com/?p=4708</guid>
		<description><![CDATA[<p><a class="IFL" href="http://www.askapache.com/php/scrape-offline-page-curl.html"><img src="http://uploads.askapache.com/2010/10/askapache-scraper-350x89.png" alt="I can do anything" title="askapache-scraper" width="350" height="89" class="size-medium wp-image-4709" /></a>So, here's what I hacked together last night, that is being used today.  It's essentially 2 files.<br class="C" /></p>
<ol>
<li>A php file that scrapes uses curl to scrape all the urls for the page (favicon, css, images, pdfs, etc..)</li>
<li>A simple bash shell script acting as a cgi that creates a zip file of all the urls, and a self-extracting exe file for those without a winzip tool</li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.askapache.com/php/scrape-offline-page-curl.html"></a><a href="http://www.askapache.com/php/scrape-offline-page-curl.html"><cite>AskApache.com</cite></a></p><p>A large client has a secure website where they assemble and create presentations consisting of a single Table of Contents page with many pdf's attached to it.  They use the site to make presentations.  This is a big client, a rich client, and they needed a way to guarantee they would be able to access the site.  So I got this request:</p>

<blockquote>Can you make an offline version of the Page that is always updated and available for download so we can download the offline version and present using that in case the website is down or more often, in case Internet Access is unavailable?</blockquote>

<p class="anote"><strong>Update</strong>: I used <strong>COOKIE</strong> based authentication to secure this clients site, so that only logged in users can see anything at all, so how do I enable the curl requests to authenticate as well using the COOKIE of the requesting user in each request made by curl?  Just add the users HTTP_COOKIE to the headers array used by curl like so:</p>
<pre>array(
...
"Cookie: {$_SERVER[&#039;HTTP_COOKIE&#039;]}"
)</pre>
<p>That now means the scraped version of the page is an exact duplicate that the user is looking at.  Very sweet!</p>


<h2>I can GET anything</h2>
<p><a class="IFL" href="http://www.askapache.com/php/scrape-offline-page-curl.html"><img src="http://uploads.askapache.com/2010/10/askapache-scraper-350x89.png" alt="I can do anything" title="askapache-scraper" width="350" height="89" class="size-medium wp-image-4709" /></a>So, here's what I hacked together last night, that is being used today.  It's essentially 2 files.<br class="C" /></p>
<ol>
<li>A php file that scrapes uses curl to scrape all the urls for the page (favicon, css, images, pdfs, etc..)</li>
<li>A simple bash shell script acting as a cgi that creates a zip file of all the urls, and a self-extracting exe file for those without a winzip tool</li>
</ol>


<h2>The PHP File</h2>
<p>This is a simple script that is given 2 parameters:</p>
<ol>
<li>The url to scrape</li>
<li>The type of download to return</li>
</ol>


<h3>scrapeit.php</h3>
<pre>&lt;?php
ob_start();
&nbsp;
/**
* gogeturl2() - grabs a url with curl, and saves it to disk, works for all media types, pdf, js, img, etc.
*
* @return
*/
function gogeturl2($url, $saveto)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
if ($fp = fopen($saveto, &#039;w&#039;)) // {curl_setopt($ch,CURLOPT_STDERR, $fp); curl_setopt($ch,CURLOPT_VERBOSE,1);}
{
  curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
  curl_setopt($ch, CURLOPT_MAXCONNECTS, 4);
  curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
  curl_setopt($ch, CURLOPT_FAILONERROR, 1);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
  curl_setopt($ch, CURLOPT_FILE, $fp);
  curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3",
    "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5",
    "Accept-Language: en-us,en;q=0.5",
    "Accept-Encoding: none",
    "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7",
    "Keep-Alive: 300",
    "Connection: Keep-Alive",
    "Pragma:"));
  $r = curl_exec($ch);
  $ch_info = curl_getinfo($ch);
  if (curl_errno($ch)) error_log(print_r($ch_info, 1) . print_r(curl_errno($ch), 1) . print_r(curl_error($ch), 1));
  else curl_close($ch);
  fclose($fp);
}
}
/**
* gogeturl()  returns the source of the requested url (thanks to accept-encoding: none)
*
* @return
*/
function gogeturl($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_MAXCONNECTS, 4);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 GTB6",
  "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
  "Accept-Language: en-us,en;q=0.5",
  "Accept-Encoding: none",
  "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7",
  "Keep-Alive: 115",
  "Connection: keep-alive",
  "Pragma:"));
$g = curl_exec($ch);
if (curl_errno($ch)) error_log(print_r(array(
&#039;chinfo&#039; =&gt; $ch_info,
&#039;curl_errno&#039; =&gt; curl_errno($ch),
&#039;curl_error&#039; =&gt; curl_error($ch)
), 1));
curl_close($ch);
return $g;
}
&nbsp;
/**
* _mkdir() makes a directory
*
* @return
*/
function _mkdir($path, $mode = 0755)
{
$old = umask(0);
$res = @mkdir($path, $mode);
umask($old);
return $res;
}
&nbsp;
/**
* rmkdir()  recursively makes a directory tree
*
* @return
*/
function rmkdir($path, $mode = 0755)
{
return is_dir($path) || (rmkdir(dirname($path), $mode) &amp;&amp; _mkdir($path, $mode));
}</pre>

<p>The following should be in a couple functions, but I was running on a tight time schedule, and hey this $hitt aint free... wait yes it is, always.</p>
<pre>// Ok lets get it on!
// first lets setup some variables
if (!isset($_GET[&#039;url&#039;]) || empty($_GET[&#039;url&#039;]))die();
$td = $th = $urls = array();
$FDATE = date("m-d-y-Hms");
$FTMP = &#039;/home/askapache/sites/askapache.com/tmp&#039;;
$fetch_url = $_GET[&#039;url&#039;];
$fu = parse_url($fetch_url);
$fd = substr($FTMP . $fu[&#039;path&#039;], 0, - 1);
$FEXE = "{$fd}-{$FDATE}.exe";
$FZIP = "{$fd}-{$FDATE}.zip";
&nbsp;
// now this is a shortcut to download the css file and add all the images in it to the img_urls array
$img_urls = array();
$gg = preg_match_all("/url\(([^\)]*?)\)/Ui", gogeturl(&#039;https://www.askapache.com/askapache-0128770124.css&#039;), $th);
$imgs = array_unique($th[1]);
foreach($imgs as $img)
{
// only because all the links are relative
$img_urls[] = &#039;https://www.askapache.com&#039; . $img;
}
&nbsp;
// now fetch the main page, and assemble an array of all the external resources into the urls array
$gg = preg_match_all("/(background|href)=([\"\&#039;])([^\"\&#039;#]+?)([\"\&#039;])/Ui", gogeturl($fetch_url), $th);
foreach($th[3] as $url)
{
if (strpos($url, &#039;.js&#039;) !== false)continue;
if (strpos($url, &#039;wp-login.php&#039;) !== false || $url == &#039;https://www.askapache.com/&#039;) continue;
if (strrpos($url, &#039;/&#039;) == strlen($url) - 1)continue;
if (strpos($url, &#039;https://www.askapache.com/&#039;) === false)
{
  if ($url[0] == &#039;/&#039;) $urls[] = &#039;https://www.askapache.com&#039; . $url;
  else continue;
}
else $urls[] = $url;
}
&nbsp;
// now create a uniq array of urls, then download and save each of them
$urls = array_merge(array_unique($img_urls), array_unique($urls));
foreach($urls as $url)
{
  $pu = parse_url($url);
  rmkdir(substr($fd . $pu[&#039;path&#039;], 0, strrpos($fd . $pu[&#039;path&#039;], &#039;/&#039;)));
  gogeturl2($url, $fd . $pu[&#039;path&#039;]);
}
&nbsp;
// deletes dir ie. /this-page/this-page/ when it should be /this-page/index.html
if (is_dir($fd . $fu[&#039;path&#039;])) rmdir($fd . $fu[&#039;path&#039;]);
&nbsp;
// now save the page as index.html
gogeturl2($fetch_url, $fd . &#039;/index.html&#039;);
&nbsp;
// fixup to be able3 to parse
$g = file_get_contents($fd . &#039;/index.html&#039;);
$g = str_replace(&#039;&lt;script&#039;, &#039;&lt;!--&lt;script&#039;, $g);
$g = str_replace(&#039;script&gt;&#039;, &#039;script&gt;!--&gt;&#039;, $g);
$g = str_replace(&#039;href="https://www.askapache.com/&#039;, &#039;href="/&#039;, $g);
$g = str_replace(&#039;src="https://www.askapache.com/&#039;, &#039;src="/&#039;, $g);
$g = str_replace(&#039;href="/&#039;, &#039;href="&#039;, $g);
$g = str_replace(&#039;src="/&#039;, &#039;src="&#039;, $g);
$g = str_replace("href=&#039;https://www.askapache.com/", "href=&#039;/", $g);
$g = str_replace("src=&#039;https://www.askapache.com/", "src=&#039;/", $g);
$g = str_replace("href=&#039;/", "href=&#039;", $g);
$g = str_replace("src=&#039;/", "src=&#039;", $g);
file_put_contents($fd . &#039;/index.html&#039;, $g);
&nbsp;
// fixup for css file
foreach($urls as $url)
{
if (strpos($url, &#039;.css&#039;) !== false)
{
  $fuu = parse_url($url);
  $css = file_get_contents($fd . $fuu[&#039;path&#039;]);
  $css = str_replace(&#039;url(/&#039;, &#039;url(../&#039;, $css);
  file_put_contents($fd . $fuu[&#039;path&#039;], $css);
}
}
&nbsp;
// my favorite technique, using fsockopen to initiate a shell script server-side.
// passing the args in the HTTP Headers... genius!!
// close the sucker fast with HTTP/1.0 and connection: close
$fp = fsockopen ($_SERVER[&#039;SERVER_NAME&#039;], 80, $errno, $errstr, 5);
fwrite($fp, "GET /cgi-bin/sh/zip.sh HTTP/1.0\r\nHost: www.askapache.com\r\nX-Pad: {$fd}\r\nX-Allow: {$FDATE}\r\nConnection: Close\r\n\r\n");
fclose($fp);
&nbsp;
// loop until the file created by /cgi-bin/sh/zip.sh is found
$c = 0;
do
{
$c++;
sleep(1);
clearstatcache();
if (is_file("{$FEXE}")) continue;
}
while ($c &lt; 20);
&nbsp;
// either zip or exe
$type = $_GET[&#039;type&#039;];
if ($type == &#039;zip&#039;) $file = $FZIP;
else $file = $FEXE;
&nbsp;
// wow great debugging dude
error_log($file);
&nbsp;
// if the file is there, do a 302 redirect to initiate download
if (file_exists("{$file}"))
{
  @header("HTTP/1.1 302 Moved", 1, 302);
  @header("Status: 302 Moved", 1, 302);
  @header(&#039;Location: https://www.askapache.com/&#039; . basename($file));
  exit;
}
&nbsp;
exit;
?&gt;</pre>



<h2>zip.sh</h2>
<pre>#!/bin/sh
&nbsp;
# all you need for cgi
  echo -e "Content-type: text/plain\n\n"
&nbsp;
# blank that run log
  echo "" &gt; /home/askapache/sites/askapache.com/tmp/run.log
&nbsp;
# redirect 1 and 2 to the run log for the whole script
  exec &amp;&gt;/home/askapache/sites/askapache.com/tmp/run.log
&nbsp;
# basename
  N=${HTTP_X_PAD//*\/}
&nbsp;
# date-based
  NN=${HTTP_X_ALLOW}
&nbsp;
# create recursively the dir tree
  mkdir -pv $HTTP_X_PAD
&nbsp;
# cd to the tmp
  cd /home/askapache/sites/askapache.com/tmp
&nbsp;
# the zip version with date
  F=$N-$NN.zip
&nbsp;
# the exe version with date
  NN=$N-$NN.exe
&nbsp;
# for debugging, only goes to run log
  echo "F=$F"
  echo "NN=$NN"
  echo "N=$N"
&nbsp;
# create a relative (r is recursive) archive of the entire dir
  /usr/bin/zip -rvv $F $N
&nbsp;
# add the self-extracting stub to the archive
  /bin/cat unzipsfx.exe $F &gt; $NN
&nbsp;
# fix the sfx stub
  /usr/bin/zip -A $NN
&nbsp;
# move both the exe and zip to the web-docroot to be dl&#039;d directly
  cp -vf $NN /home/askapache/sites/askapache.com/htdocs/
  cp -vf $F /home/askapache/sites/askapache.com/htdocs/
&nbsp;
# sleep for 60 seconds and then rm all the files, so you better download that file fast
  sleep 60 &amp;&amp; rm -rvf $HTTP_X_PAD $F $NN /home/askapache/sites/askapache.com/htdocs/$NN /home/askapache/sites/askapache.com/htdocs/$F
&nbsp;
#suh suh cya
exit 0;</pre>


<h3>Creating SFX Archives</h3>
<p>The best way is 7z, but I couldn't get p7zip's sfx module to work and didn't have time to compile it.  Instead I just used the stub available here:  <code>curl -O -L ftp://ftp.info-zip.org/pub/infozip/win32/unz552xn.exe</code> which works great but no customization like password, icons, etc.. oh well.</p>



<h2>Implementation</h2>
<p>Simple, just create a link to the php file with the url and type parameters.  <code>/cgi-bin/php/scrapeit.php?url=http://www.askapache.com/htaccess/htaccess.html&amp;type=exe</code> or if you integrate into wordpress like I did you can add this to your header or admin_bar and use the <code>get_permalink()</code> for the url arg.</p>

<h2>Lock It Down</h2>
<p>This was used on a private site so what I did was add some code to the scrapeit.php file that just copied the HTTP_COOKIE value sent by the requesting user and sent that as part of the request in the fsockopen request.  That means only logged in users can do this, and furthermore, if a user doesn't have access to a page and tries to use this to circumvent, they can't.  And also htaccess was used to limit the scripts to only allow the ip's running the server to make connections.</p>

<h2>Conclusion</h2>
<p>What can't be done with linux, bash, http, php, and a little server-side finesse?  My clients are very happy, and I had some fun!</p><p><a href="http://www.askapache.com/php/scrape-offline-page-curl.html"></a><a href="http://www.askapache.com/php/scrape-offline-page-curl.html">Creating an Offline Version of Page</a> originally appeared on <cite>AskApache.com</cite> </p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/php/scrape-offline-page-curl.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Session File Hacks</title>
		<link>http://www.askapache.com/php/php-session-hack.html</link>
		<comments>http://www.askapache.com/php/php-session-hack.html#comments</comments>
		<pubDate>Fri, 25 Jun 2010 00:00:09 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.askapache.com/?p=1019</guid>
		<description><![CDATA[<p><strong>What they say about kung-fu is true</strong>..</p>
<p>It can be attained by anyone through <em>hard work over time</em>.   You can become as good as the amount of work you put in.   Here's a short look at a basic technique that I use.  Simply reverse engineering the source code and taking notes along the way...</p>
<pre>static void php_session_send_cookie(TSRMLS_D)
  if (SG(headers_sent)) {
          if (output_start_filename) {
                  php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot send session cookie - headers already sent by (output started at %s:%d)",
                          output_start_filename, output_start_lineno);
          } else {
                  php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot send session cookie - headers already sent");
          }
          return;
  }

  /* URL encode session_name and id because they might be user supplied */
  e_session_name = php_url_encode(PS(session_name), strlen(PS(session_name)), NULL);</pre>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.askapache.com/php/php-session-hack.html"></a><a href="http://www.askapache.com/php/php-session-hack.html"><cite>AskApache.com</cite></a></p><p>If you want to learn best tricks and tips, there's only one way to do it... at least only one way that I know of.  Here are some notes I created while learning about the intricacies of php sessions, it's all in the code.</p>


<pre>[Session]
; Handler used to store/retrieve data.
session.save_handler = files</pre>

<p>Argument passed to save_handler.  In the case of files, this is the path where data files are stored. As of PHP 4.0.1, you can define the path as:</p>
<pre>session.save_path = "N;/path"</pre>

<p> where N is an integer.  Instead of storing all the session files in
 /path, what this will do is use subdirectories N-levels deep, and
 store the session data in those directories.  This is useful if you
 or your OS have problems with lots of files in one directory, and is
 a more efficient layout for servers that handle lots of sessions.</p>

<pre>;
; NOTE 1: PHP will not create this directory structure automatically.
;         You can use the script in the ext/session dir for that purpose.
; NOTE 2: See the section on garbage collection below if you choose to
;         use subdirectories for session storage
;
; The file storage module creates files using mode 600 by default.
; You can change that by using
;
;     session.save_path = "N;MODE;/path"
;
; where MODE is the octal representation of the mode. Note that this
; does not overwrite the process&#039;s umask.
;session.save_path = "/tmp"</pre>




<h3>session.c</h3>
<pre>/* {{{ PHP_INI
 */
PHP_INI_BEGIN()
        STD_PHP_INI_BOOLEAN("session.bug_compat_42",    "1",         PHP_INI_ALL, OnUpdateBool,   bug_compat,         php_ps_globals,    ps_globals)
        STD_PHP_INI_BOOLEAN("session.bug_compat_warn",  "1",         PHP_INI_ALL, OnUpdateBool,   bug_compat_warn,    php_ps_globals,    ps_globals)
        STD_PHP_INI_ENTRY("session.save_path",          "",          PHP_INI_ALL, OnUpdateSaveDir,save_path,          php_ps_globals,    ps_globals)
        STD_PHP_INI_ENTRY("session.name",               "PHPSESSID", PHP_INI_ALL, OnUpdateString, session_name,       php_ps_globals,    ps_globals)
        PHP_INI_ENTRY("session.save_handler",           "files",     PHP_INI_ALL, OnUpdateSaveHandler)
        STD_PHP_INI_BOOLEAN("session.auto_start",       "0",         PHP_INI_ALL, OnUpdateBool,   auto_start,         php_ps_globals,    ps_globals)
        STD_PHP_INI_ENTRY("session.gc_probability",     "1",         PHP_INI_ALL, OnUpdateLong,    gc_probability,     php_ps_globals,    ps_globals)
        STD_PHP_INI_ENTRY("session.gc_divisor",         "100",       PHP_INI_ALL, OnUpdateLong,    gc_divisor,        php_ps_globals,    ps_globals)
        STD_PHP_INI_ENTRY("session.gc_maxlifetime",     "1440",      PHP_INI_ALL, OnUpdateLong,    gc_maxlifetime,     php_ps_globals,    ps_globals)
        PHP_INI_ENTRY("session.serialize_handler",      "php",       PHP_INI_ALL, OnUpdateSerializer)
        STD_PHP_INI_ENTRY("session.cookie_lifetime",    "0",         PHP_INI_ALL, OnUpdateLong,    cookie_lifetime,    php_ps_globals,    ps_globals)
        STD_PHP_INI_ENTRY("session.cookie_path",        "/",         PHP_INI_ALL, OnUpdateString, cookie_path,        php_ps_globals,    ps_globals)
        STD_PHP_INI_ENTRY("session.cookie_domain",      "",          PHP_INI_ALL, OnUpdateString, cookie_domain,      php_ps_globals,    ps_globals)
        STD_PHP_INI_BOOLEAN("session.cookie_secure",    "",          PHP_INI_ALL, OnUpdateBool,   cookie_secure,      php_ps_globals,    ps_globals)
        STD_PHP_INI_BOOLEAN("session.cookie_httponly",  "",          PHP_INI_ALL, OnUpdateBool,   cookie_httponly,    php_ps_globals,    ps_globals)
        STD_PHP_INI_BOOLEAN("session.use_cookies",      "1",         PHP_INI_ALL, OnUpdateBool,   use_cookies,        php_ps_globals,    ps_globals)
        STD_PHP_INI_BOOLEAN("session.use_only_cookies", "0",         PHP_INI_ALL, OnUpdateBool,   use_only_cookies,   php_ps_globals,    ps_globals)
        STD_PHP_INI_ENTRY("session.referer_check",      "",          PHP_INI_ALL, OnUpdateString, extern_referer_chk, php_ps_globals,    ps_globals)
        STD_PHP_INI_ENTRY("session.entropy_file",       "",          PHP_INI_ALL, OnUpdateString, entropy_file,       php_ps_globals,    ps_globals)
        STD_PHP_INI_ENTRY("session.entropy_length",     "0",         PHP_INI_ALL, OnUpdateLong,    entropy_length,     php_ps_globals,    ps_globals)
        STD_PHP_INI_ENTRY("session.cache_limiter",      "nocache",   PHP_INI_ALL, OnUpdateString, cache_limiter,      php_ps_globals,    ps_globals)
        STD_PHP_INI_ENTRY("session.cache_expire",       "180",       PHP_INI_ALL, OnUpdateLong,    cache_expire,       php_ps_globals,    ps_globals)
        PHP_INI_ENTRY("session.use_trans_sid",          "0",         PHP_INI_ALL, OnUpdateTransSid)
        STD_PHP_INI_ENTRY("session.hash_function",      "0",         PHP_INI_ALL, OnUpdateLong,    hash_func,          php_ps_globals,    ps_globals)
        STD_PHP_INI_ENTRY("session.hash_bits_per_character",      "4",         PHP_INI_ALL, OnUpdateLong,    hash_bits_per_character,          php_ps_globals,    ps_globals)
&nbsp;
        /* Commented out until future discussion */
        /* PHP_INI_ENTRY("session.encode_sources", "globals,track", PHP_INI_ALL, NULL) */
PHP_INI_END()
/* }}} */</pre>



<h3>Session Errors</h3>
<pre>The session id contains illegal characters, valid characters are a-z, A-Z, 0-9 and &#039;-,&#039;
fcntl(%d, F_SETFD, FD_CLOEXEC) failed: %s (%d)
open(%s, O_RDWR) failed: %s (%d)
ps_files_cleanup_dir: opendir(%s) failed: %s (%d)
read failed: %s (%d)
read returned less bytes than requested
write failed: %s (%d)
write wrote less bytes than requested
mm_malloc failed, avail %d, err %s
cannot allocate new data segment
Skipping numeric key %ld.
A session is active. You cannot change the session module&#039;s ini settings at this time.
Cannot find save handler %s
Cannot find serialization handler %s
Unknown session.serialize_handler. Failed to encode session object.
Cannot encode non-existent session.
Unknown session.serialize_handler. Failed to decode session object.
Failed to decode session object. Session has been destroyed.
Invalid session hash function
The ini setting hash_bits_per_character is out of range (should be 4, 5, or 6) - using 4 for now
No storage module chosen - failed to initialize session.
Failed to initialize storage module: %s (path: %s)
The session bug compatibility code will not
Your script possibly relies on a session side-effect which existed until PHP 4.2.3. Please be advised that the session extension does not consider global variables as a source of data, unless register_globals is enabled. You can disable this functionality and this warning by setting session.bug_compat_42 or session.bug_compat_warn to off, respectively.
Failed to write session data (%s). Please
Cannot send session cache limiter - headers already sent (output started at %s:%d)
Cannot send session cache limiter - headers already sent
Cannot send session cookie - headers already sent by (output started at %s:%d)
Cannot send session cookie - headers already sent
Cannot find save handler %s
Cannot find unknown save handler
purged %d expired session objects
Trying to destroy uninitialized session
Session object destruction failed
Cannot find named PHP session module (%s)
Argument %d is not a valid callback
Cannot regenerate session id - headers already sent
Session object destruction failed</pre>







<pre>PS_GC_FUNC(files)
{
        PS_FILES_DATA;
&nbsp;
        /* we don&#039;t perform any cleanup, if dirdepth is larger than 0.
           we return SUCCESS, since all cleanup should be handled by
           an external entity (i.e. find -ctime x | xargs rm) */
&nbsp;
        if (data-&gt;dirdepth == 0) {
                *nrdels = ps_files_cleanup_dir(data-&gt;basedir, maxlifetime TSRMLS_CC);
        }
&nbsp;
        return SUCCESS;
}</pre>

<h3>mod_files.c</h3>
<pre>/* If you change the logic here, please also update the error message in
 * ps_files_open() appropriately */
static int ps_files_valid_key(const char *key)
{
        size_t len;
        const char *p;
        char c;
        int ret = 1;
&nbsp;
        for (p = key; (c = *p); p++) {
                /* valid characters are a..z,A..Z,0..9 */
                if (!((c &gt;= &#039;a&#039; &amp;&amp; c &lt;= &#039;z&#039;)
                                || (c &gt;= &#039;A&#039; &amp;&amp; c &lt;= &#039;Z&#039;)
                                || (c &gt;= &#039;0&#039; &amp;&amp; c &lt;= &#039;9&#039;)
                                || c == &#039;,&#039;
                                || c == &#039;-&#039;)) {
                        ret = 0;
                        break;
                }
        }
&nbsp;
        len = p - key;
&nbsp;
        if (len == 0) {
                ret = 0;
        }
&nbsp;
        return ret;
}</pre>




<pre>static int ps_files_cleanup_dir(const char *dirname, int maxlifetime TSRMLS_DC)
{
        DIR *dir;
        char dentry[sizeof(struct dirent) + MAXPATHLEN];
        struct dirent *entry = (struct dirent *) &amp;dentry;
        struct stat sbuf;
        char buf[MAXPATHLEN];
        time_t now;
        int nrdels = 0;
        size_t dirname_len;
&nbsp;
        dir = opendir(dirname);
        if (!dir) {
                php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ps_files_cleanup_dir: opendir(%s) failed: %s (%d)", dirname, strerror(errno), errno);
                return (0);
        }
&nbsp;
        time(&amp;now);
&nbsp;
        dirname_len = strlen(dirname);
&nbsp;
        /* Prepare buffer (dirname never changes) */
        memcpy(buf, dirname, dirname_len);
        buf[dirname_len] = PHP_DIR_SEPARATOR;
&nbsp;
        while (php_readdir_r(dir, (struct dirent *) dentry, &amp;entry) == 0 &amp;&amp; entry) {
                /* does the file start with our prefix? */
                if (!strncmp(entry-&gt;d_name, FILE_PREFIX, sizeof(FILE_PREFIX) - 1)) {
                        size_t entry_len = strlen(entry-&gt;d_name);
&nbsp;
                        /* does it fit into our buffer? */
                        if (entry_len + dirname_len + 2 &lt; MAXPATHLEN) {
                                /* create the full path.. */
                                memcpy(buf + dirname_len + 1, entry-&gt;d_name, entry_len);
&nbsp;
                                /* NUL terminate it and */
                                buf[dirname_len + entry_len + 1] = &#039;\0&#039;;
&nbsp;
                                /* check whether its last access was more than maxlifet ago */
                                if (VCWD_STAT(buf, &amp;sbuf) == 0 &amp;&amp;
#ifdef NETWARE
                                                (now - sbuf.st_mtime.tv_sec) &gt; maxlifetime) {
#else
                                                (now - sbuf.st_mtime) &gt; maxlifetime) {
#endif
                                        VCWD_UNLINK(buf);
                                        nrdels++;
                                }
                        }
                }
        }
&nbsp;
        closedir(dir);
&nbsp;
        return (nrdels);
}</pre>







<h3>ext/session/mod_files.c</h3>
<pre>#define PS_FILES_DATA ps_files *data = PS_GET_MOD_DATA()
&nbsp;
PS_OPEN_FUNC(files)
{
        ps_files *data;
        const char *p, *last;
        const char *argv[3];
        int argc = 0;
        size_t dirdepth = 0;
        int filemode = 0600;
&nbsp;
        if (*save_path == &#039;\0&#039;) {
                /* if save path is an empty string, determine the temporary dir */
                save_path = php_get_temporary_directory();
&nbsp;
                if (strcmp(save_path, "/tmp")) {
                        if (PG(safe_mode) &amp;&amp; (!php_checkuid(save_path, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {
                                return FAILURE;
                        }
                        if (php_check_open_basedir(save_path TSRMLS_CC)) {
                                return FAILURE;
                        }
                }
        }
&nbsp;
        /* split up input parameter */
        last = save_path;
        p = strchr(save_path, &#039;;&#039;);
        while (p) {
                argv[argc++] = last;
                last = ++p;
                p = strchr(p, &#039;;&#039;);
                if (argc &gt; 2) break;
        }
        argv[argc++] = last;
&nbsp;
        if (argc &gt; 1) {
                errno = 0;
                dirdepth = (size_t) strtol(argv[0], NULL, 10);
                if (errno == ERANGE) {
                        php_error(E_WARNING, "The first parameter in session.save_path is invalid");
                        return FAILURE;
                }
        }
&nbsp;
        if (argc &gt; 2) {
                errno = 0;
                filemode = strtol(argv[1], NULL, 8);
                if (errno == ERANGE || filemode &lt; 0 || filemode &gt; 07777) {
                        php_error(E_WARNING, "The second parameter in session.save_path is invalid");
                        return FAILURE;
                }
        }
        save_path = argv[argc - 1];
&nbsp;
        data = emalloc(sizeof(*data));
        memset(data, 0, sizeof(*data));
&nbsp;
        data-&gt;fd = -1;
        data-&gt;dirdepth = dirdepth;
        data-&gt;filemode = filemode;
        data-&gt;basedir_len = strlen(save_path);
        data-&gt;basedir = estrndup(save_path, data-&gt;basedir_len);
&nbsp;
        PS_SET_MOD_DATA(data);
&nbsp;
        return SUCCESS;
}</pre>










<blockquote><pre>[PHP 5.2.0 session.save_path safe_mode and open_basedir bypass]
&nbsp;
Author: Maksymilian Arciemowicz (SecurityReason)
Date:
- - Written: 02.10.2006
- - Public: 08.12.2006
SecurityAlert Id: 43
CVE: CVE-2006-6383
SecurityRisk: High
Affected Software: PHP 5.2.0
Advisory URL: http://securityreason.com/achievement_securityalert/43
Vendor: http://www.php.net
&nbsp;
- --- 0.Description ---
PHP is an HTML-embedded scripting language. Much of its syntax is borrowed from
C, Java and Perl with a couple of unique PHP-specific features thrown in. The
goal of the language is to allow web developers to write dynamically generated
pages quickly.
&nbsp;
A nice introduction to PHP by Stig Sather Bakken can be found at
http://www.zend.com/zend/art/intro.php on the Zend website. Also, much  of the
PHP Conference Material is freely available.
&nbsp;
Session support in PHP consists of a way to preserve certain data across
subsequent accesses. This enables you to build more customized applications and
increase the appeal of your web site.
&nbsp;
A visitor accessing your web site is assigned a unique id, the so-called
session id. This is either stored in a cookie on the user side or is propagated
in the URL.
&nbsp;
session.save_path defines the argument which is passed to the save handler. If
you choose the default files handler, this is the path where the files are
created. Defaults to /tmp. See also session_save_path().
&nbsp;
There is an optional N argument to this directive that determines the number of
directory levels your session files will be spread around in. For example,
setting to &#039;5;/tmp&#039; may end up creating a session file and location like
/tmp/4/b/1/e/3/sess_4b1e384ad74619bd212e236e52a5a174If . In order to use N you
must create all of these directories before use. A small shell script exists in
ext/session to do this, it&#039;s called mod_files.sh. Also note that if N is used
and greater than 0 then automatic garbage collection will not be performed, see
a copy of php.ini for further information. Also, if you use N, be sure to
surround session.save_path in "quotes" because the separator (;) is also used
for comments in php.ini.
&nbsp;
- --- 1. session.save_path safe mode and open basedir bypass ---
session.save_path can be set in ini_set(), session_save_path() function. In
session.save_path there must be path where you will save yours tmp file. But
syntax for session.save_path can be:
&nbsp;
[/PATH]
&nbsp;
OR
&nbsp;
[N;/PATH]
&nbsp;
N - can be a string.
&nbsp;
EXAMPLES:
&nbsp;
1. session_save_path("/DIR/WHERE/YOU/HAVE/ACCESS")
2. session_save_path("5;/DIR/WHERE/YOU/HAVE/ACCESS")
&nbsp;
and
&nbsp;
3.
session_save_path("/DIR/WHERE/YOU/DONT/HAVE/ACCESS\0;/DIR/WHERE/YOU/HAVE/ACCESS")</pre></blockquote>






<pre>CACHE_LIMITER_FUNC(public)
{
        char buf[MAX_STR + 1];
        struct timeval tv;
        time_t now;
&nbsp;
        gettimeofday(&amp;tv, NULL);
        now = tv.tv_sec + PS(cache_expire) * 60;
#define EXPIRES "Expires: "
        memcpy(buf, EXPIRES, sizeof(EXPIRES) - 1);
        strcpy_gmt(buf + sizeof(EXPIRES) - 1, &amp;now);
        ADD_HEADER(buf);
&nbsp;
        snprintf(buf, sizeof(buf) , "Cache-Control: public, max-age=%ld", PS(cache_expire) * 60); /* SAFE */
        ADD_HEADER(buf);
&nbsp;
        last_modified(TSRMLS_C);
}
&nbsp;
CACHE_LIMITER_FUNC(private_no_expire)
{
        char buf[MAX_STR + 1];
&nbsp;
        snprintf(buf, sizeof(buf), "Cache-Control: private, max-age=%ld, pre-check=%ld", PS(cache_expire) * 60, PS(cache_expire) * 60); /* SAFE */
        ADD_HEADER(buf);
&nbsp;
        last_modified(TSRMLS_C);
}
&nbsp;
CACHE_LIMITER_FUNC(private)
{
        ADD_HEADER("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
        CACHE_LIMITER(private_no_expire)(TSRMLS_C);
}
&nbsp;
CACHE_LIMITER_FUNC(nocache)
{
        ADD_HEADER("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
        /* For HTTP/1.1 conforming clients and the rest (MSIE 5) */
        ADD_HEADER("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
        /* For HTTP/1.0 conforming clients */
        ADD_HEADER("Pragma: no-cache");
}
&nbsp;
static php_session_cache_limiter_t php_session_cache_limiters[] = {
        CACHE_LIMITER_ENTRY(public)
        CACHE_LIMITER_ENTRY(private)
        CACHE_LIMITER_ENTRY(private_no_expire)
        CACHE_LIMITER_ENTRY(nocache)
        {0}
};
&nbsp;
static int php_session_cache_limiter(TSRMLS_D)
{
        php_session_cache_limiter_t *lim;
&nbsp;
        if (PS(cache_limiter)[0] == &#039;\0&#039;) return 0;
&nbsp;
        if (SG(headers_sent)) {
                char *output_start_filename = php_get_output_start_filename(TSRMLS_C);
                int output_start_lineno = php_get_output_start_lineno(TSRMLS_C);
&nbsp;
                if (output_start_filename) {
                        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot send session cache limiter - headers already sent (output started at %s:%d)",
                                output_start_filename, output_start_lineno);
                } else {
                        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot send session cache limiter - headers already sent");
                }
                return -2;
        }
&nbsp;
        for (lim = php_session_cache_limiters; lim-&gt;name; lim++) {
                if (!strcasecmp(lim-&gt;name, PS(cache_limiter))) {
                        lim-&gt;func(TSRMLS_C);
                        return 0;
                }
        }
&nbsp;
        return -1;
}</pre>









<pre>static void php_session_send_cookie(TSRMLS_D)
{
        smart_str ncookie = {0};
        char *date_fmt = NULL;
        char *e_session_name, *e_id;
&nbsp;
        if (SG(headers_sent)) {
                char *output_start_filename = php_get_output_start_filename(TSRMLS_C);
                int output_start_lineno = php_get_output_start_lineno(TSRMLS_C);
&nbsp;
                if (output_start_filename) {
                        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot send session cookie - headers already sent by (output started at %s:%d)",
                                output_start_filename, output_start_lineno);
                } else {
                        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot send session cookie - headers already sent");
                }
                return;
        }
&nbsp;
        /* URL encode session_name and id because they might be user supplied */
        e_session_name = php_url_encode(PS(session_name), strlen(PS(session_name)), NULL);
        e_id = php_url_encode(PS(id), strlen(PS(id)), NULL);
&nbsp;
        smart_str_appends(&amp;ncookie, COOKIE_SET_COOKIE);
        smart_str_appends(&amp;ncookie, e_session_name);
        smart_str_appendc(&amp;ncookie, &#039;=&#039;);
        smart_str_appends(&amp;ncookie, e_id);
&nbsp;
        efree(e_session_name);
        efree(e_id);
&nbsp;
        if (PS(cookie_lifetime) &gt; 0) {
                struct timeval tv;
                time_t t;
&nbsp;
                gettimeofday(&amp;tv, NULL);
                t = tv.tv_sec + PS(cookie_lifetime);
&nbsp;
                if (t &gt; 0) {
                        date_fmt = php_std_date(t TSRMLS_CC);
                        smart_str_appends(&amp;ncookie, COOKIE_EXPIRES);
                        smart_str_appends(&amp;ncookie, date_fmt);
                        efree(date_fmt);
                }
        }
&nbsp;
        if (PS(cookie_path)[0]) {
                smart_str_appends(&amp;ncookie, COOKIE_PATH);
                smart_str_appends(&amp;ncookie, PS(cookie_path));
        }
&nbsp;
        if (PS(cookie_domain)[0]) {
                smart_str_appends(&amp;ncookie, COOKIE_DOMAIN);
                smart_str_appends(&amp;ncookie, PS(cookie_domain));
        }
&nbsp;
        if (PS(cookie_secure)) {
                smart_str_appends(&amp;ncookie, COOKIE_SECURE);
        }
&nbsp;
        if (PS(cookie_httponly)) {
                smart_str_appends(&amp;ncookie, COOKIE_HTTPONLY);
        }
&nbsp;
        smart_str_0(&amp;ncookie);
&nbsp;
        /*      &#039;replace&#039; must be 0 here, else a previous Set-Cookie
                header, probably sent with setcookie() will be replaced! */
        sapi_add_header_ex(ncookie.c, ncookie.len, 0, 0 TSRMLS_CC);
}</pre><p><a href="http://www.askapache.com/php/php-session-hack.html"></a><a href="http://www.askapache.com/php/php-session-hack.html">PHP Session File Hacks</a> originally appeared on <cite>AskApache.com</cite> </p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/php/php-session-hack.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Advanced WordPress wp-config.php Tweaks</title>
		<link>http://www.askapache.com/wordpress/advanced-wp-config-php-tweaks.html</link>
		<comments>http://www.askapache.com/wordpress/advanced-wp-config-php-tweaks.html#comments</comments>
		<pubDate>Wed, 03 Mar 2010 08:23:37 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://www.askapache.com/?p=3341</guid>
		<description><![CDATA[<p>The bottom line for this article is that I want to make WordPress as fast, secure, and easy to install, run, and manage because I am using it more and more for client production sites, I will work for days in order to solve an issue so that I never have to spend time on that issue again. Time is money in this industry and that is ultimately (time) what there is to gain by tweaking WordPress.</p>

<p class="cnote"><strong>Note:</strong> I spent no time on readability, this is primarily a read the code and figure it out article.. This is for advanced users looking for a reference or discussion and for those of you looking to advance.  Feedback would be great <em>if you make it that far..</em></p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.askapache.com/wordpress/advanced-wp-config-php-tweaks.html"></a><a href="http://www.askapache.com/wordpress/advanced-wp-config-php-tweaks.html"><cite>AskApache.com</cite></a></p><p>The bottom line for this article is that I want to make WordPress as fast, secure, and easy to install, run, and manage because I am using it more and more for client production sites, I will work for days in order to solve an issue so that I never have to spend time on that issue again. Time is money in this industry and that is ultimately (time) what there is to gain by tweaking WordPress.</p>
<p class="cnote"><strong>Note:</strong> I spent no time on readability, this is primarily a read the code and figure it out article.. This is for advanced users looking for a reference or discussion and for those of you looking to advance.  Feedback would be great <em>if you make it that far..</em></p>
<p>For a better handle on the way I like to structure web site directories, see <a href="http://www.askapache.com/htaccess/optimize-website-files-cache-security.html">Optimize a Website for Speed, Security, and Easy Management</a> but note it is a bit outdated compared to what I'm doing now.  I don't have the luxury of using only one type of server, or hosting provider anymore, so I have been working towards making things even more portable in order to move from host to host from server to server without issues i.e. my portable <a href="http://www.askapache.com/linux/bash_profile-functions-advanced-shell.html">.bash_profile</a>.</p>
<p>So I've been basically experimenting various ways to accomplish that and thought I would share what I am currently doing for my benefit and hopefully get some input.  All of my WP installs run the development version, and one main idea with my setups is that upgrading is automated.  So I really keep the WordPress install clean and use plugins and wp-config.php to do all the customization.</p>
<ul>
    <li>Portability - Hands-free upgrades and easy to move</li>
    <li>Security - Additional security and protection</li>
    <li>Speed - Less CPU and Disk I/O</li>
    <li>Customization - All my favorite customizations</li>
</ul>
<h2>wp-config.php</h2>
<p>These are the main settings I use.. Seriously this is more like an interactive article, because to understand it you will need to do some code grepping.  You may want to grab a jolt.</p>
<h3>ASKAPACHE_ROOT</h3>
<p>The ASKAPACHE_ROOT variable is just a better way for me to be able to include and access all the different files in my site tree.  For instance, in my non-wp php files, I can do this:</p>
<pre>!defined(&#039;ASKAPACHE_ROOT&#039;) &amp;&amp; require $_SERVER[&#039;DOCUMENT_ROOT&#039;] . &#039;/wp-config.php&#039;;
include(ASKAPACHE_ROOT . &#039;/includes/custom-download.inc.php&#039;);</pre>
<h3>ASKAPACHE_LOCK</h3>
<p>This is one of my all-time favorite hacks, that I think is one of the most useful methods I employ as a web developer.  This allows me to use far-future-expire headers for optimum caching, while still forcing browsers to re-validate every day or so automatically, or forcing them to re-validate whenever I change the suffix.  This takes advantage of the <a href="http://www.askapache.com/htaccess/mod_rewrite-fix-for-caching-updated-files.html">mod_rewrite trick</a> that I use on EVERY site I run, definately worth learning. Because I practice best-practice web-standards, for every web site I create a single css file and javascript file, which I then add to the template like:</p>
<pre>&lt;link rel="stylesheet" type="text/css" media="all" href="http://static.askapache.com/c/apache-0&lt;?php echo ASKAPACHE_LOCK?&gt;.css" /&gt;
&lt;script src="http://static.askapache.com/j/apache-0&lt;?php echo ASKAPACHE_LOCK;?&gt;.js" type="text/javascript"&gt;&lt;/script&gt;</pre>
<pre>&lt;?php
/**
 * The base configurations of the WordPress.
 *
 * This file has the following configurations: MySQL settings, Table Prefix,
 * Secret Keys, WordPress Language, and ABSPATH. You can find more information by
 * visiting {@link http://codex.wordpress.org/Editing_wp-config.php Editing
 * wp-config.php} Codex page. You can get the MySQL settings from your web host.
 *
 * This file is used by the wp-config.php creation script during the
 * installation. You don&#039;t have to use the web site, you can just copy this file
 * to "wp-config.php" and fill in the values.
 *
 * @package WordPress
 */
/* http://codex.wordpress.org/Editing_wp-config.php */
&nbsp;
/** /home/liet/askapache.com */
!defined(&#039;ASKAPACHE_ROOT&#039;) &amp;&amp; define(&#039;ASKAPACHE_ROOT&#039;, str_replace(&#039;/public_html&#039;,&#039;&#039;, $_SERVER[&#039;DOCUMENT_ROOT&#039;]));
&nbsp;
/** The 008 at the end is for manual tweaking.  time() returns seconds since &#039;00:00:00 1970-01-01 UTC&#039;. */
// http://www.askapache.com/htaccess/mod_rewrite-fix-for-caching-updated-files.html
!defined(&#039;ASKAPACHE_LOCK&#039;) &amp;&amp; define(ASKAPACHE_LOCK&#039;, substr(time(),0,5).&#039;008&#039;); // 12533001
&nbsp;
/** absolute path to the WordPress directory */
!defined(&#039;ABSPATH&#039;) &amp;&amp; define(&#039;ABSPATH&#039;, ASKAPACHE_ROOT .&#039;/public_html/&#039;);
&nbsp;
/**
 * WP_SITEURL, defined since WordPress Version 2.2, allows the WordPress address (URL) to be defined. The valued defined is the address where your WordPress core files reside.
 * It should include the http:// part too. Do not put a slash "/" at the end.
 * Setting this value in wp-config.php overrides the wp_options table value for siteurl and disables the WordPress address (URL) field in the Administration &gt; Settings &gt; General panel.
 */
!defined(&#039;WP_SITEURL&#039;) &amp;&amp; define(&#039;WP_SITEURL&#039;, &#039;http://&#039;.$_SERVER[&#039;SERVER_NAME&#039;]);
&nbsp;
/**
 * WP_HOME is another wp-config.php option added in WordPress Version 2.2. Similar to WP_SITEURL,
 * WP_HOME overrides the wp_options table value for home but does not change it permanently.
 * home is the address you want people to type in their browser to reach your WordPress blog. It should include the http:// part. Also, do not put a slash "/" at the end.
 */
!defined(&#039;WP_HOME&#039;) &amp;&amp; define(&#039;WP_HOME&#039;, WP_SITEURL);
&nbsp;
/** no trailing slash, full paths only */
!defined(&#039;WP_CONTENT_DIR&#039;) &amp;&amp; define( &#039;WP_CONTENT_DIR&#039;, ABSPATH . &#039;wp-content&#039; );
&nbsp;
// full url - WP_CONTENT_DIR is defined further up
!defined(&#039;WP_CONTENT_URL&#039;) &amp;&amp; define( &#039;WP_CONTENT_URL&#039;, WP_SITEURL . &#039;/wp-content&#039;);
&nbsp;
/** Allows for the plugins directory to be moved from the default location. @since 2.6.0 */
// full path, no trailing slash
!defined(&#039;WP_PLUGIN_DIR&#039;) &amp;&amp; define( &#039;WP_PLUGIN_DIR&#039;, WP_CONTENT_DIR . &#039;/plugins&#039; );
&nbsp;
/** Allows for the plugins directory to be moved from the default location. @since 2.6.0 */
// full url, no trailing slash
!defined(&#039;WP_PLUGIN_URL&#039;) &amp;&amp; define( &#039;WP_PLUGIN_URL&#039;, WP_CONTENT_URL . &#039;/plugins&#039; );
&nbsp;
/** Allows for the plugins directory to be moved from the default location. @since 2.1.0 */
// Relative to ABSPATH.  For back compat.
//!defined(&#039;PLUGINDIR&#039;) &amp;&amp; define( &#039;PLUGINDIR&#039;, &#039;wp-content/plugins&#039; );
&nbsp;
/** Number of autosaves to save. TRUE is default and enables post revisions, FALSE disables revisions completely. */
!defined(&#039;WP_POST_REVISIONS&#039;) &amp;&amp; define(&#039;WP_POST_REVISIONS&#039;, 150);
&nbsp;
/* ini_set(&#039;memory_limit&#039;, WP_MEMORY_LIMIT); */
!defined(&#039;WP_MEMORY_LIMIT&#039;) &amp;&amp; define(&#039;WP_MEMORY_LIMIT&#039;, &#039;64M&#039;);
&nbsp;
/** Only check at this interval for new messages. Default is 5min */
/** @since 2.9  */
!defined(&#039;WP_MAIL_INTERVAL&#039;) &amp;&amp; define(&#039;WP_MAIL_INTERVAL&#039;, 3600); // 1 hour
&nbsp;
/** Saves updated post values to post from edit window every x seconds. (default 60)
 * When editing a post, WordPress uses Ajax to auto-save revisions to the post as you edit. You may want to increase this setting for longer delays in between auto-saves, or decrease the setting to make sure you never lose changes.
 * @since 2.5.0 */
!defined( &#039;AUTOSAVE_INTERVAL&#039; ) &amp;&amp; define( &#039;AUTOSAVE_INTERVAL&#039;, 60 );
&nbsp;
/** @since 2.9.0  */
/** Permanently deletes posts, pages, attachments, and comments which have been in the trash for EMPTY_TRASH_DAYS. */
!defined( &#039;EMPTY_TRASH_DAYS&#039; ) &amp;&amp; define( &#039;EMPTY_TRASH_DAYS&#039;, 300 );</pre>
<hr class="C" />
<h2>Debugging WordPress</h2>
<p>One of my secrets for getting really good at this stuff is to master debugging.  There is really not ever a time when I am working on a site that I don't have <a href="http://www.askapache.com/security/elite-log-file-scrolling-with-color-syntax.html">color-highlighted logs scrolling automatically in an ssh window</a>.  It's really almost impossible to fix problems with wordpress or do any kind of advanced anything without being able to view debugging info.  At first I relied heavily on a <a href="http://www.askapache.com/php/custom-phpini-tips-and-tricks.html">custom php.ini</a> being available on the server, but after having to deal with many hosts who don't allow <code>php.ini</code> files I now rely completely on setting values using <a href="http://php.net/manual/en/function.ini-set.php">ini_set</a> for ultimate portability. Detailed towards the end of this article and is also included in this <code>wp-config.php</code></p>
<pre>/**#@+
 * DEBUGGING STUFF
 */
/** display of notices during development. if false, error_reporting is E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING | E_RECOVERABLE_ERROR otherwise E_ALL */
!defined(&#039;WP_DEBUG&#039;) &amp;&amp; define(&#039;WP_DEBUG&#039;, false);
&nbsp;
/** The SAVEQUERIES definition saves the database queries to a array and that array can be displayed to help analyze those queries.
 *  The information saves each query, what function called it, and how long that query took to execute.  */
!defined(&#039;SAVE_QUERIES&#039;) &amp;&amp; define(&#039;SAVE_QUERIES&#039;, WP_DEBUG);
&nbsp;
!defined(&#039;ACTION_DEBUG&#039;) &amp;&amp; define(&#039;ACTION_DEBUG&#039;, WP_DEBUG);
&nbsp;
/** This will allow you to edit the scriptname.dev.js files in the wp-includes/js and wp-admin/js directories.  */
!defined(&#039;SCRIPT_DEBUG&#039;) &amp;&amp; define(&#039;SCRIPT_DEBUG&#039;, WP_DEBUG);
&nbsp;
/** Add define(&#039;WP_DEBUG_LOG&#039;, true); to enable php debug logging to WP_CONTENT_DIR/debug.log */
//!defined(&#039;WP_DEBUG_LOG&#039;) &amp;&amp; define(&#039;WP_DEBUG_LOG&#039;, true);
&nbsp;
/** This determines whether errors should be printed to the screen as part of the output or if they should be hidden from the user.
 *  Add define(&#039;WP_DEBUG_DISPLAY&#039;, false); to wp-config.php to use the globally configured setting for display_errors and not force it to On */
!defined(&#039;WP_DEBUG_DISPLAY&#039;) &amp;&amp; define(&#039;WP_DEBUG_DISPLAY&#039;, false);</pre>
<hr class="C" />
<h2>Ultimate Security Tweaks</h2>
<p>Well, ultimate for WP's built-in keys and password functions, this is all for wp-config.php keep in mind.  This is a very neccessary and recommended step, and is one of the only things I modify for each new installation.</p>
<h3>Security KEYS</h3>
<p>If like me you are familiar with password-cracking software like John the ripper, rainbow hash tables, l0pht-crack, etc.. then you will like to know that you can specify your own keys and salts for the encryption used by WP.  They are <code>AUTH_KEY</code>, <code>AUTH_SALT</code>, <code>SECURE_AUTH_KEY</code>, <code>SECURE_AUTH_SALT</code>, <code>LOGGED_IN_KEY</code>, <code>LOGGED_IN_SALT</code>, <code>NONCE_KEY</code>, <code>NONCE_SALT</code>, <code>SECRET_KEY</code> and <code>SECRET_SALT</code>.</p>
<p>A random and long key gives you better encryption, and exponentially increasing that is using a random and long salt for the encryption.  Encryptions with known salts are incredibly easy to decrypt compared to encryptions with secure salts, because the salt + key individually need to be guessed in order to find a matching hash, vs. just the key if the salt is known.  See: <a href="http://www.askapache.com/security/locating-weak-passwords.html">Locating weak passwords</a>.</p>
<blockquote>
    <p>A secret key is a hashing salt which makes your site harder to hack and access harder to crack by adding random elements to the password.</p>
    <p>In simple terms, a secret key is a password with elements that make it harder to generate enough options to break through your security barriers. A password like "password" or "test" is simple and easily broken. A random, unpredictable password such as "88a7da62429ba6ad3cb3c76a09641fc" takes years to come up with the right combination.</p>
</blockquote>
<p>For more information on the technical background and breakdown of secret keys and secure passwords, see: </p>
<ul>
    <li><a href="http://wordpress.org/support/topic/170987">WordPress Support Forum - HOWTO: Set up secret keys in WordPress 2.6+</a></li>
    <li><a href="http://en.wikipedia.org/wiki/Password_cracking">Wikipedia's explanation of Password Cracking</a></li>
</ul>
<p>I like to use the <a href="https://api.wordpress.org/secret-key/1.1/">WordPress.org secret-key service</a> 4 times.  That's because for each key and salt I like to do: (1 key from api +random keyboard input+1 key from api).</p>
<pre>/**#@+
 * Authentication Unique Keys.
 *
 * Change these to different unique phrases!
 * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/ WordPress.org secret-key service}
 * You can change these at any point in time to invalidate all existing cookies.
 * This will force all users to have to log in again.
 *
 * @since 2.6.0
 *
 * Get salt to add to hashes to help prevent attacks.
 *
 * The secret key is located in two places: the database in case the secret key
 * isn&#039;t defined in the second place, which is in the wp-config.php file. If you
 * are going to set the secret key, then you must do so in the wp-config.php
 * file.
 *
 * The secret key in the database is randomly generated and will be appended to
 * the secret key that is in wp-config.php file in some instances. It is
 * important to have the secret key defined or changed in wp-config.php.
 *
 * If you have installed WordPress 2.5 or later, then you will have the
 * SECRET_KEY defined in the wp-config.php already. You will want to change the
 * value in it because hackers will know what it is. If you have upgraded to
 * WordPress 2.5 or later version from a version before WordPress 2.5, then you
 * should add the constant to your wp-config.php file.
 *
 * Below is an example of how the SECRET_KEY constant is defined with a value.
 * You must not copy the below example and paste into your wp-config.php. If you
 * need an example, then you can have a
 * {@link https://api.wordpress.org/secret-key/1.1/ secret key created} for you.
 *
 * Salting passwords helps against tools which has stored hashed values of
 * common dictionary strings. The added values makes it harder to crack if given
 * salt string is not weak.
 *
 * @since 2.5
 * @link https://api.wordpress.org/secret-key/1.1/ Create a Secret Key for wp-config.php
 *
 * @return string Salt value from either &#039;SECRET_KEY&#039; or &#039;secret&#039; option
 */
define(&#039;AUTH_KEY&#039;,        &#039;jflkhaskljdfhkljasdhflkjashd;flkjhas;djfh;kajshdflkjashdlfkjhasdlkfhal?p[B+GR{@&gt;{Yq`c|LnG;dvq#| %OA_cbBSU6,rICC1o/c)-|&#039;);
define(&#039;SECURE_AUTH_KEY&#039;, &#039;jflkhaskljdfhkljasdhflkjashd;flkjhas;djfh;kajshdflkjashdlfkjhasdlkfhal?Vp[Bb15baar8&amp;R-r&lt;[T|?(xhJJABGq+Ux+U$)-Hltp/&#039;);
define(&#039;LOGGED_IN_KEY&#039;,   &#039;jflkhaskljdfhkljasdhflkjashd;flkjhas;djfh;kajshdflkjashdlfkjhasdlkfhal?Vp[B&lt;5n6DG|YWnJ9tY2!M1L)`{-$LW~~Ia%.uCbn!P. 41o2$Z$4&#039;);
define(&#039;NONCE_KEY&#039;,       &#039;jflkhaskljdfhkljasdhflkjashd;flkjhas;djfh;kajshdflkjashdlfkjhasdlkfhal?Vp[Bgu&lt;wM*zewR0.{+m:bmrB?wj!B,4]Wo+4 Avk ApR-D?E&#039;);
define(&#039;SECRET_KEY&#039;,     &#039;jflkhaskljdfhkljasdhflkjashd;flkjhas;djfh;kajshdflkjashdlfkjhasdlkfhal?Vp[B52ugH6muE9r4._iZwoYKUybrqLPpv|d Xr+|yrqhUE&#039;);
&nbsp;
define(&#039;AUTH_SALT&#039;,        &#039;123423190847olqkfhladhfsldshafasdfasdf09a7f-90a87df98adfyapoiyaf9asd8f70a9s8d7f908a7sdf97W4qCdm~Ky%+%~PPa5b YEmDI%U[W!-B&#039;);
define(&#039;SECURE_AUTH_SALT&#039;, &#039;123423190847olqkfhladhfsldshafasdfasdf09a7f-90a87df98adfyapoiyaf9asd8f70a9s8d7f908a7sdf97W4qCdmad/7o6.AU3%9o-|Kqm]+eUqr-n~:ag&#039;);
define(&#039;LOGGED_IN_SALT&#039;,   &#039;123423190847olqkfhladhfsldshafasdfasdf09a7f-90a87df98adfyapoiyaf9asd8f70a9s8d7f908a7sdf97W4qCdmsLiCv@KJ{#wd(?qe(KcH3!&#039;);
define(&#039;NONCE_SALT&#039;,       &#039;123423190847olqkfhladhfsldshafasdfasdf09a7f-90a87df98adfyapoiyaf9asd8f70a9s8d7f908a7sdf97W4qCdmG9&gt;+wm 2)bS0Pd_+1rx0brX]ND8|&#039;);
define(&#039;SECRET_SALT&#039;,      &#039;123423190847olqkfhladhfsldshafasdfasdf09a7f-90a87df98adfyapoiyaf9asd8f70a9s8d7f908a7sdf97W4qCdm2&lt;&gt;))U|sty)+4vpWooKls/^[vN&#039;);
/**#@-*/</pre>
<hr class="C" />
<h2>Using SSL for Admin and Login</h2>
<p>SSL is kinda required from my point of view, it is just way to easy to sniff data off the wire otherwise.  At least with SSL you force them to use tools like burpsuite, paros proxy, webscarab, etc..</p>
<pre>/** @since 2.6.0  */
!defined(&#039;FORCE_SSL_ADMIN&#039;) &amp;&amp; define(&#039;FORCE_SSL_ADMIN&#039;, true);
&nbsp;
/** @since 2.6.0  */
!defined(&#039;FORCE_SSL_LOGIN&#039;) &amp;&amp; define(&#039;FORCE_SSL_LOGIN&#039;, true);</pre>
<h3>Mod_Rewrite to Force SSL</h3>
<p>This is pretty cool, it forces non-https for all urls except for /wp-admin and wp-login.php, which both require https.  It also checks for the logged_in_cookie, and if that is present in the request then it doesn't force non-https.  Kinda confusing if you don't have a <a href="http://www.askapache.com/htaccess/mod_rewrite-variables-cheatsheet.html">mod_rewrite cheatsheet</a>.</p>
<pre>RewriteCond %{THE_REQUEST} ^$ [OR]
RewriteCond %{REQUEST_URI} ^/(wp-admin|wp-login\.php).*$ [NC,OR]
RewriteCond %{HTTP_COOKIE} ^.*wp_li_sadfsdfasdf11b361cdsdfasdfasd=.*$ [NC]
RewriteRule .* - [S=1]
&nbsp;
RewriteCond %{HTTPS} =on [OR]
RewriteCond %{HTTP_HOST} !^www\.askapache\.com$ [NC]
RewriteRule .* http://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
&nbsp;
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(wp-admin/.*|wp-login\.php.*)\ HTTP/ [NC]
RewriteCond %{HTTPS} !=on
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]</pre>
<hr class="C" />
<h2>File System Permissions</h2>
<p><a class="IFR" href="http://www.askapache.com/security/chmod-umask-fileperms-stat-tricks.html"><img src="http://uploads.askapache.com/2008/11/danger-chmod-screenshot.png" alt="chmod, umask, file permissions test" title="chmod, umask, file permissions test" /></a>You can get a basic and solid intro on file permissions by reading: <a href="http://codex.wordpress.org/Changing_File_Permissions">Changing File Permissions</a>, or you can check out some of my <a href="http://www.askapache.com/security/chmod-umask-fileperms-stat-tricks.html">file permission research</a>.<br class="C" />
</p>
<pre>/** The permissions as octal number, usually 0644 for files, 0755 for dirs.
 *  http://codex.wordpress.org/Changing_File_Permissions
 *  if ( !$wp_filesystem-&gt;mkdir($remote_destination, FS_CHMOD_DIR) )
 */
!defined(&#039;FS_CHMOD_DIR&#039;) &amp;&amp; define(&#039;FS_CHMOD_DIR&#039;, (0755 &amp; ~ umask()));
!defined(&#039;FS_CHMOD_FILE&#039;) &amp;&amp; define(&#039;FS_CHMOD_FILE&#039;, (0644 &amp; ~ umask()));
/**#@-*/
&nbsp;
/** Define the timeouts for the connections. Only available after the construct is called to allow for per-transport overriding of the default. */
//stream_set_timeout( $stream, FS_TIMEOUT );
//!defined(&#039;FS_TIMEOUT&#039;) &amp;&amp; define(&#039;FS_TIMEOUT&#039;, 30);
&nbsp;
//$this-&gt;link = @ftp_connect($this-&gt;options[&#039;hostname&#039;], $this-&gt;options[&#039;port&#039;], FS_CONNECT_TIMEOUT);
//!defined(&#039;FS_CONNECT_TIMEOUT&#039;) &amp;&amp; define(&#039;FS_CONNECT_TIMEOUT&#039;, 30);
&nbsp;
// function get_filesystem_method($args = array(), $context = false) {
//  $method = defined(&#039;FS_METHOD&#039;) ? FS_METHOD : false; //Please ensure that this is either &#039;direct&#039;, &#039;ssh&#039;, &#039;ftpext&#039; or &#039;ftpsockets&#039;
//!defined(&#039;FS_METHOD&#039;) &amp;&amp; define(&#039;FS_METHOD&#039;, &#039;direct&#039;);
&nbsp;
/** These methods for the WordPress core, plugin, and theme upgrades try to determine the WordPress path, as reported by PHP, but symlink trickery can sometimes
 * &#039;muck this up&#039; so if you know the paths to the various folders on the server, as seen via your FTP user, you can manually define them in the wp-config.php file.
 * FS_METHOD forces the filesystem method. It should only be "direct", "ssh", "ftpext", or "ftpsockets".
 * FTP_BASE is the full path to the "base" folder of the WordPress installation.
 * FTP_CONTENT_DIR is the full path to the wp-content folder of the WordPress installation.
 * FTP_PLUGIN_DIR is the full path to the plugins folder of the WordPress installation.
 * FTP_PUBKEY is the full path to your SSH public key.
 * FTP_PRIKEY is the full path to your SSH private key.
 * FTP_USER is either user FTP or SSH username. Most likely these are the same, but use the appropriate one for the type of update you wish to do.
 * FTP_PASS is the password for the username entered for FTP_USER. If you are using SSH public key authentication this can be omitted.
 * FTP_HOST is the hostname:port combination for your SSH/FTP server. The standard FTP port is 21 and the standard SSH port is 22.
 */
//define(&#039;FS_METHOD&#039;, &#039;ftpext&#039;);
//define(&#039;FTP_BASE&#039;, &#039;/path/to/wordpress/&#039;);
//define(&#039;FTP_CONTENT_DIR&#039;, &#039;/path/to/wordpress/wp-content/&#039;);
//define(&#039;FTP_PLUGIN_DIR &#039;, &#039;/path/to/wordpress/wp-content/plugins/&#039;);
//define(&#039;FTP_PUBKEY&#039;, &#039;/home/username/.ssh/id_rsa.pub&#039;);
//define(&#039;FTP_PRIKEY&#039;, &#039;/home/username/.ssh/id_rsa&#039;);
//define(&#039;FTP_USER&#039;, &#039;username&#039;);
//define(&#039;FTP_PASS&#039;, &#039;password&#039;);
//define(&#039;FTP_HOST&#039;, &#039;ftp.example.org:21&#039;);
&nbsp;
/**
 * Block requests through the proxy.
 *
 * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
 * prevent plugins from working and core functionality, if you don&#039;t include api.wordpress.org.
 *
 * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL in your wp-config.php file
 * and this will only allow localhost and your blog to make requests.
 * The constant WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
 * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow.
 *
 * @since 2.8.0
 * @link http://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
/** @since 2.9  */
//!defined(&#039;WP_HTTP_BLOCK_EXTERNAL&#039;) &amp;&amp; define( &#039;WP_HTTP_BLOCK_EXTERNAL&#039;, false );
&nbsp;
/*
 * The constant WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
 * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow.
 *
 * @since 2.8.0
 * @link http://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
 * $accessible_hosts = preg_split(&#039;|,\s*|&#039;, WP_ACCESSIBLE_HOSTS);
 * return !in_array( $check[&#039;host&#039;], $accessible_hosts ); //Inverse logic, If its in the array, then we can&#039;t access it.
 */
//!defined(&#039;WP_ACCESSIBLE_HOSTS&#039;) &amp;&amp; define( &#039;WP_ACCESSIBLE_HOSTS&#039;, &#039;askapache.com,askapache.org&#039; );</pre>
<hr class="C" />
<h3>Cookies!</h3>
<p>There's always a little comfort in having non-default cookies for security (against auto-bots), and using shorter names also means smaller HTTP Packets.</p>
<p>The <code>$cookie_hash</code> is my hack to get around the fact that <code>COOKIEHASH</code> isn't definable in <code>wp-config</code>.</p>
<pre>/**#@+
 * COOKIES
 * Used to guarantee unique hash cookies @since 1.5 */
$cookie_hash=md5(WP_SITEURL);
&nbsp;
/** Set a cookie now to see if they are supported by the browser.
 * setcookie(TEST_COOKIE, &#039;WP Cookie check&#039;, 0, COOKIEPATH, COOKIE_DOMAIN);
 * @since 2.3.0 */
!defined(&#039;TEST_COOKIE&#039;) &amp;&amp; define(&#039;TEST_COOKIE&#039;, &#039;wp_tc&#039;);
&nbsp;
/* @since 2.6.0 */
!defined(&#039;LOGGED_IN_COOKIE&#039;) &amp;&amp; define(&#039;LOGGED_IN_COOKIE&#039;, &#039;wp_li_&#039; . $cookie_hash);
&nbsp;
/* @since 2.6.0 */
!defined(&#039;SECURE_AUTH_COOKIE&#039;) &amp;&amp; define(&#039;SECURE_AUTH_COOKIE&#039;, &#039;wp_sa_&#039; . $cookie_hash);
&nbsp;
/* @since 2.5.0 */
!defined(&#039;AUTH_COOKIE&#039;) &amp;&amp; define(&#039;AUTH_COOKIE&#039;, &#039;wp_a_&#039; . $cookie_hash);
&nbsp;
/* @since 2.0.0 */
!defined(&#039;PASS_COOKIE&#039;) &amp;&amp; define(&#039;PASS_COOKIE&#039;, &#039;wp_p_&#039; . $cookie_hash);
&nbsp;
/* @since 2.0.0 */
!defined(&#039;USER_COOKIE&#039;) &amp;&amp; define(&#039;USER_COOKIE&#039;, &#039;wp_u_&#039; . $cookie_hash);
&nbsp;
/* ok unset this var, its not needed as COOKIEHASH will have this value, but is not definable in wp-config.php */
unset($cookie_hash);
&nbsp;
/** @since 1.2.0 */
!defined(&#039;COOKIEPATH&#039;) &amp;&amp; define(&#039;COOKIEPATH&#039;, preg_replace(&#039;|https?://[^/]+|i&#039;, &#039;&#039;, WP_HOME . &#039;/&#039; ) );
&nbsp;
/** @since 1.5.0 */
!defined(&#039;SITECOOKIEPATH&#039;) &amp;&amp; define(&#039;SITECOOKIEPATH&#039;, preg_replace(&#039;|https?://[^/]+|i&#039;, &#039;&#039;, WP_SITEURL . &#039;/&#039; ) );
&nbsp;
/** @since 2.6.0 */
!defined(&#039;ADMIN_COOKIE_PATH&#039;) &amp;&amp; define( &#039;ADMIN_COOKIE_PATH&#039;, SITECOOKIEPATH . &#039;wp-admin&#039; );
&nbsp;
/** @since 2.6.0 */
!defined(&#039;PLUGINS_COOKIE_PATH&#039;) &amp;&amp; define( &#039;PLUGINS_COOKIE_PATH&#039;, preg_replace(&#039;|https?://[^/]+|i&#039;, &#039;&#039;, WP_PLUGIN_URL)  );
&nbsp;
/** @since 2.0.0 */
!defined(&#039;COOKIE_DOMAIN&#039;) &amp;&amp; define(&#039;COOKIE_DOMAIN&#039;, $_SERVER[&#039;SERVER_NAME&#039;]);</pre>
<hr class="C" />
<pre>/**
  * The WP_CACHE setting, if true, includes the wp-content/advanced-cache.php script, when executing wp-settings.php.
  * For an advanced caching plugin to use, static because you would only want one
  * if ( defined(&#039;WP_CACHE&#039;) )@include WP_CONTENT_DIR . &#039;/advanced-cache.php&#039;;
  */
!defined(&#039;WP_CACHE&#039;) &amp;&amp; define(&#039;WP_CACHE&#039;, true);
&nbsp;
/** WordPress Localized Language, defaults to en_US.
 *
 * Change this to localize WordPress.  A corresponding MO file for the chosen
 * language must be installed to wp-content/languages. For example, install
 * de.mo to wp-content/languages and set WPLANG to &#039;de&#039; to enable German
 * language support. */
!defined(&#039;WPLANG&#039;) &amp;&amp; define (&#039;WPLANG&#039;, &#039;en_US&#039;);
&nbsp;
/** Stores the location of the language directory. First looks for language folder in WP_CONTENT_DIR
 *   and uses that folder if it exists. Or it uses the "languages" folder in WPINC. @since 2.1.0 */
//!defined(&#039;WP_LANG_DIR&#039;) &amp;&amp; define(&#039;WP_LANG_DIR&#039;, ABSPATH . WPINC . &#039;/languages&#039;);
&nbsp;
/** LANGDIR defines what directory the WPLANG .mo file resides. If LANGDIR is not defined WordPress looks first to wp-content/languages and then wp-includes/languages for the .mo defined by WPLANG file.  Old static relative path maintained for limited backwards compatibility - won&#039;t work in some cases*/
//!defined(&#039;LANGDIR&#039;) &amp;&amp; define(&#039;LANGDIR&#039;, &#039;wp-content/languages&#039;);
&nbsp;
/** Stores the location of the WordPress directory of functions, classes, and core content. @since 1.0.0 */
//!defined(&#039;WPINC&#039;) &amp;&amp; define(&#039;WPINC&#039;, &#039;wp-includes&#039;);</pre>
<hr class="C" />
<h2>WPMU Stuff</h2>
<p>I personally don't use.</p>
<pre>/** Allows for the mu-plugins directory to be moved from the default location. @since 2.8.0 */
//!defined(&#039;WPMU_PLUGIN_DIR&#039;) &amp;&amp; define( &#039;WPMU_PLUGIN_DIR&#039;, WP_CONTENT_DIR . &#039;/mu-plugins&#039; ); // full path, no trailing slash
&nbsp;
/** Allows for the mu-plugins directory to be moved from the default location. @since 2.8.0 */
//!defined(&#039;WPMU_PLUGIN_URL&#039;) &amp;&amp; define( &#039;WPMU_PLUGIN_URL&#039;, WP_CONTENT_URL . &#039;/mu-plugins&#039; ); // full url, no trailing slash
&nbsp;
/** Allows for the mu-plugins directory to be moved from the default location. @since 2.8.0 */
//!defined( &#039;MUPLUGINDIR&#039; ) &amp;&amp; define( &#039;MUPLUGINDIR&#039;, &#039;wp-content/mu-plugins&#039; ); // Relative to ABSPATH.  For back compat.</pre>
<hr class="C" />
<h2>WordPress Database</h2>
<p>This is usually the only thing I have to manually edit when creating a new site, unless I just use the same DB and modify the $table_prefix, (farther down). I run everything I possibly can in UTF-8, but if you don't already know alot about character sets, wow it is one of the most confusing things so you may want to save learning about that topic for another day.  Otherwise the following are helpful (<em>and show how confusing character sets are!</em>)</p>
<ul>
    <li><a href="http://dev.mysql.com/doc/refman/5.0/en/charset-charsets.html">Character Sets and Collations MySQL Support</a></li>
    <li><a href="http://codex.wordpress.org/Converting_Database_Character_Sets">Converting Database Character Sets</a></li>
    <li><a href="http://dev.mysql.com/doc/refman/5.0/en/charset-unicode-sets.html">UTF-8 character sets</a> (<a href="http://en.wikipedia.org/wiki/UTF-8">UTF-8</a>)</li>
</ul>
<p>If you ever setup WP to use the builtin membership features, make sure you learn about the <code>CUSTOM_USER_TABLE</code> and <code>CUSTOM_USER_META_TABLE</code> constants, I've found them very helpful.</p>
<pre>/**#@+
 * MySQL settings
 */
/** The name of the database for WordPress */
define(&#039;DB_NAME&#039;, &#039;askapachewpblog75&#039;);
&nbsp;
/** The username to access the database */
define(&#039;DB_USER&#039;, &#039;askapache245d&#039;);
&nbsp;
/** The password for the username to access the database */
define(&#039;DB_PASSWORD&#039;, &#039;asdfklj2340&#039;);
&nbsp;
/** The hostname to connect to the database at */
define(&#039;DB_HOST&#039;, &#039;mysql.askapache.com&#039;);
&nbsp;
/** The charset of the database */
define(&#039;DB_CHARSET&#039;, &#039;utf8&#039;);
&nbsp;
/** The collation of the database */
define(&#039;DB_COLLATE&#039;, &#039;utf8_general_ci&#039;);</pre>
<hr class="C" />
<h2>$table_prefix</h2>
<p>The <code>$table_prefix</code> is the value placed in the front of your database tables. Change the value if you want to use something other than wp_ for your database prefix. Typically this is changed if you are <a href="http://codex.wordpress.org/Installing_Multiple_Blogs">installing multiple WordPress blogs</a> in the same database, and also for enhanced security.</p>
<p>Its a safe and good idea to change this value pre-installation to add more security to your WordPress blog. Exploits attempted against your WordPress blog by malicious crackers often are built with the premise that your blog uses the prefix wp_, by changing the value you mitigate some attack vectors. </p>
<pre>/**
 * WordPress Database Table prefix.
 *
 * You can have multiple installations in one database if you give each a unique
 * prefix. Only numbers, letters, and underscores please!
 */
$table_prefix  = &#039;ar15_&#039;;
&nbsp;
/** CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE are used to designated that the user and usermeta tables normally utilized by WordPress are not used, instead these values/tables are used to store your user information. */
//!defined(&#039;CUSTOM_USER_TABLE&#039;) &amp;&amp; define(&#039;CUSTOM_USER_TABLE&#039;, $table_prefix . &#039;my_users&#039;);
//!defined(&#039;CUSTOM_USER_META_TABLE&#039;) &amp;&amp; define(&#039;CUSTOM_USER_META_TABLE&#039;, $table_prefix . &#039;my_usermeta&#039;);</pre>
<h2>Setup PHP Ini Settings</h2>
<pre>
/** Turns the output of errors on or off, you really never want this on, you should only view errors by reading the log file. */
ini_set(&#039;display_errors&#039;, WP_DEBUG_DISPLAY);
&nbsp;
/** Tells whether script error messages should be logged to the server&#039;s error log or error_log. */
ini_set(&#039;log_errors&#039;, &#039;On&#039;);
&nbsp;
/** http://us.php.net/manual/en/timezones.php */
ini_set(&#039;date.timezone&#039;, &#039;America/Indianapolis&#039;);
&nbsp;
/** Where to log php errors */
ini_set(&#039;error_log&#039;, ASKAPACHE_ROOT . &#039;/logs/php_error.log&#039;);
&nbsp;
/** Set the memory limit, otherwise defaults to &#039;32M&#039; */
ini_set(&#039;memory_limit&#039;, WP_MEMORY_LIMIT);</pre>
<h2>Sessions are slow</h2>
<p>So I only use sessions when I have a specific use... In this case I need sessions only when one of the tools in the /online-tools/ directory is being used.  And that is for the <a href="http://www.askapache.com/security/php-captcha-anti-spam-example.html">captcha image</a>.  In the future I won't ever use sessions.</p>
<pre>if(preg_match( &#039;#^/online-tools/#&#039;,$_SERVER[&#039;REQUEST_URI&#039;])) session_start();</pre>
<h2>Include Custom Files</h2>
<p>Sure you could use the my-hacks.php that WP allows, or you can just stick your functions in your <code>TEMPLATEPATH/functions.php</code> file, but they are executed only after the wp-settings.php file, which may be too late for your file.</p>
<p>In the past I've also used the <a href="http://us2.php.net/manual/en/ini.core.php#ini.auto-prepend-file">auto_prepend_file</a> settings to run my script before anything (index.php) but I ran into some issues on different hosts, and it wasn't as portable.</p>
<p>This is useful because you can have a file with globally available functions that you can use in non-WP areas as well as WP areas.  I am moving away from this more and more as I learn more about classes and build plugins instead for portability.</p>
<pre>include_once ASKAPACHE_ROOT . &#039;/includes/myfunctions.inc&#039;;
&nbsp;
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . &#039;wp-settings.php&#039;);
?&gt;</pre>
<h2>Some Useful PHP</h2>
<p>I am constantly trying to make my sites and code more portable, so I am using plugins alot more to accomplish things that I use to do with separate php.  Here are some examples of minimal php.</p>
<pre>add_filter("the_generator", create_function(&#039;$a&#039;,&#039;return "";&#039;));
add_filter(&#039;the_content&#039;, create_function(&#039;$a&#039;, &#039;return ((is_feed())? $a."&lt;p&gt;&lt;a href=\"".get_permalink()."\"&gt;".get_the_title()."&lt;/a&gt; originally appeared on ".get_bloginfo("name").".&lt;/p&gt;" : $a);&#039;), 99999);
add_filter(&#039;excerpt_length&#039;, create_function(&#039;$a&#039;, &#039;return 300;&#039;),99);
add_filter(&#039;excerpt_more&#039;, create_function(&#039;$a&#039;, &#039;return "&amp;hellip;";&#039;),99);
add_action( &#039;wp_head&#039;, create_function(&#039;$a&#039;,&#039;echo "&lt;link rel=\"pingback\" href=\"&#039;.get_bloginfo(&#039;pingback_url&#039;).&#039;\" /&gt;\n";&#039;), 95 );
add_action( &#039;wp_head&#039;, create_function(&#039;$a&#039;,&#039;echo "&lt;link rel=\"schema.rss\" href=\"http://purl.org/rss/1.0/\" /&gt;\n";&#039;), 96 );
add_action( &#039;wp_head&#039;, create_function(&#039;$a&#039;,&#039;echo "&lt;link rel=\"schema.rel\" href=\"http://purl.org/vocab/relationship/\" /&gt;\n";&#039;), 97 );
add_action( &#039;wp_head&#039;, create_function(&#039;$a&#039;,&#039;echo "&lt;link rel=\"meta\" type=\"application/rdf+xml\" href=\"/foaf.rdf\" /&gt;\n";&#039;), 98 );
add_action( &#039;wp_head&#039;, create_function(&#039;$a&#039;,&#039;echo "&lt;link href=\"/favicon.ico\" rel=\"shortcut icon\" type=\"image/x-icon\" /&gt;\n";&#039;), 99 );</pre>
<h2>Debugging Note</h2>
<p><a href="http://wordpress.org/extend/plugins/askapache-debug-viewer/screenshots/"><img alt="AskApache Advanced Debugging Output" src="http://s.wordpress.org/extend/plugins/askapache-debug-viewer/screenshot-1.png?r=160129" title="AskApache Advanced Debugging Output" width="625" height="548" /></a>If you read this far than you probably know how important debugging is, but I sometimes like to stick the best tips deep in my articles to make sure only YOU find it.  GRTFM isn't used on this site, it's mostly a requirement because my writing can get pretty bad..  The point, debugging is more than a crucial requirement if you want to do anything cool.  Don't worry I got you.. check my <a href="http://wordpress.org/extend/plugins/askapache-debug-viewer/">AskApache Debug Viewer Plugin from the official WP site</a>.  It's pretty close to providing as verbose amount of information that I could possibly figure out how to get out of php, probably more than you have ever seen at least, I focused on quantity.  I use it all the time on new installs as there is no setup required and it tells me advanced information about the setup of the server, hacker code for sure.<br class="C" />
</p>
<p>Here's a quick function to see set global vars, I just think this is interesting code.</p>
<pre>function askapache_global_debug(){
  global $_GET,$_POST,$_COOKIE,$_SESSION,$_ENV,$_FILES,$_SERVER,$_REQUEST,$HTTP_POST_FILES,$HTTP_POST_VARS,$HTTP_SERVER_VARS,$HTTP_RAW_POST_DATA,$HTTP_GET_VARS,$HTTP_COOKIE_VARS,$HTTP_ENV_VARS;
  $gv=create_function(&#039;$n&#039;,&#039;global $$n; ob_start(); if ( is_array($$n) &amp;&amp; sizeof($$n)&gt;0 &amp;&amp; print("[{$n}]\n") ) print_r($$n);return ob_get_clean();&#039;);
  foreach (array(&#039;_GET&#039;,&#039;_POST&#039;,&#039;_COOKIE&#039;,&#039;_SESSION&#039;,&#039;_ENV&#039;,&#039;_FILES&#039;,&#039;_SERVER&#039;,&#039;_REQUEST&#039;,&#039;HTTP_POST_FILES&#039;,&#039;HTTP_POST_VARS&#039;,&#039;HTTP_SERVER_VARS&#039;,&#039;HTTP_RAW_POST_DATA&#039;,&#039;HTTP_GET_VARS&#039;,&#039;HTTP_COOKIE_VARS&#039;,&#039;HTTP_ENV_VARS&#039;) as $k)echo $gv($k);
  print_r(get_defined_constants());
}</pre>
<p class="anote">Also check the WordPress Codex page: <a href="http://codex.wordpress.org/Editing_wp-config.php">Editing wp-config.php</a> and Perishable Press's: <a href="http://perishablepress.com/press/2009/12/01/stupid-wordpress-tricks/">Stupid WordPress Tricks</a></p><p><a href="http://www.askapache.com/wordpress/advanced-wp-config-php-tweaks.html"></a><a href="http://www.askapache.com/wordpress/advanced-wp-config-php-tweaks.html">Advanced WordPress wp-config.php Tweaks</a> originally appeared on <cite>AskApache.com</cite> </p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/wordpress/advanced-wp-config-php-tweaks.html/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>AskApache Debug Viewer Plugin for WordPress</title>
		<link>http://www.askapache.com/wordpress/debug-viewer-plugin.html</link>
		<comments>http://www.askapache.com/wordpress/debug-viewer-plugin.html#comments</comments>
		<pubDate>Mon, 06 Apr 2009 03:53:31 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://www.askapache.com/?p=2502</guid>
		<description><![CDATA[<p><a class="IFL" href='http://uploads.askapache.com/2009/04/screenshot-1.png' title='screenshot-1'><img src="http://uploads.askapache.com/2009/04/screenshot-1-350x306.png" alt="screenshot-1" title="screenshot-1" width="350" height="306" /></a><strong>The story behind this plugin is sorta wack</strong>, but in a good way :).  While doing tons of security research on permissions, authorization, access, etc.. for the <a href="http://www.askapache.com/htaccess/htaccess-plugin-blocks-spam-hackers-and-password-protects-blog.html">Password Protection plugin</a> (<em><a href="http://www.askapache.com/htaccess/password-protection-plugin-status.html">still being worked on</a></em>), I needed to have unheard of debugging capabilities while working on the plugin on the various websites, webhosts, and test servers that I use to test in different environments.  So I hacked together a bunch of php code that helped me debug, actually I pretty much went overkill and tried to get as much debugging info as programmatically possible, and it ended up being so much code that I took it out of my Password Protection code and made it its own plugin.<br class="C" /></p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.askapache.com/wordpress/debug-viewer-plugin.html"></a><a href="http://www.askapache.com/wordpress/debug-viewer-plugin.html"><cite>AskApache.com</cite></a></p><p><a href="#php-debug-screenshots">Screen Shots</a> | <a href="#php-debug-functions">PHP Debug Functions</a></p>
<p><a class="IFL" href='http://uploads.askapache.com/2009/04/screenshot-1.png' title='screenshot-1'><img src="http://uploads.askapache.com/2009/04/screenshot-1-350x306.png" alt="AskApache Debug Viewer Plugin for WordPress" title="screenshot-1" width="350" height="306" /></a><strong>The story behind this plugin is sorta wack</strong>, but in a good way :).  While doing tons of security research on permissions, authorization, access, etc.. for the <a href="http://www.askapache.com/htaccess/htaccess-plugin-blocks-spam-hackers-and-password-protects-blog.html">Password Protection plugin</a> (<em><a href="http://www.askapache.com/htaccess/password-protection-plugin-status.html">still being worked on</a></em>), I needed to have unheard of debugging capabilities while working on the plugin on the various websites, webhosts, and test servers that I use to test in different environments.  So I hacked together a bunch of php code that helped me debug, actually I pretty much went overkill and tried to get as much debugging info as programmatically possible, and it ended up being so much code that I took it out of my Password Protection code and made it its own plugin.<br class="C" /></p>

<p>I've been using it for several months now while working on a plugin or diagnosing some issue, and decided that I'd share it with everyone.  Hopefully it will help other plugin authors and php programmers in general to start writing more robust and error-proof code, which would in turn help me!  To help those not using WordPress, I've included most of the debugging functions below, but you'll need the AskApacheDebug class for them to work.  Hope you find it useful!  I do.  <a href="http://wordpress.org/extend/plugins/askapache-debug-viewer/">Download AskApache Debug Viewer</a></p>
<hr class="C" />


<h2><a name="php-debug-screenshots" id="php-debug-screenshots"></a>Screenshots and Debug Output</h2>
<p>The plugin outputs the debugging info in the admin footer by hooking into the 'in_admin_footer' action.<br /><a href='http://uploads.askapache.com/2009/04/screenshot-2.png' title='screenshot-2'><img src="http://uploads.askapache.com/2009/04/screenshot-2.png" alt="AskApache Debug Viewer Plugin for WordPress" title="screenshot-2" /></a></p>

<p><a class="FL" style="border-right:5px solid #FFF;" href='http://uploads.askapache.com/2009/04/screenshot-3.png' title='screenshot-3'><img width="341" height="350" src="http://uploads.askapache.com/2009/04/screenshot-3-341x350.png" alt="AskApache Debug Viewer Plugin for WordPress" title="screenshot-3" /></a><a class="FL" style="border-right:5px solid #FFF;" href='http://uploads.askapache.com/2009/04/screenshot-4.png' title='screenshot-4'><img width="350" height="170" src="http://uploads.askapache.com/2009/04/screenshot-4-350x170.png" alt="AskApache Debug Viewer Plugin for WordPress" title="screenshot-4" /></a><br class="C" /></p>
<p><a class="FL" style="border-right:5px solid #FFF;" href='http://uploads.askapache.com/2009/04/screenshot-5.png' title='screenshot-5'><img width="350" height="285" src="http://uploads.askapache.com/2009/04/screenshot-5-350x285.png" alt="AskApache Debug Viewer Plugin for WordPress" title="screenshot-5" /></a><a class="FL" style="border-right:5px solid #FFF;" href='http://uploads.askapache.com/2009/04/screenshot-6.png' title='screenshot-6'><img width="350" height="285" src="http://uploads.askapache.com/2009/04/screenshot-6-350x285.png" alt="AskApache Debug Viewer Plugin for WordPress" title="screenshot-6" /></a><br class="C" /></p>
<p><a class="FL" style="border-right:5px solid #FFF;" href='http://uploads.askapache.com/2009/04/screenshot-7.png' title='screenshot-7'><img width="350" height="285" src="http://uploads.askapache.com/2009/04/screenshot-7-350x285.png" alt="AskApache Debug Viewer Plugin for WordPress" title="screenshot-7" /></a><a class="FL" style="border-right:5px solid #FFF;" href='http://uploads.askapache.com/2009/04/screenshot-8.png' title='screenshot-8'><img width="350" height="285" src="http://uploads.askapache.com/2009/04/screenshot-8-350x285.png" alt="AskApache Debug Viewer Plugin for WordPress" title="screenshot-8" /></a><br class="C" /></p>
<p><a class="FL" style="border-right:5px solid #FFF;" href='http://uploads.askapache.com/2009/04/screenshot-9.png' title='screenshot-9'><img width="350" height="285" src="http://uploads.askapache.com/2009/04/screenshot-9-350x285.png" alt="AskApache Debug Viewer Plugin for WordPress" title="screenshot-9" /></a><a class="FL" style="border-right:5px solid #FFF;" href='http://uploads.askapache.com/2009/04/screenshot-10.png' title='screenshot-10'><img width="350" height="285" src="http://uploads.askapache.com/2009/04/screenshot-10-350x285.png" alt="AskApache Debug Viewer Plugin for WordPress" title="screenshot-10" /></a><br class="C" /></p>




<h2><a name="php-debug-functions" id="php-debug-functions"></a>PHP Debugging Functions</h2>
<p>Ok so for those interested more in the php flavor, here are a few of the functions that produce the debugging output.  I'll start with my customized _stat function, which took a lot of research to write, but you can read that story at <a href="http://www.askapache.com/security/chmod-stat.html">Chmod, Umask, Stat, Fileperms, and File Permissions</a>.</p>

<pre>function _stat($fl)
{
  static $ftypes = false;
  if (!$ftypes)
  {
    $this-&gt;logg(__FUNCTION__ . &#039;:&#039; . __LINE__);
    $ftypes = array(S_IFSOCK =&gt; &#039;ssocket&#039;, S_IFLNK =&gt; &#039;llink&#039;, S_IFREG =&gt; &#039;-file&#039;, S_IFBLK =&gt; &#039;bblock&#039;, S_IFDIR =&gt; &#039;ddir&#039;, S_IFCHR =&gt; &#039;cchar&#039;, S_IFIFO =&gt; &#039;pfifo&#039;);
  }
&nbsp;
  $s = $ss = array();
  if (($ss = stat($fl)) === false) return $this-&gt;logg(__FUNCTION__ . &#039;:&#039; . __LINE__ . " Couldnt stat {$fl}", 0);
  $p = $ss[&#039;mode&#039;];
  $t = decoct($p &amp; S_IFMT);
  $q = octdec($t);
  $type = (array_key_exists($q, $ftypes)) ? substr($ftypes[$q], 0, 1) : &#039;?&#039;;
$s = array(
&#039;filename&#039; =&gt; $fl,
&nbsp;
&#039;human&#039; =&gt; ($type .
(($p &amp; S_IRUSR) ? &#039;r&#039; : &#039;-&#039;) . (($p &amp; S_IWUSR) ? &#039;w&#039; : &#039;-&#039;) . (($p &amp; S_ISUID) ? (($p &amp; S_IXUSR) ? &#039;s&#039; : &#039;S&#039;) : (($p &amp; S_IXUSR) ? &#039;x&#039; : &#039;-&#039;)) .
(($p &amp; S_IRGRP) ? &#039;r&#039; : &#039;-&#039;) . (($p &amp; S_IWGRP) ? &#039;w&#039; : &#039;-&#039;) . (($p &amp; S_ISGID) ? (($p &amp; S_IXGRP) ? &#039;s&#039; : &#039;S&#039;) : (($p &amp; S_IXGRP) ? &#039;x&#039; : &#039;-&#039;)) .
(($p &amp; S_IROTH) ? &#039;r&#039; : &#039;-&#039;) . (($p &amp; S_IWOTH) ? &#039;w&#039; : &#039;-&#039;) . (($p &amp; S_ISVTX) ? (($p &amp; S_IXOTH) ? &#039;t&#039; : &#039;T&#039;) : (($p &amp; S_IXOTH) ? &#039;x&#039; : &#039;-&#039;))),
&#039;octal&#039; =&gt; sprintf("%o", ($ss[&#039;mode&#039;] &amp; 007777)),
&#039;hex&#039; =&gt; sprintf("0x%x", $ss[&#039;mode&#039;]),
&#039;decimal&#039; =&gt; sprintf("%d", $ss[&#039;mode&#039;]),
&#039;binary&#039; =&gt; sprintf("%b", $ss[&#039;mode&#039;]),
&#039;base_convert&#039; =&gt; base_convert($ss[&#039;mode&#039;],10,8),
&#039;fileperms&#039; =&gt; fileperms($fl),
&#039;mode&#039; =&gt; $p,
&nbsp;
&#039;type_octal&#039; =&gt; sprintf("%07o", $q),  &#039;fileuid&#039; =&gt; $ss[&#039;uid&#039;],
&nbsp;
&#039;type&#039; =&gt; $type,
&#039;filegid&#039; =&gt; $ss[&#039;gid&#039;],
&#039;owner_name&#039; =&gt; $this-&gt;get_posix_info(&#039;user&#039;, $ss[&#039;uid&#039;],
&#039;name&#039;),
&#039;group_name&#039; =&gt; $this-&gt;get_posix_info(&#039;group&#039;, $ss[&#039;gid&#039;],
&#039;name&#039;),
&#039;dirname&#039; =&gt; dirname($fl),
&#039;is_file&#039; =&gt; is_file($fl) ? 1 : 0,
&#039;is_dir&#039; =&gt; is_dir($fl) ? 1 : 0,
&#039;is_link&#039; =&gt; is_link($fl) ? 1 : 0,
&#039;is_readable&#039; =&gt; is_readable($fl) ? 1 : 0,
&#039;is_writable&#039; =&gt;
is_writable($fl) ? 1 : 0,&#039;device&#039; =&gt; $ss[&#039;dev&#039;],
&#039;device_number&#039; =&gt; $ss[&#039;rdev&#039;],
&#039;inode&#039; =&gt; $ss[&#039;ino&#039;],
&#039;link_count&#039; =&gt; $ss[&#039;nlink&#039;],
&#039;size&#039; =&gt; $ss[&#039;size&#039;],
&#039;blocks&#039; =&gt; $ss[&#039;blocks&#039;],
&#039;block_size&#039; =&gt; $ss[&#039;blksize&#039;],
&#039;accessed&#039; =&gt; date(&#039;Y M D H:i:s&#039;, $ss[&#039;atime&#039;]),
&#039;modified&#039; =&gt; date(&#039;Y M D H:i:s&#039;, $ss[&#039;mtime&#039;]),
&#039;created&#039; =&gt; date(&#039;Y M D H:i:s&#039;, $ss[&#039;ctime&#039;]),
&#039;mtime&#039; =&gt; $ss[&#039;mtime&#039;], &#039;atime&#039; =&gt; $ss[&#039;atime&#039;],
&#039;ctime&#039; =&gt; $ss[&#039;ctime&#039;], );
  if (is_link($fl)) $s[&#039;link_to&#039;] = readlink($fl);
  if (realpath($fl) != $fl) $s[&#039;real_filename&#039;] = realpath($fl);
&nbsp;
  return $s;
}</pre>



<h3>get_debug_functions</h3>
<p>These are various security and user related information.  Nice.</p>

<pre>function get_debug_functions($vb=false)
{
  $functions=$oa=array();
  $functions = array(
&#039;PHP script Process ID&#039; =&gt; &#039;getmypid&#039;,
&#039;PHP script owners UID&#039; =&gt; &#039;getmyuid&#039;,
&#039;php_sapi_name&#039; =&gt; &#039;php_sapi_name&#039;,
&#039;PHP Uname&#039; =&gt; &#039;php_uname&#039;,
&#039;Zend Version&#039; =&gt; &#039;zend_version&#039;,
&#039;PHP INI Loaded&#039; =&gt; &#039;php_ini_loaded_file&#039;,
&#039;Current Working Directory&#039; =&gt; &#039;getcwd&#039;,
&#039;Last Mod&#039; =&gt; &#039;getlastmod&#039;,
&#039;Script Inode&#039; =&gt; &#039;getmyinode&#039;,
&#039;Script GID&#039; =&gt; &#039;getmygid&#039;,
&#039;Script Owner&#039; =&gt; &#039;get_current_user&#039;,
&#039;Get Rusage&#039; =&gt; &#039;getrusage&#039;,
&#039;Error Reporting&#039; =&gt; &#039;error_reporting&#039;,
&#039;Path name of controlling terminal&#039; =&gt; &#039;posix_ctermid&#039;,
&#039;Error number set by the last posix function that failed&#039; =&gt; &#039;posix_get_last_error&#039;,
&#039;Pathname of current directory&#039; =&gt; &#039;posix_getcwd&#039;,
&#039;posix_getpid&#039; =&gt; &#039;posix_getpid&#039;,
&#039;posix_uname&#039; =&gt; &#039;posix_uname&#039;,
&#039;posix_times&#039; =&gt;&#039;posix_times&#039;,
&#039;posix_errno&#039; =&gt; &#039;posix_errno&#039;,
&#039;Effective group ID of the current process&#039; =&gt; &#039;posix_getegid&#039;,
&#039;Effective user ID of the current process&#039; =&gt; &#039;posix_geteuid&#039;,
&#039;Real group ID of the current process&#039; =&gt; &#039;posix_getgid&#039;,
&#039;Group set of the current process&#039; =&gt; &#039;posix_getgroups&#039;,
&#039;Login name&#039; =&gt; &#039;posix_getlogin&#039;,
&#039;Current process group identifier&#039; =&gt; &#039;posix_getpgrp&#039;,
&#039;Current process identifier&#039; =&gt; &#039;posix_getpid&#039;,
&#039;Parent process identifier&#039; =&gt; &#039;posix_getppid&#039;,
&#039;System Resource limits&#039; =&gt; &#039;posix_getrlimit&#039;,
&#039;Return the real user ID of the current process&#039; =&gt; &#039;posix_getuid&#039;,
&#039;Magic Quotes GPC&#039; =&gt; &#039;get_magic_quotes_gpc&#039;,
&#039;Magic Quotes Runtime&#039; =&gt; &#039;get_magic_quotes_runtime&#039;, );
&nbsp;
  foreach ($functions as $title =&gt; $func_name) {
    $val = &#039;&#039;;
    if ( ( $this-&gt;checkfunction($func_name) &amp;&amp; ($val = $func_name()) !== false) ){
      if (empty($val)) $val=$func_name;
      $oa[$title] = $val;
    }
  }
&nbsp;
  return $oa;
}</pre>


<h3>get_debug_permissions</h3>
<p>This is a function designed to get as much information about file/user/group permissions as possible.</p>

<pre>function get_debug_permissions($vb=false)
{
  $oa=array();
&nbsp;
  $user_info = $this-&gt;get_posix_info(&#039;user&#039;);
  $group_info = $this-&gt;get_posix_info(&#039;group&#039;);
&nbsp;
$functions = array(
&#039;Real Group ID&#039; =&gt; posix_getgid(),
&#039;Effective Group ID&#039; =&gt; posix_getegid(),
&#039;Parent Process ID&#039; =&gt; posix_getppid(),
&#039;Parent Process Group ID&#039; =&gt; posix_getpgid(posix_getppid()),
&#039;Real Process ID&#039; =&gt; posix_getpid(),
&#039;Real Process Group ID&#039; =&gt; posix_getpgid(posix_getpid()),
&#039;Process Effective User ID&#039; =&gt; posix_geteuid(),
&#039;Process Owner Username&#039; =&gt; $user_info[&#039;name&#039;],
&#039;File Owner Username&#039; =&gt; get_current_user(),
&#039;User Info&#039; =&gt; print_r($user_info, 1),
&#039;Group Info&#039; =&gt; print_r($group_info, 1),
&#039;RealPath&#039;  =&gt; realpath(__FILE__),
&#039;SAPI Name&#039; =&gt; (function_exists(&#039;php_sapi_name&#039;)) ? print_r(php_sapi_name(), 1) : &#039;&#039;,
&#039;Posix Process Owner&#039; =&gt; print_r(posix_getpwuid(posix_geteuid()), 1),
&#039;Scanned Ini&#039; =&gt; (function_exists(&#039;php_ini_scanned_files&#039;)) ? str_replace("\n", "", php_ini_scanned_files()) : &#039;&#039;,
&#039;PHP.ini Path&#039; =&gt; get_cfg_var(&#039;cfg_file_path&#039;),
&#039;Sendmail Path&#039; =&gt; get_cfg_var(&#039;sendmail_path&#039;),
&#039;Info about a group by group id&#039; =&gt; posix_getgrgid(posix_getegid()),
&#039;Process group id for Current process&#039; =&gt; posix_getpgid(posix_getpid()),
&#039;Process group id for Parent process&#039; =&gt; posix_getpgid(posix_getppid()),
&#039;Process group id of the session leader.&#039; =&gt; posix_getsid(posix_getpid()),
&#039;Info about a user by username&#039; =&gt; posix_getpwnam(get_current_user()),
&#039;Info about a user by user id&#039; =&gt; posix_getpwuid(posix_geteuid()),
&#039;Apache Version&#039; =&gt; (function_exists(&#039;apache_get_version&#039;)) ? print_r(apache_get_version(), 1) : &#039;&#039;,
&#039;Apache Modules&#039; =&gt; (function_exists(&#039;apache_get_modules&#039;)) ? print_r(apache_get_modules(), 1) : &#039;&#039;,
&#039;PHP_LOGO_GUI&#039; =&gt; php_logo_guid(),
&#039;ZEND_LOGO_GUI&#039; =&gt; zend_logo_guid()
);
&nbsp;
  foreach ($functions as $title =&gt; $v) $oa[$title] = $v;
&nbsp;
  return $oa;
}</pre>



<h3>get_debug_defined</h3>
<p>This gets all the defined constants, if verbose it gets more and gets the values for each.</p>

<pre>function get_debug_defined($vb=false)
{
  $oa=array();
  foreach ((array)@get_defined_constants() as $k =&gt; $v){if (!$vb &amp;&amp; in_array($k, array(&#039;ABSPATH&#039;, &#039;WP_ADMIN&#039;))) $vb = true;  if($vb)$oa[$k]=$v;}
&nbsp;
  foreach (
  array(&#039;WP_TEMP_DIR&#039;, &#039;WP_SITEURL&#039;, &#039;WP_HOME&#039;, &#039;ABSPATH&#039;, &#039;WP_CONTENT_URL&#039;,
  &#039;WP_CONTENT_DIR&#039;, &#039;WP_PLUGIN_DIR&#039;, &#039;WP_PLUGIN_URL&#039;, &#039;WP_LANG_DIR&#039;, &#039;TEMPLATEPATH&#039;,
  &#039;STYLESHEETPATH&#039;, &#039;WPINC&#039;, &#039;COOKIEPATH&#039;, &#039;SITECOOKIEPATH&#039;, &#039;ADMIN_COOKIE_PATH&#039;,
  &#039;PLUGINS_COOKIE_PATH&#039;, &#039;PHP_SAPI&#039;, &#039;PHP_OS&#039;, &#039;PHP_VERSION&#039;
  ) as $def) if (defined($def) &amp;&amp; $val = constant($def) &amp;&amp; !empty($val)) $oa[$def] = $val;
&nbsp;
  return $oa;
}</pre>


<h3>get_debug_inis</h3>
<p>This function gets the values of your php ini, if verbose it gets them all and shows the currently used value instead of both the global and local.</p>

<pre>function get_debug_inis($vb=false)
{
  $oa=array();
&nbsp;
  foreach (array(&#039;Error Log&#039; =&gt; &#039;error_log&#039;,
&#039;Session Data Path&#039; =&gt; &#039;session.save_path&#039;,
&#039;Upload Tmp Dir&#039; =&gt; &#039;upload_tm_p_dir&#039;,
&#039;Include Path&#039; =&gt; &#039;include_path&#039;,
&#039;Memory Limit&#039; =&gt; &#039;memory_limit&#039;,
&#039;Max Execution Time&#039; =&gt; &#039;max_execution_time&#039;,
&#039;Display Errors&#039; =&gt; &#039;display_errors&#039;,
&#039;Allow url fopen&#039; =&gt; &#039;allow_url_fopen&#039;,
&#039;Disabled Functions&#039; =&gt; &#039;disable_functions&#039;,
&#039;Safe Mode&#039; =&gt; &#039;safe_mode&#039;,
&#039;Open Basedir&#039; =&gt; &#039;open_basedir&#039;,
&#039;File Uploads&#039; =&gt; &#039;file_uploads&#039;,
&#039;Max Upload Filesize&#039; =&gt; &#039;upload_max_filesize&#039;,
&#039;Max POST Size&#039; =&gt; &#039;post_max_size&#039;,
&#039;Open Basedir&#039; =&gt; &#039;open_basedir&#039;) as $title =&gt; $ini_name) if (($val = &#039;&#039; &amp;&amp; $val = strval(ini_get($ini_name))) !== false &amp;&amp; !empty($val)) $oa[$title] = $val;
&nbsp;
  if($vb!==false){
    foreach ((array)@ini_get_all() as $k =&gt; $v) $oa[$k] = (($v[&#039;global_value&#039;] == $v[&#039;local_value&#039;]) ? $v[&#039;global_value&#039;] : $v);
  }
  return $oa;
}</pre>


<h3>get_debug_phpinfo</h3>
<p>I'm particularly proud of this function because the preg_replace was tough and the result is a perfect array of values returned by the phpinfo command.</p>

<pre>function get_debug_phpinfo()
{
  $oa=array();
  ob_start();
  phpinfo(-1);
  $oa = preg_replace(array(&#039;#^.*&lt;body&gt;(.*)&lt;/body&gt;.*$#ms&#039;, &#039;#&lt;h2&gt;PHP License&lt;/h2&gt;.*$#ms&#039;, &#039;#&lt;h1&gt;Configuration&lt;/h1&gt;#&#039;, "#\r?\n#", "#&lt;/(h1|h2|h3|tr)&gt;#", &#039;# +&lt;#&#039;, "#[ \t]+#", &#039;#&amp;nbsp;#&#039;, &#039;#  +#&#039;, &#039;# class=".*?"#&#039;, &#039;%&amp;#039;%&#039;, &#039;#&lt;tr&gt;(?:.*?)" src="(?:.*?)=(.*?)" alt="PHP Logo" /&gt;&lt;/a&gt;&#039; . &#039;&lt;h1&gt;PHP Version (.*?)&lt;/h1&gt;(?:\n+?)&lt;/td&gt;&lt;/tr&gt;#&#039;,
    &#039;#&lt;h1&gt;&lt;a href="(?:.*?)?=(.*?)"&gt;PHP Credits&lt;/a&gt;&lt;/h1&gt;#&#039;, &#039;#&lt;tr&gt;(?:.*?)" src="(?:.*?)=(.*?)"(?:.*?)Zend Engine (.*?),(?:.*?)&lt;/tr&gt;#&#039;, "#  +#", &#039;#&lt;tr&gt;#&#039;, &#039;#&lt;/tr&gt;#&#039;), array(&#039;$1&#039;, &#039;&#039;, &#039;&#039;, &#039;&#039;, &#039;&lt;/$1&gt;&#039; . "\n", &#039;&lt;&#039;, &#039; &#039;, &#039; &#039;, &#039; &#039;, &#039;&#039;, &#039; &#039;, &#039;&lt;h2&gt;PHP Configuration&lt;/h2&gt;&#039; . "\n" . &#039;&lt;tr&gt;&lt;td&gt;PHP Version&lt;/td&gt;&lt;td&gt;$2&lt;/td&gt;&lt;/tr&gt;&#039; . "\n" . &#039;&lt;tr&gt;&lt;td&gt;PHP Egg&lt;/td&gt;&lt;td&gt;$1&lt;/td&gt;&lt;/tr&gt;&#039;,
    &#039;&lt;tr&gt;&lt;td&gt;PHP Credits Egg&lt;/td&gt;&lt;td&gt;$1&lt;/td&gt;&lt;/tr&gt;&#039;, &#039;&lt;tr&gt;&lt;td&gt;Zend Engine&lt;/td&gt;&lt;td&gt;$2&lt;/td&gt;&lt;/tr&gt;&#039; . "\n" . &#039;&lt;tr&gt;&lt;td&gt;Zend Egg&lt;/td&gt;&lt;td&gt;$1&lt;/td&gt;&lt;/tr&gt;&#039;, &#039; &#039;, &#039;%S%&#039;, &#039;%E%&#039;), ob_get_clean());
  $sections = explode(&#039;&lt;h2&gt;&#039;, strip_tags($oa, &#039;&lt;h2&gt;&lt;th&gt;&lt;td&gt;&#039;));
  unset($sections[0]);
  $oa = array();
  foreach ($sections as $section)
  {
    $n = substr($section, 0, strpos($section, &#039;&lt;/h2&gt;&#039;));
    preg_match_all(&#039;#%S%(?:&lt;td&gt;(.*?)&lt;/td&gt;)?(?:&lt;td&gt;(.*?)&lt;/td&gt;)?(?:&lt;td&gt;(.*?)&lt;/td&gt;)?%E%#&#039;, $section, $askapache, PREG_SET_ORDER);
    foreach ($askapache as $m) $oa[$n][$m[1]] = (!isset($m[3]) || $m[2] == $m[3]) ? $m[2] : array_slice($m, 2);
  }
  return $oa;
}</pre>




<h3>get_debug_included</h3>
<p>Gets a list of all the files included by php, if verbose it also super-stats them.</p>

<pre>function get_debug_included($vb=false)
{
  $oa=array();
  foreach((array)@get_included_files() as $k=&gt;$v) $oa[$v]=($vb===false) ? &#039;&#039; : $this-&gt;_stat($v);
  return $oa;
}</pre>








<h3>get_debug_classes</h3>
<p>Gets a list of predefined classes declared in your php instance, if verbose it gets EVERY class and also gets the methods for each.</p>

<pre>function get_debug_classes($vb=false)
{
  $classes=$oa=array();
  $classes= ($vb!==false) ? (array)@get_declared_classes() : array(&#039;WP&#039;,&#039;WP_Error&#039;,&#039;Walker&#039;,&#039;WP_Ajax_Response&#039;,&#039;wpdb&#039;,&#039;WP_Object_Cache&#039;,&#039;WP_Query&#039;,&#039;WP_Rewrite&#039;,&#039;WP_Locale&#039;);
  foreach ($classes as $k)  $oa[$k] = @get_class_methods($k);
&nbsp;
  return $oa;
}</pre>


<h3>get_debug_globals</h3>
<p>This function tries to get the values of every known (past and present) global variable in php.</p>

<pre>function get_debug_globals($vb=false)
{
  $oa=array();
&nbsp;
  $globs =
  array(
  &#039;GET&#039;     =&gt; isset( $_GET )?$_GET:&#039;&#039;,
  &#039;POST&#039;    =&gt; isset( $_POST )?$_POST:&#039;&#039;,
  &#039;COOKIE&#039;  =&gt; isset( $_COOKIE )?$_COOKIE:&#039;&#039;,
  &#039;SESSION&#039;   =&gt; isset( $_SESSION )?$_SESSION:&#039;&#039;,
  &#039;ENV&#039;     =&gt; isset( $_ENV )?$_ENV:&#039;&#039;,
  &#039;FILES&#039;     =&gt; isset( $_FILES )?$_FILES:&#039;&#039;,
  &#039;SERVER&#039;  =&gt; isset( $_SERVER )?$_SERVER:&#039;&#039;,
  &#039;SERVER&#039;  =&gt; isset( $_SERVER )?$_SERVER:&#039;&#039;,
  &#039;UPLOAD&#039;  =&gt; function_exists(&#039;wp_upload_dir&#039;) ? wp_upload_dir():&#039;&#039;,
  &#039;REQUEST&#039;   =&gt; isset( $_REQUEST )?$_REQUEST:&#039;&#039;,
  &#039;HTTP_POST_FILES&#039;   =&gt; isset( $HTTP_POST_FILES )?$HTTP_POST_FILES:&#039;&#039;,
  &#039;HTTP_POST_VARS&#039;    =&gt; isset( $HTTP_POST_VARS )?$HTTP_POST_VARS:&#039;&#039;,
  &#039;HTTP_SERVER_VARS&#039;  =&gt;  isset( $HTTP_SERVER_VARS )?$HTTP_SERVER_VARS:&#039;&#039;,
  &#039;HTTP_RAW_POST_DATA&#039; =&gt; isset( $HTTP_RAW_POST_DATA )?$HTTP_RAW_POST_DATA:&#039;&#039;,
  &#039;HTTP_GET_VARS&#039;     =&gt; isset( $HTTP_GET_VARS )?$HTTP_GET_VARS:&#039;&#039;,
  &#039;HTTP_COOKIE_VARS&#039;  =&gt;  isset( $HTTP_COOKIE_VARS )?$HTTP_COOKIE_VARS:&#039;&#039;,
  &#039;HTTP_ENV_VARS&#039;     =&gt; isset( $HTTP_ENV_VARS )?$HTTP_ENV_VARS:&#039;&#039;,
  );
  foreach ($globs as $k =&gt; $v) if (isset($v) &amp;&amp; sizeof($v) &gt; 0) $oa[$k] = $v;
&nbsp;
  foreach (array_keys($_SERVER) as $k) if ($val = strval($_SERVER[$k]) &amp;&amp; !empty($val)) $oa[(substr($k, 0, 5) == &#039;HTTP_&#039; ? &#039;HTTP&#039; : &#039;SERVER&#039;)][$k] = $_SERVER[$k];
&nbsp;
  return $oa;
}</pre>


<h3>get_debug_loaded_extensions</h3>
<p>Returns a list of all the loaded extensions in php.  If verbose it also returns their functions!</p>

<pre>function get_debug_loaded_extensions($vb=false)
{
  $oa=array();
  foreach((array)@get_loaded_extensions() as $k=&gt;$v) $oa[$v]= ($vb===false) ? &#039;&#039; : (array)@get_extension_funcs($v);
  return $oa;
}</pre><p><a href="http://www.askapache.com/wordpress/debug-viewer-plugin.html"></a><a href="http://www.askapache.com/wordpress/debug-viewer-plugin.html">AskApache Debug Viewer Plugin for WordPress</a> originally appeared on <cite>AskApache.com</cite> </p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/wordpress/debug-viewer-plugin.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

