Archive for the 'PHP' Category

03rd May 2007

Change the maximum upload size with PHP

Depending on how you host your website (or application) there are different ways to change the PHP settings. In particular, the most asked about problem, changing the maximum upload size.

There are 3 settings PHP uses that limit your uploading ability:

  • post_max_size
    This is the combined maximum size of all files sent on the form. If you have 2 file fields on your form, the total filzesize of the 2 files must not exceed the post_max_size value.
  • upload_max_filesize
    This is the filesize limit of each individual file.
  • memory_limit
    PHP scripts have a memory limit, and generally speaking this can prevent some uploads from working. The limit should be set at a reasonable level, of course you won’t need 20mb for a simple ‘hello world’ script. Try slowly increasing this value if you find that uploads still aren’t working.

If you host your site remotely, you should check their documentation on how to change the PHP configuration settings. But if you’re not so inclined, and prefer a trial and error approach, here’s a summary of things to try:

Change php.ini directly

If you host your site on a server that you have access to, you can change your php.ini file directly. This is the easiest approach. Your php.ini file should exist in the PHP installation directory. Open it in your favourite text editor and search for these lines and change them:

memory_limit = 8M
post_max_size = 8M
upload_max_filesize = 2M

You may need to restart apache for the changes to take effect.

Changes to .htaccess

.htaccess files only apply to Apache webservers. They are files that append and change certain values that apache uses and they are placed in the root folder (and all folders beneath will use those settings). If apache uses PHP as a Module, then you can add values to the .htaccess file:

php_flag file_uploads On
php_value memory_limit 8M
php_value post_max_size 8M
php_value upload_max_filesize 2M
 

Download this code: .htaccess.txt

If you try this approach, and your webserver displays a 500 interal server error, then PHP is not runing as a module and apache didn’t like the php_value entries. You will need to remove your changes.

Upload a php.ini file

This generally works if the changes to .htaccess method doesn’t. Some web hosts that use apache, also use PHP as a CGI. Then also, most times, this allows changes to the PHP configuration using a custom php.ini file that you can upload. You don’t want to include every setting available to PHP in your file. Only include the ones you want to change, and don’t forget the heading [PHP]:

[PHP]
; Whether to allow HTTP file uploads.
file_uploads = On
; Maximum amount of memory a script may consume (8MB)
memory_limit = 8M
; Maximum size of POST data that PHP will accept.
post_max_size = 8M
; Maximum allowed size for uploaded files.
upload_max_filesize = 2M 

Download this code: php.ini

Still not working

In the event these techniques didn’t work for you, check with your host’s documentation.

Posted in Ajax File Browser, PHP | 6 Comments »

08th Feb 2007

How to use Gzip to load your site faster

Lately I’ve been reading various random articles about some browsers ability to deflate zipped webpages, so that there is less bandwidth and faster loading times for websites. Although this ability has been around for a while, it’s only been lately that I have a need to use it.

To understand the concept of page compression and the support for it, visit this site. But in short, most browsers support it, including IE6 and 7 (according to this test page).

For those rare browsers that do not support compression, they just receive a non-compressed page. So effectively, you’d be nuts not to use compression on your site. There’s nothing to lose (apart from a slight server load increase, but I’m told Slashdot uses compression even with it’s large amount of site hits).

Here is a real world example of a page compressed with Gzip:

Gzip in action

Here I’ve compressed the html document, css and javascript files. Look at the total, that page is 75% smaller, and 75% faster to load in your browser.

This tutorial will only examine one particular way of implementing Gzip compression with PHP, but there is another way to accomplish it with Apache if you have administration access to your server.

How to implement Gzip compression in 5 minutes

