Jump to content

Php Guide: Fequently Asked Questions

- - - - -

  • Please log in to reply
9 replies to this topic

#1
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,124 posts
  • Location:Vancouver, Eh! Cleverness: 200
This sticky was formed to address common problems users have had in the past with PHP, in hopes so that you may find an answer to your questions before you ask.

---- Also ensure to read up on our sit
e FAQ before posting.

A list of our separate tutorials for PHP can be found here: PHP Tutorials. They span many diverse topics and may contain some information not usually found in other tutorials on-line.

How do I post PHP code in the forum?
You may post PHP code by wrapping your code around [ph
p] (php-highlighting) or [code] (general code) tags, you also can press the code (<>) button on the editor interface and enter code in to the prompt. Please use either one at all times when posting a code, otherwise the formatting may be lost.

Common Questions:

How do I run PHP code at home?
The most general method of running PHP code on your computer would be to install a web server stack on your computer. Free common "Apache MySQL and PHP" bundles can be found here.
Common Issues:

1) My code stopped working, but there are no errors. What's wrong?
Web servers are commonly set up to not display errors, but rather to log them by default. To turn on error reporting you may place these two directives at the top of your script:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
You can as well enable errors to be displayed permanently by setting display_errors = On in php.ini


2) How do I fix the "headers already sent" error when starting a session?
HTTP headers and cookies must be sent before any content to the browser. This means that will you need to place the code at the top of your script, and clear anything before the <?php tag, including whitespace or any HTML.

Your text editor may also be setting an erroneous UTF byte order mark, or BOM, at the beginning of your code file. This is invisible, and can only be turned off by the appropriate settings. Try saving your file as UTF without BOM, or as plain ASCII.

You can view if and where your headers are being sent with the following code:
if(headers_sent($file, $line) == true) {
  print "Headers are already sent by $file on $line\n";
}
The parameters create references to variables for later use.


3) Why has my script reached "Maximum execution time" and stopped?
On a web server where resources are limited, a default maximum execution time is recommended to prevent a faulty script from running forever. You can change the maximum time for a single script, if you were wishing to set it to one hour (3600 seconds) then you would place this at the top of your script: set_time_limit(3600);


4) I cannot see \n newlines, including from an HTML textarea field
Browsers were simply meant to ignore text carriage returns and line feeds when displaying HTML, a line break in HTML is <br/>

To convert newlines to HTML line breaks, you can use the function nl2br()
$notes = nl2br($_POST['notes']); // \r\n, \r, \n = <br/>[/color]
[color=Black]$notes = htmlspecialchars($notes); //< = &lt;
echo $notes;

5) Why are all my HTML form's quotes escaped automatically into \' or \"?
This is a deprecated feature of PHP called magic quotes, which attempts to automatically apply addslashes() to all HTTP variables, such as $_GET/$_POST/$_COOKIE. You may wish to check if it is on with magic_quotes_gpc() and apply stripslashes() to fix this.
if(magic_quotes_gpc() == true) {
	$data = stripslashes($data);
}
Note this should be done to prevent extra escaping before you sanitize the data to be placed into a database.

Note: PHP intends to remove support for magic quotes for further versions.

File Handling:

6) What is the difference between require() and include()?
From the PHP manual: "require() and include() are identical in every way except how they handle failure. include() produces a Warning while require() results in a Fatal Error. In other words, don’t hesitate to use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless. Be sure to have an appropriate include_path setting as well. "

Another note: Try to use require_once() and include_once() functions only when you are sure you really need their functionality, they allow inclusion of a script once per execution of php/php.exe, which may be a problem on some types of installations.


A general related improvement is to have interpreter caching so that further loading of the same file is of little consequence.

A tutorial for eAccelerator: http://forum.codecal...pache-tutorial/



7) I get a "Permission Denied" warning while writing to a file with fopen()
If you are getting permission denied trying to write to a resource, you must first allow the file to be written to. Using your FTP client to set permissions to 644 (owner can read/write, others can read) will be sufficient to allow write access by PHP. If you are using Linux in or with an SSH shell, you can also use the command line option "chmod 644 filename(s)" to do the same. This may be dependant on your setup and you will need to consult your host or web administrator to use the right values, incorrect values can lead to stability issues or worse.


8) Why does fopen() overwrite my file when I write to it?
fopen() has different modes of writing to a file. fopen($file, 'w') will write to the beginning of a file overwriting any contents, and creates the file if it does not exist. If you wish to only append to a file, then you must define the mode as 'a'. This is also true for file_put_contents, the third parameter for this function must be FILE_APPEND of which is a definition, not a string.


file_put_contents($foo, $bar, FILE_APPEND);


Security Practices

9) How do I make my database secure from malicious SQL injection?
This depends on the functions you are using, for the vanilla mysql_connect() related functions you should use mysql_real_escape_string() on all data being sent to the database.

This will escape quotes and nullify incorrect UTF sequences based on the currently selected charset. This is a very common mistake for new programmers not to use this.
$name = mysql_real_escape_string($_POST['name']);
mysql_query("UPDATE table SET name = '$name' WHERE id='42'");
An open database connection is required to use any of the mysql_* functions. A warning will be issued to you if you attempt to perform sanitation before this an open connection is made.


