---- Also ensure to read up on our site 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 [php] (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.
- Windows: XAMPP (Xplatform-Apache-MySQL-PHP-Perl)
- Linux: XAMPP - Linux distribution and source
- Mac OS X: XAMPP - Mac OSX distribution and source
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.ini2) 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); //< = < 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)


Sign In
Create Account

Back to top











