Archive

Posts Tagged ‘write’

Write To The Output Buffer In PHP

February 10th, 2009 1 comment

The first thing you learn about in PHP is probably how to print something. This is usually done with a call to the echo or print, but there is another way to print things by writing content directly to the output buffer. The following code looks like you are writing to a file, but the text will appear in the browser window because we are writing to the php://output output stream.

$fp = fopen("php://output", 'r+');
fputs($fp, "Hello World");

Or another way…

file_put_contents("php://output", "Hello World");

The php://output stream is an encapsulation between PHP and the browser. The stream doesn’t really exist, but PHP knows what to do with it.

Why would you ever need to know this? Well lets say that you had an application that produced some logs when users performed certain actions. You might want to print those to screen in your development environment rather than save them. So rather than altering the code to see what environment you are in you can just set a configuration option so that you write to php://output instead of the log file. This means that your logs will appear with your output.

Categories: PHP Tags: , , , , , ,

The PHP User On Linux

January 5th, 2008 No comments

Reading or writing a file using PHP is quite a common practice, but it can often fall cause programs to fall flat on their face if the proper user privileges are not in place. Although this is not a problem on Windows machines due to the lack of a proper security model, but on Linux machines you need to make sure your scripts can run with the correct permissions.

First you must determine what the name of the user and group is. On OS X the default is "www" for both user and group. If you are using Apache then the user and group information is kept in the http.conf file. Look for a couple of lines that look like this, this is the default settings for Apache 2.2.

User daemon
Group daemon

On this server my PHP scripts will run with the user and group of "daemon". You must use chmod to change the owner of the directories that scripts are to run in. For example, if your server runs from /user/local/apache2/htdocs/ then you should use the following code. You might have to be logged in as root in order to run this.

chown daemon:daemon /usr/local/apache2/htdocs/
chmod 770 /usr/local/apache2/htdocs/

You can use the -R flag on both chomod and chown to make all sub directories have the same permissions.

chown -R daemon:daemon /usr/local/apache2/htdocs/
chmod -R 770 /usr/local/apache2/htdocs/

Setting the security to 770 will be very secure as it will only allow the user daemon to have read/write access to these directories. Setting the chmod code to 775 will allow you to read the files. If you use the same username for Apache as you use to log into the server then you won’t have this trouble.

Categories: PHP Tags: , , , , , , , , ,