Step 1: Enable zlib compression in php. You can do this many ways, just choose one:

  • Add a line to your .htaccess file:
    php_flag zlib.output_compression On
  • Add or change a line in your php.ini file:
    zlib.output_compression = On
  • Add a line to the top of your PHP scripts before any output:
    ini_set(’zlib_output_compression’,'On’);

Now that you’ve done that (and particularly with the first 2 options), any file that is passed through PHP will be Gzipped if the browser supports it.

Step 2: If you want to compress other files, javascript, css, etc:

If your file does not pass through PHP before it is outputted, you can change the extension of the file to .php and it will be compressed. For this example I’ll use core.js.

  1. Rename core.js to something like core.js.php
  2. Open core.js.php in your favourite text editor and add this to the beggining of the file (before anything else) then save:
    <?php header("Content-type: text/js"); ?>

    Download this code: gzip_js_example.php

  3. Reference core.js.php in your html just as you would normally, the browser will see it as a JS file, not PHP:
    <script language="javascript" src="core.js.php" type="text/javascript"></script>

    Download this code: gzip_js_example.html

So to explain, we rename the file to make it a php file, so it is passed through the PHP compiler. Then we add a mime header line to the file, so that the browser knows what type of file it’s meant to be. Then we reference the file (if it’s a CSS or JS file for example) just as we normally would.

Remember to change the mime type to text/css for CSS files.

A quick note with this method. Only compress files that are specifically meant for a web browser (html, js, css, and xml). If you try this with a PDF file, for example, it works in browsers, but not when saved and displayed in Adobe PDF Reader.
If you’re finding that this method causes errors in your scripts, chances are that you haven’t got the zlib module installed with PHP.

Technorati: php, gzip, compression, browsers

Posted in PHP | Comments Off

28th Nov 2006

How to make a great ‘Go Back’ feature

You may or may not know about the PHP $_SERVER variable, HTTP_REFERER. It is meant to hold the URL of the previously visited page that the user has been to. Also, you may already use this variable in buttons or links to allow the user to “Go Back” to their previous page.

When I mentioned that the variable is meant to hold the data, unfortunately this is not always the case. A number of firewalls and other software stop the HTTP_REFERER header from being sent to the server, making any “Go Back” buttons or links on your site useless if you’re referring to this variable (Kerio Personal Firewall is one such application).

A recent look at my own logs tells me that over 25% of the users who download from this site hide their referring address. If you apply the same percentage to your site, that’s a lot of people who go nowhere when they click “Go Back”.

So what do you do? Save the current page to the $_SESSION array!

“But what a pain! having to do this for every page.”

Luckily for you I agree. So I’ve created a file you can include in your scripts to keep track of the users browsing history - automatically!

The script presents 2 constants to you: GOBACK and HISTORYWASPOSTED. GOBACK holds the URL of the previously visited page, and HISTORYWASPOSTED is either set to True or False depending if the user has reached that referring page by use of a POST form or not. Depending on the structure of your site, you’ll have to decide what the HISTORYWASPOSTED constant can do for you. You may not want a user to go back if they arrived at that page by a form. Your script might break without the right POST vars.

Finally, you can specify the history length at the top of the script.

<?php
//----------------------------------------------------------------
//  History - by JC
//  www.jc21.com
//----------------------------------------------------------------
//  Keeps a track of http referers even for those users that
//  disable referring (by firewall software or whatever).
//
//  Usage:  just include this file at the top of your script.
//  The constant variable GOBACK holds the referring page.
//  If that page was reached by a POST form submission, the constant
//  variable HISTORYWASPOSTED will be True.
//----------------------------------------------------------------
 
//Number of history entries. Change this to your liking.
define('HISTORY_MAX',20);
 
 
//Supress errors incase session has already been started.
@session_start();
// Check if here by post
if (count($_POST) > 0) {
	$_hbp = true;
} else {
	$_hbp = false;
}
// Check if history array exists and create if not.
if (!is_array($_SESSION['_HISTORY'])) {
	$_SESSION['_HISTORY'] = array();
}
//Check if this page is already on top
if ($_SESSION['_HISTORY'][1][0] == $_SERVER['REQUEST_URI'] && !$_SESSION['_HISTORY'][1][1]) {
	//We're going back trough our history!
	//Remove the first element of the array
	array_shift($_SESSION['_HISTORY']);
} elseif ($_SESSION['_HISTORY'][0][0] != $_SERVER['REQUEST_URI'] || ($_SESSION['_HISTORY'][0][0] == $_SERVER['REQUEST_URI'] && $_hbp)) {
	// Set this page as a referer.
	array_unshift($_SESSION['_HISTORY'],array($_SERVER['REQUEST_URI'],$_hbp));
}
//Trim array to x many history entries.
if (count($_SESSION['_HISTORY']) > (HISTORY_MAX+1)) {
	// get number of extras.
	$_e = (count($_SESSION['_HISTORY']) - (HISTORY_MAX+1));
	for ($x=0;$x<$_e;$x++) {
		array_pop($_SESSION['_HISTORY']);
	}
}
// Set GOBACK and HISTORYWASPOSTED
if (isset($_SESSION['_HISTORY'][0])) {
	define('GOBACK',$_SESSION['_HISTORY'][1][0]);
	define('HISTORYWASPOSTED',$_SESSION['_HISTORY'][1][1]);
} else {
	define('GOBACK',false);
	define('HISTORYWASPOSTED',false);
}
// Cleanup vars.
unset($_e,$_hbp);
?>

Download this code: history.inc.php

And here’s how you might use it:

<?php
include('history.inc.php');
?>
 
<p>Hello World</p>
 
<?php
//check if referring page wasn't result of a POST
if (!HISTORYWASPOSTED) {
	?>
	<p><a href="<?php echo GOBACK; ?>">Go Back</a></p>
	<?php
}
?>

Download this code: history_use.php

Posted in PHP | 2 Comments »

07th Nov 2006

Snippets Online

Today I launch another small database site.

Snippets.jc21.com is a database of useful pieces of code from any langauge you may use.

I often use different computers to code, or sometimes forget to backup my snippets before a re-format. So I made this site to keep a track of things.

The site allows full search and browsing capabilities, so you can easily find what you’re looking for. There are only a few gems there at the moment, but will be growing each day.
If you have any useful snippets or functions that you would like to share, submit them.

Posted in Javascript, PHP | 1 Comment »

03rd Nov 2006

Take your dynamic website anywhere with Outsite-In

The concept of a dynamic website relies largely on a Webserver, a database and a scripting language. Because of those needs, it seems that the thought of transferring a dynamic script driven application to a CD that could run on a PC without an internet connection would stump most people.

User InterfaceThe team over at Media Variations have made this thought into a reality. Using PHP, Apache and Mysql built-in, your scripts can have the same functionality as if it were running online. Sure you’re probably saying ‘I’ve seen other applications do this before,’ but not so easily!

The clean funky setup wizard makes it possible to transform your site to an executable to run from a CD or USB drive - you could even allow users to download your site from the web!

Some uses for this product are covered on their website. The cheap price tag for such a powerful easy to use tool makes this application real value for money. Take the 30day evaluation and prove me wrong!

Posted in PHP | 2 Comments »

01st Nov 2006

Zend and Microsoft Collaboration

Recently it was announced that Zend and Mirosoft are collaborating to ensure PHP will run on Windows IIS servers with equal (or close enough) performance of Linux/Apache servers.

While all reports claim that “it’s giving users another choice not to choose linux”, I find myself asking “Why would I want to use PHP on IIS?”

Once upon a time I used to run PHP as a CGI on IIS when I was starting out, something I don’t reccomend to anyone. It was slow, hard to setup and didn’t help me learn about the real world servers using Apaches’ modules.

The biggest feature of the LAMP combination is the cheap price tag. Hosting providers that use Windows Server and IIS charge more to the customer.

However, these changes may convert some ASP developers to use PHP alongside their applications, and slowly raise more demand for PHP programmers.

See the articles here:

Posted in PHP | No Comments »