Friday, October 28, 2011

PHP - Print any variable easily

You often need to print some PHP variable right into the HTML code, but the variable is out of your current scope. Familiar problem, isn't it?

Here is a bright solution: PHP function that prints any global variable:


function print_var($var = 'domain', $url = '')
{
  global $$var, $$$var;
  if ($url != '')
    echo("<a href=\"$url\">${$var}</a>");
  else
    echo(${$var});
}

Moreover, you can pass some URL as a second parameter, and your variable becomes a clicable link :)

Some examples:


<?php print_var('page')?>
<?php print_var('domain', '/') ?>
<?php print_var('software', '/download/') ?>
<?php print_var('author', 'http://www.site.com') ?>

Sunday, October 16, 2011

Wordpress + Custom Scripts = Error 404

Wordpress is the most popular CMS in the world. Many sites are powered by Wordpress, plugins almost for every need are available. But...

If you decide to add some custom web scripts or other CMS to the domain where Wordpress is already installed, you'll get a problem with Error Handling. Wordpress shows Error 404 (File not found) for any URL that is not a part of Wordpress system!

Moreover, Wordpress changes standard error pages to its own ones. So if an error occurs outside Wordpress environment, the error message appears in Wordpress style anyway!

This can be fixed using .htaccess settings. At first you should exclude work folders form RewriteMode redirections. Add the following line into .htaccess file in the root of your site:

RewriteEngine On
RewriteBase /wordpress/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_URI} !^/(folder1|folder2)/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wordpress /index.php [L]

Then you should disable custom error page, at least in folders of your scripts. Add the following line to .htaccess files in your script folders. You can add this line to the root file as well, but sometimes it doesn't work:

ErrorDocument 404 default

This is enough if Wordpress is installed into a folder. But if Wordpress is installed into the root of the site, the solution may not work depending on CMS version and installed theme. Most probably you will need to fix some files manually to disable 404 error handling. The core is located in class-wp.php file:

function handle_404() {
...
$wp_query->set_404();
status_header( 404 );
...
}

BTW, Wordpress in the root of the site is not a best practice...