<?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>Jonathan Dean &#187; php</title>
	<atom:link href="http://www.jonathandean.com/tag/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.jonathandean.com</link>
	<description>Web Development and Design</description>
	<lastBuildDate>Fri, 03 Feb 2012 22:49:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Dynamic config files in Symfony</title>
		<link>http://www.jonathandean.com/2010/09/dynamic-config-files-in-symfony/</link>
		<comments>http://www.jonathandean.com/2010/09/dynamic-config-files-in-symfony/#comments</comments>
		<pubDate>Thu, 09 Sep 2010 05:04:07 +0000</pubDate>
		<dc:creator>Jonathan Dean</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[symfony]]></category>

		<guid isPermaLink="false">http://www.jonathandean.com/?p=866</guid>
		<description><![CDATA[Don&#8217;t like the idea of manually setting certain values in your Symfony YAML configuration files? Or maybe, like in my case, you want the value of one setting to be set based on the value of a previous one, maybe a calculation of other values for instance. It may not be obvious at first but ...]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>Don&#8217;t like the idea of manually setting certain values in your Symfony YAML configuration files? Or maybe, like in my case, you want the value of one setting to be set based on the value of a previous one, maybe a calculation of other values for instance. It may not be obvious at first but you <em>can</em> include PHP blocks in your config files. You just need to be a little careful about the line endings in order for it to work properly. If you take a look at your apps/<em>application</em>/config/settings.yml there&#8217;s already an example in there in how to achieve this:</p>
<pre class="brush: plain; title: ; notranslate">
dev:
  .settings:
    error_reporting: &lt;?php echo ((E_ALL | E_STRICT) ^ E_NOTICE).&quot;\n&quot; ?&gt;
</pre>
<p>Here&#8217;s a (silly) example of what you may want to put in your app.yml:</p>
<pre class="brush: plain; title: ; notranslate">
&lt;?php $i = 10; ?&gt;
all:
  numbers:
    option1: &lt;?php echo ($i++) . &quot;\n&quot; ?&gt;
    option2: &lt;?php echo ($i++) . &quot;\n&quot; ?&gt;
    default: &lt;?php echo $i . &quot;\n&quot; ?&gt;
</pre>
<p>Just note &#8220;\n&#8221; at the end of the line as this is important. Without it the newline character won&#8217;t be added and the resulting YAML will be malformed. Also be really careful not to put any spaces or anything in front of a PHP block that doesn&#8217;t output anything, such as the first line in that example since that will also be malformed YAML. Just always remember to think of what the output will look like and that it must be valid YAML.</p>
<p><strong>Note:</strong> I&#8217;m using Symfony 1.4 and haven&#8217;t verified this in other versions.</p>
<div class="shr-publisher-866"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.jonathandean.com/2010/09/dynamic-config-files-in-symfony/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Running PHP and MySQL with phpMyAdmin on OS X 10.5</title>
		<link>http://www.jonathandean.com/2009/06/running-php-and-mysql-with-phpmyadmin-on-os-x-105/</link>
		<comments>http://www.jonathandean.com/2009/06/running-php-and-mysql-with-phpmyadmin-on-os-x-105/#comments</comments>
		<pubDate>Wed, 24 Jun 2009 00:32:27 +0000</pubDate>
		<dc:creator>Jonathan Dean</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.jonathandean.com/?p=311</guid>
		<description><![CDATA[Apache already comes pre-installed on OS X but PHP is not enabled by default. To enable PHP we need to edit our Apache config file by opening the Terminal and typing sudo nano /private/etc/apache2/httpd.conf and hitting enter (put in your admin password when it asks.) Type Control+W to bring up the search option and type ...]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>Apache already comes pre-installed on OS X but PHP is not enabled by default. To enable PHP we need to edit our Apache config file by opening the Terminal and typing <em>sudo nano /private/etc/apache2/httpd.conf </em>and hitting enter (put in your admin password when it asks.) Type Control+W to bring up the search option and type <em>php5_module</em> and hit enter. Remove the # from the beginning of that line and then type Control+X to exit, Y to save when it asks, and Enter to overwrite the same filename.</p>
<p>Next, we want to create our PHP config file since it isn&#8217;t there by default. In the Terminal type <em>cd /private/etc</em> and hit enter, then type <em>sudo cp php.ini.default php.ini</em> and hit enter. This makes a copy of the default configuration we can use to get started with. We&#8217;ll use that later. Now you can start up Apache by going to System Preferences, Sharing and checking the Web Sharing box. If it was already checked, uncheck it and then recheck it again to restart Apache to accept our changes.</p>
<p>Now you need to install MySQL. Luckily, there&#8217;s already an install package available at <a title="MySQL.com" href="http://mysql.com">MySQL.com</a> so head on over there and download the latest stable version of 5.X. Now extract the zip, open the dmg and run the .pkg installer. I would also recommend double-clicking the .prefPane file for quick access to startup and shutdown commands without needing the Terminal. I don&#8217;t necessarily recommend installing the MySQLStartupItem package unless you really need it. In fact, you really shouldn&#8217;t leave MySQL or your web server running at all when you aren&#8217;t using it.</p>
<p>Once MySQL is installed you need to start it up. If you installed the preference pane (the .prefPane file) you can just go into System Preferences and then click MySQL. From there just click the button to get it started. Now we are going to want to set a password for the root user. To do that just open up the Terminal and type <em>mysql</em> . If it can&#8217;t find the mysql command we can add it to your path by editing your bash profile. Just type <em>sudo nano ~/.bash_profile</em> in the Terminal to edit the file, entering your admin password when it asks. Then add a line that looks like this: <em>export PATH=/usr/local/mysql/bin:$PATH</em> and type Control+X, Y, Enter to quit and save your changes. Then you&#8217;ll need to reload your bash profile by typing <em>source ~/.bash_profile</em></p>
<p>Now you should be able to type <em>mysql</em> in the Terminal from any directory to connect to mysql. From the <em>mysql&gt; </em>prompt type the following, substituting <em>yourpassword</em> with your desired password and then hit enter: <em>set password for &#8216;root&#8217;@'localhost&#8217; = password(&#8216;yourpassword&#8217;);</em> To make sure it was effective, log out by typing <em>exit;</em> and then enter and log back in again but this time we want to supply our credentials. So type the following to show that we want to log in using the root user and a password: <em>mysql -u root -p</em></p>
<p>To make sure PHP can connect we need to edit our php configuration to know where the MySQL socket is located. For this type <em>sudo nano /private/etc/php.ini</em> from the Terminal. When the file opens type Control+W to bring up the search box and type in <em>mysql.default_socket</em> and hit enter. After the equals sign on that line enter <em>/tmp/mysql.sock</em> and and type Control+X, Y, Enter to quit and save your changes. Now we need to restart Apache for the change to take effect by going to System Preferences, Sharing and unchecking then rechecking the Web Sharing box. (Or via command-line if you wish.)</p>
<p>Now to install phpMyAdmin just download the latest and extract it into your Sites folder in your user account (/Users/<em>username</em>/Sites/) or the Apache root (/Library/WebServer/Documents/), whichever you prefer. Browse to that folder in the Terminal and type <em>mkdir config</em> to make the config folder and then <em>chmod o+rw config</em> to make it writable. Then browse to the setup folder in your browser, which would be http://localhost/~<em>user</em>/phpmyadmin/setup/ if you installed it in your user&#8217;s Sites folder or just http://localhost/phpmyadmin/setup/ if you put it in the Apache root. From there click the New Server button and then Save to take the defaults (unless you know other options you need) and then Save again in the Configuration File settings of the Overview page. Now you should be able to log into your server by going to either http://localhost/~<em>user</em>/phpmyadmin/ or http://localhost/phpmyadmin/ and entering your root username and password. It&#8217;s highly recommended that you create another user with fewer privledges to do most of your work, though.</p>
<p>If you also want to be able to use a .htaccess file you&#8217;ll need to go to the Terminal and type <em>sudo nano /private/etc/apache2/httpd.conf</em> to edit your Apache config file. Then type Control+W and search for <em>AllowOverride</em>. Change that option from <em>None</em> to <em>All</em> so that it reads <em>AllowOverride All</em> and then  type Control+X, Y, Enter to quit and save your changes. Now we need to do the same for each user account. Do this by typing <em>sudo nano /private/etc/apache2/users/</em>username<em>.conf</em> and making the same change. If you aren&#8217;t sure what users there are you can type <em>ls /private/etc/apache2/users/ . </em>After you make the changes you&#8217;ll need to restart Apache again.</p>
<p>Some of this I did today and other parts of it I did a while ago so if anyone wants to give it a run through and let me know how it turns out that would be great. I know it could use some screenshots but those will have to come later since I was already done with this when I decided to write the instructions out.</p>
<p>My final word on this is to be mindful of security and make sure no one who shouldn&#8217;t can access any applications that are running. I would recommend shutting down MySQL and Apache when you aren&#8217;t developing to keep risks to a minimum. I&#8217;m not going to go into security since I assume that you know what you&#8217;re doing but it was worth mentioning again that any servers running on your machine are a potential security risk if you don&#8217;t know how to keep it safe.</p>
<p>References:</p>
<p><a title="Foundation PHP" href="http://foundationphp.com/tutorials/php_leopard.php">http://foundationphp.com/tutorials/php_leopard.php</a></p>
<p><a title="MySQL Documentaion Tutorial" href="http://dev.mysql.com/doc/refman/5.1/en/tutorial.html">http://dev.mysql.com/doc/refman/5.1/en/tutorial.html</a></p>
<p><a title="phpMyAdmin Setup Tool" href="http://wiki.phpmyadmin.net/pma/Setup">http://wiki.phpmyadmin.net/pma/Setup</a></p>
<p><a title="Enabling .htaccess in OS X" href="http://www.clagnut.com/blog/350/">http://www.clagnut.com/blog/350/</a>  </p>
<div class="shr-publisher-311"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.jonathandean.com/2009/06/running-php-and-mysql-with-phpmyadmin-on-os-x-105/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Search engine friendly URLs in PHP and Apache, Take 2</title>
		<link>http://www.jonathandean.com/2008/12/search-engine-friendly-urls-in-php-and-apache-take-2/</link>
		<comments>http://www.jonathandean.com/2008/12/search-engine-friendly-urls-in-php-and-apache-take-2/#comments</comments>
		<pubDate>Wed, 03 Dec 2008 16:53:58 +0000</pubDate>
		<dc:creator>Jonathan Dean</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://jedean.com/?p=71</guid>
		<description><![CDATA[A while back I posted this article about friendly URLs in PHP and Apache. Today I&#8217;d like to update that a little to not only show another method but also to enhance it a bit. When we&#8217;re done we&#8217;ll have search engine friendly URLs that look like the ones that Blogger uses. Why? Because search ...]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>A while back I posted <a href="http://interactivedeveloper.blogspot.com/2008/03/friendly-urls-in-php-and-apache.html">this article about friendly URLs in PHP and Apache</a>. Today I&#8217;d like to update that a little to not only show another method but also to enhance it a bit. When we&#8217;re done we&#8217;ll have search engine friendly URLs that look like the ones that <a href="http://www.blogger.com/">Blogger</a> uses.</p>
<p>Why? Because search engines tend to penalize dynamic URLs in search result rankings so we want ours to appear as static as possible. Now I know that search engines have come a long way in indexing dynamic content but every little bit helps. So as long as the setup is easy (and it is) we may as well put in that tiny bit of extra effort. Why would static URLs get a higher ranking? I assume because creating a static page takes just a little more effort than a dynamic one and therefore you could argue that the content is likely to be of higher quality. Also, the content isn&#8217;t going to be compromised by spam bots that are mass posting or even stupid humans that are (mass) posting.</p>
<p>For an easy example, I&#8217;ve listed 5 URL formats that are common and could likely serve  the same content. They are in order with the most search engine friendly at the top.</p>
<ol>
<li>http://www.example.com/post/title-of-post.html</li>
<li>http://www.example.com/post/title-of-post</li>
<li>http://www.example.com/post/654123</li>
<li>http://www.example.com/post.php?id=654123</li>
</ol>
<p>#3 beats #4 for two reasons. The first is that #4 is obviously dynamic content based on the fact that it is passing a parameter whereas #3 could actually be pointing to the static file post/index.html or post/default.htm. The other reason is that id is considered an especially obvious parameter to dynamic content and is often ignored when indexing. Using post.php?postId=654123 would be slightly better.</p>
<p>#2 is a huge leap over #3 because it actually includes the title of the post in the URL. Of all the things you can do to improve SEO, including your search keywords in the URL is going to give you the best result (and even better if the keyword is in your domain name!) #1 is just a little better still because adding that .html extension really enforces the appearance of being static content. As far as the crawler is concerned there is no way to tell that URL is dynamic.</p>
<p>So how do we make this happen? Well if you&#8217;re using PHP and Apache 2 you have a few options. (Note, Apache 1 will not work here because it doesn&#8217;t support the &#8220;look back&#8221; method that allows Apache to keep looking back in the URL until it finds our file. Without that it would only be able to find /post in the /post/title-of-post/ directory rather than in the root which is where it actually is. That may make more sense later.)</p>
<p>I recently modified Method 3 of <a href="http://www.sitepoint.com/article/search-engine-friendly-urls/3/">this sitepoint article</a> to get set up quickly with the scheme. It&#8217;s not perfect but it is pretty fast and easy to get up and running with for small sites. If you have a lot of dynamic pages then you may want to combine this method with the <a href="http://interactivedeveloper.blogspot.com/2008/03/friendly-urls-in-php-and-apache.html">URL rewrite method</a> I posted about previously so that you don&#8217;t have to create lots of files without extensions and update your Apache configuration for each. I like this method because it&#8217;s easier to mix friendly URL pages with normal directories. I say that because the regex used in the other method requires that you have a file extension for accessing a normal file directly. So it will ignore /somedir/images/img.jpg and /somedir/index.php but it will try to parse /somedir/example/ which can be a bit of a pain. With this method we&#8217;re only going to worry about particular dynamic files and let the rest operate as usual. A drawback of this method is that you can&#8217;t use it on your root directory. For instance you can&#8217;t have http://www.example.com/dynamic-parameter.html. It would have to be something like http://www.example.com/processor/dyanamic-parameter.html.</p>
<p>Now to get down to it. We&#8217;re going to do a few things here:</p>
<ul>
<li>Create or modify our .htaccess file to tell Apache that certain files should be processed as PHP, even without an extension (or you could edit your vhost.conf file if you use Plesk or even your main Apache config if you feel comfortable)</li>
<li>Either remove the .php extension from our dynamic page or create a new file with the same name and no extension and use require_once() to include the .php version</li>
<li>Add some PHP to parse our URI and set variables we can use to load the dynamic content</li>
</ul>
<p>So for the first item we&#8217;re going to open or create a .htaccess in our web root (or whatever folder we want to contain the dynamic pages.) If you only have one dynamic page, say post.php, you&#8217;d do something like this, substituting &#8220;post&#8221; with the name of your dynamic page (minus the .php extension.)</p>
<pre class="brush: xml; title: ; notranslate">
&lt;Files post&gt;
AcceptPathInfo On
ForceType application/x-httpd-php
&lt;/Files&gt;
</pre>
<p>If you have multiple pages then use filesMatch instead of Files and separate each file with a pipe character (|):</p>
<pre class="brush: xml; title: ; notranslate">
&lt;filesMatch &quot;post|blog|login|logout&quot;&gt;
AcceptPathInfo On
ForceType application/x-httpd-php
&lt;/filesMatch&gt;
</pre>
<p>Basically what we&#8217;re doing here with ForceType is telling Apache that these are PHP files and to process them as such. Typically, the .php extension gives it away but we don&#8217;t want that here.</p>
<p>Now like I said above, you can either remove the .php extension from your file or create a new file and include the .php version. If you are converting existing pages to use this method I&#8217;d recommend leaving your .php version in tact in case of bookmarks or indexed pages. So alongside &quot;post.php&quot; you&#8217;d create the file &quot;post&quot; with this in it:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
require_once('post.php');
?&gt;
</pre>
<p>So now we have the option of getting to http://www.example.com/post.php by just using http://www.example.com/post and leaving off the file extension. The next thing we need to do is parse the rest of that URL and do something with it. You can do this a lot of ways but I kind of like options so I wrote a pretty generic function that will just give us some variables to work with. Cutting right to the chase:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

$uriParts = null;
$dirsToRoot = 0;
$pathToRoot = '';
$linkToRoot = '';
$requestURI = '';
$requestParamString = '';
$requestParams = null;
parseRequestURI();

function parseRequestURI()
{
    global $uriParts;
    global $requestURI;
    global $requestParamString;
    global $requestParams;

    $uriParts = explode('?', $_SERVER['REQUEST_URI']);
    if(is_array($uriParts) &amp;amp;&amp;amp; !empty($uriParts[1]))
    {
        $requestParamString = $uriParts[1];
        $requestURI = $uriParts[0];
    }
    else if(is_array($uriParts))
        $requestURI = $uriParts[0];
    else
        $requestURI = $_SERVER['REQUEST_URI'];

    if(!empty($requestParamString))
    {
        $requestParams = array();
        $paramPairs = explode('&amp;amp;', $requestParamString);
        if(is_array($paramPairs))
        {
            foreach($paramPairs as $paramPair)
            {
                $paramParts = explode('=', $paramPair);
                $requestParams[$paramParts[0]] = $paramParts[1];
            }
        }
        else
        {
            $paramParts = explode('=', $paramPairs);
            $requestParams[$paramParts[0]] = $paramParts[1];
        }
    }

    $uriParts = explode('/', $requestURI);
    if(is_array($uriParts))
    {
        if(empty($uriParts[0])) array_shift($uriParts);
        if(empty($uriParts[count($uriParts)-1])) array_pop($uriParts);
    }
    if(substr($uriParts[count($uriParts)-1], -5) === '.html')
        $uriParts[count($uriParts)-1] = substr($uriParts[count($uriParts)-1], 0, -5);

    setPathToRoot();
}

function setPathToRoot()
{
    global $uriParts;
    global $dirsToRoot;
    global $pathToRoot;
    global $linkToRoot;

    $dirsToRoot = count($uriParts)-1;

    for($i=0; $i&lt;$dirsToRoot; $i++)
        $pathToRoot .= '../';

    $linkToRoot = empty($pathToRoot) ? './' : $pathToRoot;
}
?&gt;
</pre>
<p>I think the easiest way to use this is to just define this script as an auto prepend file so that it runs at the beginning of every PHP file. You can do that by adding the following line to your .htaccess file:</p>
<pre class="brush: xml; title: ; notranslate">
php_value auto_prepend_file /path/to/file.php
</pre>
<p>If you&#8217;re going the auto prepend route make sure you have no whitespace characters outside of the &lt;?php and ?&gt; or you could end up with HTML validation issues. You don&#8217;t want whitespace showing up before your DOCTYPE declaration!</p>
<p>Anyway, this will give you access to the following variables on every PHP page:</p>
<ul>
<li>$requestURI (String): The requested URL (without your domain name) not including any request parameters</li>
<li>$requestParamString (String): The full key/value pair request parameter string after the ?</li>
<li>$uriParts (Array): An array of the individual parts of $requestURI. You are mostly going to use this to load your dynamic content. If the last entry has a .html then it will strip it out.</li>
<li>$requestParams (Array): An associative array of the key/value pairs of $requestParamString</li>
<li>$pathToRoot (String): Prepending this to a relative path will help resolve it properly for you. Used for including CSS and other files (see below)</li>
<li>$linkToRoot (String): Just like $pathToRoot but is used for linking to other pages (see below)</li>
<li>dirsToRoot (Integer): The number of directories your browser will think you are from the root</li>
</ul>
<p>Here are a few examples of what those variables will look like for different types of URLs:</p>
<p>http://www.example.com/post/something</p>
<pre class="brush: php; title: ; notranslate">
$requestURI='/post/something'
$requestParamString=''
$uriParts=Array ( [0] =&gt; post [1] =&gt; something )
$requestParams=
$pathToRoot='../../'
$linkToRoot='../../'
$dirsToRoot=2
</pre>
<p>http://www.example.com/post/something.html</p>
<pre class="brush: php; title: ; notranslate">
$requestURI='/post/something.html'
$requestParamString=''
$uriParts=Array ( [0] =&gt; post [1] =&gt; something )
$requestParams=
$pathToRoot='../../'
$linkToRoot='../../'
$dirsToRoot=2
</pre>
<p>http://www.example.com/post/something/more.html?name=jon&#038;city=pittsburgh</p>
<pre class="brush: php; title: ; notranslate">
$requestURI='/post/something/more.html'
$requestParamString='name=jon&amp;amp;amp;city=pittsburgh'
$uriParts=Array ( [0] =&gt; post [1] =&gt; something [2] =&gt; more )
$requestParams=Array ( [name] =&gt; jon [city] =&gt; pittsburgh )
$pathToRoot='../../../'
$linkToRoot='../../../'
$dirsToRoot=3
</pre>
<p>http://www.example.com/help</p>
<pre class="brush: php; title: ; notranslate">
$requestURI='/help'
$requestParamString=''
$uriParts=Array ( [0] =&gt; help )
$requestParams=
$pathToRoot=''
$linkToRoot='./'
$dirsToRoot=0
</pre>
<p>I think you can get the idea but a few things to point out here. First, the .html extension has no effect on the $uriParts string which is what we&#8217;re going to use to get our dynamic variables. Second, you probably would never pass the query string portion after the ? but I added it for completeness. </p>
<p>The purpose of $pathToRoot and $linkToRoot may not be entirely clear at first. It&#8217;s there in order to help with a relative path issue you may run into. The reason being is that the browser has no idea that /post is your PHP file and that your currently directory is actually the root of the site (or /). As far as it&#8217;s concerned, you&#8217;re in the folder /post/something/. So say you had an images folder in your site root alongside post.php. Typically you could just refer to it using just images/imagename.jpg and that relative path would resolve properly for you. However, your browser thinks you are in the /post/something/ directory so it&#8217;s going to think you mean /post/something/images/ rather than /images. Sure, you could just use the path /images/imagename.jpg but that only works if your application is at the site root. What if you want to move the site into a subfolder on another server? Or, like in my case, you want to use the Site Preview function in Plesk for your client but the path contains several subdirectories before your root? All you have to do is change images/imagename.jpg to &lt;?php echo $pathToRoot; ?&gt;images/imagename.jpg it will give you the correct relative path. Sure it can be a pain to print that out everywhere but it was a life saver for me to be able to have that kind of portability. (Of course this is great for including style sheets and JavaScript too.)  The only difference between $pathToRoot and $linkToRoot is that when $pathToRoot would normally be an empty string (see the last example above), $linkToRoot will be &#8220;./&#8221;.  When including CSS the empty string would basically indicate the current directory which is fine. For a link the empty string actually indicates the current <span style="font-style:italic;">page</span> so we need to use &#8220;./&#8221; to explicitly indicate current <span style="font-style:italic;">directory</span> so that the link actually takes us somewhere.</p>
<p>The last part of this puzzle is to do something with those dynamic URLs. Of course, that part is completely up to you. You essentially have two choices as I see it. You can either pass only the parameter values you need and always pass them in a particular order (such as /post/jon/2008-12-04/search-engine-urls) or you can pass your parameters as pairs that come in any order (such as /post/title/search-engine-urls/username/jon/date/2008-12-04). In most cases I prefer the first method but the second can be useful for pages where you don&#8217;t know all of the parameters being passed. In that case the even indexes of $uriParts will always be the parameter names and the odd indexes will always be the values. Or I guess you can do it the other way around too. The point is that this will get the data to you and now you just have to make something meaningful out of it.</p>
<p>This should go without saying but don&#8217;t forget to always escape any values being passed to a page before it interacts with your database. Take all precautions you normally would in a dynamic page!</p>
<p><strong>Update 12/14/2008:</strong> Removed a test for &#8216;/&#8217; as the last character in setPathToRoot(). All URLs are now treated the same way.</p>
<p><strong>Update 1/24/2009:</strong> Added $linkToRoot to solve an issue in some cases where $pathToRoot would be an empty string. This works well for including CSS files but not good for making a link to the home page. $linkToRoot is the same value as $pathToRoot except when $pathToRoot is an empty string.  In that case $linkToRoot will be &#8220;./&#8221;  </p>
<div class="shr-publisher-71"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.jonathandean.com/2008/12/search-engine-friendly-urls-in-php-and-apache-take-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Friendly URLs in PHP and Apache</title>
		<link>http://www.jonathandean.com/2008/03/friendly-urls-in-php-and-apache/</link>
		<comments>http://www.jonathandean.com/2008/03/friendly-urls-in-php-and-apache/#comments</comments>
		<pubDate>Mon, 17 Mar 2008 15:39:58 +0000</pubDate>
		<dc:creator>Jonathan Dean</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://jedean.com/?p=27</guid>
		<description><![CDATA[I&#8217;ve tried a few different ways of doing friendly URLs in PHP and all have their advantages and disadvantages. For a good introduction and some other methods that don&#8217;t necessarily require an Apache server, take a look at this sitepoint article. I&#8217;ve used Method 2 there before (.htaccess Error Pages) but I don&#8217;t like what ...]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>I&#8217;ve tried a few different ways of doing friendly URLs in PHP and all have their advantages and disadvantages.  For a good introduction and some other methods that don&#8217;t necessarily require an Apache server, take a look at <a href="http://www.sitepoint.com/article/search-engine-friendly-urls">this sitepoint article</a>.  I&#8217;ve used Method 2 there before (.htaccess Error Pages) but I don&#8217;t like what that does to your server logs.</p>
<p>For the method I use most often and am describing here, the credit goes to <a href="http://exanimo.com/">ex animo</a>.  He first showed me the .htaccess rewrite rule while we were working on a project at <a href="http://sunkingdigital.com/">sunKING</a> and I have only added a little of my own twist to it.</p>
<p>The basic idea is simple:</p>
<ol>
<li>You create a rewrite rule that redirects all web page requests to a single page
</li>
<li>This page parses the requested URL and determines what page to display</li>
<li>It&#8217;s so simple there is no step 3</li>
</ol>
<p>So let&#8217;s take a look at the .htaccess file you&#8217;ll have to make in order to redirect your web requests:</p>
<pre class="brush: xml; title: ; notranslate">
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?permalink=$1 [QSA,L]
</pre>
<p>If you&#8217;re quick on the uptake you&#8217;ll notice that all requests except those that have a period in them will be redirected to index.php and that it will get the request URI as a parameter.  The reason for not allowing the period is so that we can still access images and other static assets via their actual filename.  You don&#8217;t necessarily have to do this but I think it keeps things cleaner when you don&#8217;t have to parse URIs for images as well.  Not to mention that I can think of no good reason to have a friendly URL to an image or style sheet and can think of plenty of reasons not to.</p>
<p>Anyway, so what do we do with this?  Well, we want to set up index.php to parse the URI being passed in and display the page we want.  You can do this in any number of ways but here&#8217;s how I normally do my setup for most small sites.  My simplified index.php file will look something like this:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
define('INCLUDE_PATH', $_SERVER['DOCUMENT_ROOT'].'/../includes/');
ini_set('include_path', '.:'.INCLUDE_PATH);

// define the homepage
define('DEFAULT_PAGE', 'home');

// get the URI passed in via the .htaccess rewrite
$page = $_REQUEST['permalink'];
// set the page to be the homepage if none is given
$page = empty($page) ? DEFAULT_PAGE : $page;
// if the page doesn't exist, show an error page
$page = file_exists(INCLUDE_PATH.'pages/'.$page.'.php') ? $page : '404';

// I sometimes set page titles here to use a common header, but not necessary
switch($page)
{
    case '404':
        $pageTitle = 'page not found // ';
        break;
    case 'home':
        $pageTitle = 'home // ';
        break;
    case 'about':
        $pageTitle = 'about // ';
        break;
    case 'contact':
        $pageTitle = 'contact // ';
        break;
    case 'another/page':
        $pageTitle = 'another page // ';
        break;
    default:
        $pageTitle = '';
}

require_once('header.php'); // common header
require_once('pages/'.$page.'.php'); // requested page
require_once('footer.php'); // common footer
?&gt;
</pre>
<p>You can surely (and probably should) do a lot more processing here depending on your site&#8217;s needs, security concerns, etc. but this is the basic idea. Obviously, you want make sure those include (or require) statements reference the correct file locations. I usually simplify that by setting the include path as I have above.</p>
<p>Note that in the above example I have my includes directory outside of the public root so that the files aren&#8217;t directly web accessible.  Some servers can&#8217;t do this (such as ones running Plesk) so for those you&#8217;ll have to modify that first line to be like this and put the includes folder in a public directory: </p>
<pre class="brush: php; title: ; notranslate">
define('INCLUDE_PATH', $_SERVER['DOCUMENT_ROOT'].'/includes/');
</pre>
<p>So what&#8217;s left?  Not really anything.  All you have to do now is put your PHP files in the proper locations and you&#8217;re done.  So with the example above you would put the file about.php in your includes/pages folder in order to get to that page via http://example.com/about .  To get to http://example.com/about/me you would just put your me.php file inside of includes/pages/about/me.php .</p>
<p>In fact, in the time it took you to read to the bottom of this article you could have already had your site up.  Not too shabby, eh?</p>
<p>Just to help you get started I&#8217;ve created a zip file that you can just extract an upload to your server.  If you&#8217;re using <a href="http://mediatemple.net">Media Temple</a> or other hosts that work similarly you can just upload the contents to the root folder of the website (so the folder that is named like yourdomain.com).  The html folder in the zip is the public root (where you normally put your index.php or index.html file for your home page.)</p>
<p>If you&#8217;re using Plesk you&#8217;ll want to move things around just a little since it won&#8217;t let you include files out of the public root.  Just put the files in the html folder (index.php and .htaccess) into your httpdocs folder and throw the includes folder in there as well.  Then modify that first line that defines the INCLUDE_PATH constant for the new location as mentioned above.</p>
<p><a href="http://jonathandean.s3.amazonaws.com/code/friendly-urls.zip">Download the example site (.zip)</a>  </p>
<div class="shr-publisher-27"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.jonathandean.com/2008/03/friendly-urls-in-php-and-apache/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