Some further reading on SQL injection: http://forum.codecal...injections.html

Note: MySQLi (intro) and PDO (intro) classes supersede all deprecated mysql_* calls, consider upgrading your code

10) How do I stop people from injecting HTML? Prevent XSS?
If you ask for a name, and they put HTML tags within, those tags will be displayed when you print their name next page. This unwanted result can lead to them placing malicious scripts into the page, or a redirect. Always use htmlspecialchars() when displaying a user's data
echo "Welcome " . htmlspecialchars($_POST['name']) . " to my site!";
You may also alternatively use strip_tags() on the name to strip the HTML tags completely.


Try to avoid using strip_tags's "allowed tags" feature however, as one can simply use <b style=malicious code> or similar. A helpful script to avoid malicious code - yet allow some common formatting or custom tags is HTMLPurifier. Using a markup system such as markdown or bbcode can be an alternative to filtering.

Some further reading on XSS: http://forum.codecal...23-php-xss.html

Update, August 12 2011:
A recommended read to explain the various security layers of which should be applied to production websites, generously contributed by Vaielab:
http://forum.codecal...p-security.html

Edited by Alexander, Today, 02:14 PM.
Tutorial links, useful additions to 10)


#2
FireGator

FireGator

    Learning Programmer

  • Members
  • PipPipPip
  • 37 posts
This is a great contribution to the forum, Thank you! hopefully people will start reading this before asking some more simpler of questions.
>+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.[-]
>++++++++[<++++>-] <.>+++++++++++

#3
Roger

Roger

    If nothing goes right, go left.

  • Administrators
  • 718 posts
  • Programming Language:C, PHP
  • Learning:Python
Great FAQ!

When I setup production PHP, I also like to setup the php.ini file with the following settings:

max_execution_time = 30
memory_limit = 64M
error_reporting = E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR
display_errors = Off 
log_errors = On 
error_log = /var/log/php.log  
register_globals = Off

Check out our update Guidelines/FAQ. When posting code, remember to use code tags - Posted Image.

#4
Fighter

Fighter

    Newbie

  • Members
  • PipPip
  • 28 posts
Thank you, this answered some old questions I always had.

#5
An Alien

An Alien

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 260 posts

Roger said:

Great FAQ!

When I setup production PHP, I also like to setup the php.ini file with the following settings:

max_execution_time = 30

memory_limit = 64M

error_reporting = E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR

display_errors = Off 

log_errors = On 

error_log = /var/log/php.log  

register_globals = Off


could you explain what a php.ini file is? I think it's for configuration for PHP but not sure. Sorry, I'm a noob.

#6
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,124 posts
  • Location:Vancouver, Eh! Cleverness: 200

An Alien said:

could you explain what a php.ini file is? I think it's for configuration for PHP but not sure. Sorry, I'm a noob.
Yes, it is the file that holds a majority of the configuration for PHP, including security, modules, performance and error reporting aspects. PHP: Description of core php.ini directives - Manual
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#7
Orjan

Orjan

    Writes binary right handed and hex left handed

  • Moderators
  • 3,299 posts
  • Location:Karlstad, Sweden
  • Programming Language:C, Java, C++, C#, PHP, JavaScript, Pascal
  • Learning:Java, C#
One thing to think of when installing a web server of your own is that if you can't get your server up and running, maybe some other program is using the port 80. A program that happily uses port 80 as standard settings is Skype, so if you have Skype installed, you might need to deactivate it's usage of port 80 in the settings.
__________________________________________
I study Information Systems at Karlstad University when I'm not on CodeCall

#8
webcodez

webcodez

    Programmer

  • Members
  • PipPipPipPip
  • 149 posts
Very well done. This FAQ has such a lot of questions that I have faced in the last 4 years. Even though I do know about them now, I do think this is very useful for the learning PHP programmer.

Cheers.

#9
wcypierre

wcypierre

    Newbie

  • Members
  • PipPip
  • 10 posts
I would still prefer to add ENT_QUOTES and the charset that you are using because I had read a paper whereby XSS can be performed where ENT_QUOTES parameter is not added and Google was once Xssed due to the fact that they are using the utf-7 charset.


echo "Welcome " . htmlspecialchars($_POST['name'], ENT_QUOTES, "utf-8") . " to my site!";  


or another solution would be to use htmlpurifier.

Quote

You may also alternatively use strip_tags() on the name to strip the HTML tags completely.
XSS is made possible because of Javascript and not HTML. Although HTML does play its role but its not the main boss.

#10
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,124 posts
  • Location:Vancouver, Eh! Cleverness: 200

Quote

I would still prefer to add ENT_QUOTES
If quotation is a concern, you probably are allowing users to define arbitrary content in attributes and that is more of a concern than the encoding.

wcypierre said:

XSS is made possible because of Javascript and not HTML. Although HTML does play its role but its not the main boss.
Javascript is plaintext until otherwise instructed by the browser to be interpreted. If nothing can instruct the browser to run it, it is already clean.

Alexander.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users