PHP - Frequently Asked Questions
Ok, Im starting this FAQ thread for the PHP forum. This will work pretty much the same as all the other FAQ threads.
We seriously need some new tutorials added, if you have the time, please go here: <http://www.codingforums.com/showthread.php?t=36142> and consider submitting a tutorial!
Please do not reply to this thread asking for help, if you are still having problems, start a new topic in the relevant forum describing your problem
For further information on how to add a reply, or if you would rather have your answer proof-read before you post it here (reccomended), then please visit <http://www.codingforums.com/showthread.php?t=36142>
As FAQ entries get added I will add them to the index here.
php.net - The official PHP site, where you can download the latest versions of PHP or lookup functions and syntax.
mysql.com - MySQL is the database technology that is most often used with PHP, to make dynamic data driven websites and scripts
Q. How do I write to a file using PHP?
A. This question is often asked in many ways, it could be how to add something to the end of a file, empty a file, or create a file. All of these operations come under writing to a file.
Firstly, there is a basic pattern to writing to a file, it goes something like this:
This is the order that the operations (usually) need to be carried out in. The following example shows you how to create a file, then write a string to the file.
Handle - The name often given to the variable defined when using the fopen function.
Mode - A letter that represents how the file should be opened when using fopen.
On the next line, we just simply set the variable $string to the value 'Test String'. This is the data that will get written into the file later on.
2. Next we lock the file using flock. Using an exclusive lock, which is set by putting LOCK_EX, the file is locked from other scripts writing to the file or reading from it while we put the new information into the file. If the file isn't locked and two scripts try to write to it at the same time, it can get corrupted.
3. The next part is the part that actually writes the information to the file. Using the fputs function it use the file path and data supplied ($fp and $string in this case), and writes $string to $fp.
4. From here, the file needs to be unlocked using flock again, otherwise no other scripts would be able to write or read it. To unlock the file, we use LOCK_UN.
5. Finally, we have finished with the file so we can close it. Using the fclose function we pass it the file handle ($fp) and it closes it. You should always do this as this is another thing that can lead to files getting corrupted.
If you try this and are still having problems, there are some possible reasons that it is failing, the most likley is that the file or directory you are trying to write to doesn't have the right permissions set. If you are on Linix machines (mosts PHP hosts will be running Linux), then you can CHMOD the file or directory to a value that will allow the scripts to be executed. For testing, I usually set it to 777. You can CHMOD from some FTP programs and online control panels. If you are not sure how to CHMOD on your hosting acount, you should contact your webspace provider.
This is the basics of writing to a file. Often, however, when you write to a file, you want to be able to add something on to the end of the file, and not delete everything that is in there first. This is very easy to alter, simply change the code:
Finally, to bring this to a close, just a couple more points...
How to write to the beginning of a file?
A common question is ,'how do you write to the beginning of a file' , the answer is not a new magic mode but a different approach , it should be noted that you can write to the beginning of a file by opening 'r+' and using fseek() to rewind to the start of a file then fputs() etc , however this will overwrite byte for byte the files existing contents.
To add a line to the beginning of a text file the most straightforward method is to read the file into memory , manipulate and then rewrite the file.
Newer PHP versions have handy functions such as file_get_contents() to get the files data into a variable , you can also use the above noted functions to read a file into memory or the old sausage <?$str = implode( '', file( $filename ) ) ;?>
e.g. (no filelocking for clarity)
permission denied ... why ? file permissions
<help>I would really appreciate those of you who understand all of this to please check the below is in order since it is a sticky , I am not a unix user , not a trained administrator so any pointers errata are welcomed !!!</help>
OK so many questions regarding this subject so...here we go.
Files on any *NIX system have a, at first glance ,complex ownership/permission system , its actually not that complex but can be intimidating at first.
Now you may think you don't need to understand them (and for most web-related work you probably don't ), however knowledge is power & once you do understand them , you will never again worry about the dreaded `permission denied` , dont skip though , read from the beginning , it makes more sense if you do.
The 3 common (there are more) *NIX permissions 'r' , 'w' , 'x' ( often 'e' or 'o' ) are applicable to 3 entities , the files 'owner' the files 'group' and 'others' (AKA 'everyone else' 'the world' )
All files have an owner , who that owner is depends on who created them , when you upload a file via FTP the file is owned by the user that you logged in as.
So if your FTP login is 'joe' then the file is most likely owned by user 'joe'.
When however you create a file via script (fopen() etc) the file is still owned by whoever created it , however that user is no longer 'joe' , its the user that your webserver runs as , which is normally NOT your *UNIX username (except in chrooted or suexec environments) , it is normally 'apache' or 'nobody' .
Groups are a bit of a sticky subject because how groups are assigned varies from system to system , often at the whim of the server administrator or hosting control panel interface , plesk for example assigns all file uploaded via FTP to the 'psacln' group , redhat however by default creates a new group for each user and assigns group ownership to that group (e.g. user 'joe' gets his own group 'joe').
Others AKA everyone else , the world
As far as *NIX is concerned , if someone is not the owner of the file or does not belong to the same group as a file , then you are classed as 'others' , contrary to popular belief external applications can not modify files which allow write access to 'others' , only other users of the same system or local network can actually do that (on shared hosting this is a real issue)
All *NIX files have permissions assigned , there are 3 permissions a file can be given , 'r' for read , 'w' for write & 'x' for executable , a file can have 0 or more permissions . e.g. a file can have both 'r' and 'w' permissions , so they are both readable and writable , 'rwx' means you can do pretty much anything with the file.
Now the permissions above r,w & x are applied individually to the files owner , the files group and others ! so
owner group others user group
myfile rwx r r joe joe
With the above, the owner of the file (joe) can read write & execute (if applicable , e.g. the file is a script) the file , any members of the 'joe' group (usually just the user joe) can read and write to the file , 'others' can only read the file. when your webserver requests myfile , it does so as 'apache' or nobody' and as such is given read access.
However , when your script which is probably running as 'apache' comes along and tries to write to the file , it finds it can not .. why? , well 'apache' is not the owner of the file , nor does it belong to the group 'joe' , therefore as far as this file is concerned it belongs to the 'world' group which is only allowed to read, not write to the file.
to allow apache to write to the file you would need to change the file permissions to ...
owner group others user group
myfile rwx rw rw joe joe
e.g. give 'others' write 'w' access , so an outsider , such as apache , could write to the file.
Now lets say you created a file via a PHP script , the file created by PHP (actually by apache with mod_php) will be owned by 'apache' , if you then chmod the file (again via script) to say 0700 (rwx------) then you would not have permission to delete that file via FTP , since you would then be considered as 'others' !
Luckily if you created a file by script you can chmod it to something more accessible via script <?php chmod( 'myfile' , 0766 );?> , this will then allow you to read and write to the file via FTP.
so with the following
owner group others user group
myfile rwx r r joe joe
You can not chmod the script via PHP/apache since it only has read access , however if via FTP you (as 'joe') chmod to 0766 or 0777 , then your PHP script can read and write to the file.
Its often assumed that if a directory is not writable then nor are is contents , that however is <B>not</B> the case , a writable file in a read-only directory can still be altered by anyone with the right credentials , however you will not be able to write to that directory unless the directory is writable to the user or application that attempts the write.
Also to be able to list the directories contents , the directory must be executable to the application attempting to do so , 'read' is not enough (in fact you don't even need the directory to be readable , 'x' is enough.
Need to be executable , HTML & text files etc can simply be read-only , but if a file is a script , then make it executable !
file permissions can be represented as octal modes , but that's easier than it sounds , if ...
r (read) = 4
w (write) = 2
x (execute) = 1
if the owner of a file has read & write permissions that's 4+2 = 6
if the group just has read permission that's 4
if others also only have read permissions , again that's 4
so myfile below has the mode 0644
owner group others user group
myfile rw r r joe joe
As noted above chmod() can change the permissions of a given file , for a user or an application to change these permissions however the user or application needs to have write access to the file in the first place !!
for PHP its important when chmod()'ding to use octal values
chmod( 'myfile' , '0644' ) ; will cause issues , since we are passing the mode as a string
chmod( 'myfile' , 644 ) ; here 644 , is , as far as PHP is concerned, decimal ! again be prepared for problems
chmod( 'myfile' , 0644 ) ; is correct !
chown & ghgrp
PHP has the chown & chgrp commands, however only a superuser can use them , so unless your webserver runs as 'root' or similar , you can't use them.
If your server runs PHP as a CGI then much of the above may change , its is not common for CGI scripts to be run as a different user than the webserver via Apaches mod_suexec or phpsuexec etc
If you webserver runs in a chrooted environment then its possible (probable) that the webserver (above stated as 'apache' or 'nobody') may well run as another user , often as the user account e.g the same as your FTP login , if this is the case then you will have less issues with file ownership & generally be in a much safer playground.
Not really important here , but you may wonder why when you create a file via FTP or script that it is given e.g. 0755 for FTP or 0644 for scripts , this is decided by the umask , the responsibility of the server administrator
So , if you read the above , and if it made any sense at all :D , you will understand why you can't ,immediately alter your files uploaded by FTP via a PHP script, if you don't then read again , if I am making no sense then please post and say so & I will try and clarify , if anyone wants to add to this document , post & I will add/amend
How can i do a random password function ?
Q: How can i do a random password function ?
There it is,
First of all, you need a character bank as well abcdefghijklm...etc..,
It looks that you want a password generated by the server, so you need to specify all your chars and yes, Upper cases too..
Functions used in this scripts are:
substr Return parts of a $string
$i++ Increment / Decrement variables
srand Seed the random number generator < PHP 4.2
microtime Return current Unix timestamp with microseconds
rand Generate a random integer
strlen Return lenght of a string
Very begginner question:
Q: How to resolve the 'headers already sent' error?
A: This is one of the most common errors. You often get it when your using session_start() or header().
Headers are sent automatically when any output is sent to the user. You send output with print/echo (and some other functions) as well as having anything outside php tags. This includes blank lines spaces, tabs and all other characters. You must send the header BEFORE the output. You must watch out not to have any blank lines before the <?php tag and after the ?> tag
-mentioned but not OB functions
Good to read:
If you spot an error (or have a suggestion) PM me. I'll fix it as fast as I can.
Just because JS and PHP are client-side and server-side respectively does not mean they cannot be used together. JS makes pages dynamic (on the client side) while PHP makes pages dynamic (on the server side, when the page actually loads (the user does not see how the php affects the page)).
Q: What is the difference between addslashes() and mysql_real_escape_string() when running MySQL queries?
A: The difference between addslashes() and mysql_real_escape_string() is that mysql_real_escape_string() escapes all characters harmful to a mysql query (such as line feeds, carriage returns, quotes, and a number of other assorted special characters), while addslashes() only escapes quotes (both single and double), backslashes, and the NULL byte.
Related to this topic is magic quotes. If magic_quotes_gpc is enabled in the PHP config, it automatically runs the equivalent of addslashes() on $_POST, $_GET, and $_COOKIE data (and by proxy, $_REQUEST data). If magic_quotes_runtime is enabled, it runs it on almost all external data (file reads, database results, and so on). Thus, we would want to remove this from our data before entering, as when used with mysql_real_escape_string() it would double-escape values, and would cause errors.
Q: What is the difference between using $HTTP_POST_VARS and $_POST for accessing POST variables?
A: The difference between $HTTP_POST_VARS and $_POST is that one is depricated, and one is not. $HTTP_POST_VARS (and others such as GET, SERVER, ENV, COOKIE, etc.) were all renamed in PHP 4.1.0 to variables such as $_POST, $_GET, $_SERVER, $_ENV, $_COOKIE, and so on. In later versions of PHP (possibly PHP6) they will be eventually removed.
It is noteworthy to say that the $HTTP_POST_VARS array and the $_POST superglobal array are not references...that is to say, they are separate variables. Changing the value of $_POST['foo'] will not modify the value of $HTTP_POST_VARS['foo'].
How do I read a file using PHP?
How do I read a file using PHP?
The following are basic steps followed in reading a file using PHP
Open a file using fopen
lock the file using flock
read the contents of the file using fread
unlock the file using flock
close the file using fclose
2. Then open the file using fopen in "r" read mode. If the file doesn't exists, it will show you an error.
3.Lock the file using flock.using an shared lock,which is set by putting LOCK_SH.When a statement reads data without making any modifications, its transaction obtains a shared lock on the data.
4.Read the data from the file using fread. Read the file until end of the file will be reached.
5.unlock the file using flockby putting LOCK_UN
6.close the file using fclose
Sending HTML email with PHP
I read a really good article about the PHP emailing program PHPmailer and decided to check it out.
Heres how I use it to send HTML emails on my sites:
functions used with single quotes is used as direct/literal input, and text within single quotes does not get parsed.
There's also the alternative syntax for control structures available to you.
My code isn't working, and I get no errors!
First and foremost: Turn on error reporting at the very beginning of your script.
Also, be sure output buffering is off: ob_end_flush()
And if you can't figure it out after that, post a new thread in this forum with as much relevant information as possible, and any code that we might need so we can help you as quickly as possible.
How do I determine alternating rows?
Common question when using loops and css divs or tables. There are two ways to determine whether you're current iteration is odd or even. One way is through modulus (remainder) division, and the other way is through bitwise comparison. Bitwise comparison is faster than modulus since only the least significant bit needs to be checked. This equates to approximately 2 - 3 times faster than modulus division.
http://www.phpvideotutorials.com/free and check out the free lessons (the first teaches you how to install WAMP)
|All times are GMT +1. The time now is 12:48 PM.|
Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.