Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
* * * * * 1 votes

PHP Guide: Frequently Asked Questions

mysqli

  • Please log in to reply
13 replies to this topic

#1 Alexander

Alexander

    YOL9

  • Moderator
  • 3963 posts
  • Location:Vancouver, Eh! Cleverness: 200
  • Programming Language:C, C++, PHP, Assembly

Posted 19 October 2010 - 12:35 AM

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=auto:0] (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?
(Or...Why do I see "" at the beginning of my web page?)

Your text editor may be setting an erroneous UTF byte order mark, or BOM, at the beginning of your code file. These byte sequences were intended to be invisible in Unicode for the purpose of locating the start of the stream, and can only be turned off by the appropriate settings. Try saving your file as UTF without BOM or as plain ASCII, or strip the bytes by opening your document in ASCII mode or with a non-Unicode text editor.


The first error occurs due to the order content must be sent to the browser, which is after any HTTP headers and cookies. This means that will you need to place the code at the top of your script, and clear all bytes before the <?php tag, including whitespace and any HTML before headers can be sent.

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);


These limits are important however and care should be taken in to working within them. Prematurely optimising code can lead to development, but more often than not, you just have a slow, poorly parallelised bit of code that you can probably improve upon.


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/>

$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 where the process continues or you rely on it to let faulty code function.


A general related improvement is to have interpreter bytecode caching so that further loading of the same file are 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 vulnerabilities - and you may be correcting only symptoms of a larger problem.


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 or allowing HTML.

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, 11 October 2014 - 03:59 PM.
Tutorial links, useful additions to 10), BOM/other updates

  • 2

#2 FireGator

FireGator

    CC Regular

  • Just Joined
  • PipPipPip
  • 35 posts

Posted 19 October 2010 - 06:24 PM

This is a great contribution to the forum, Thank you! hopefully people will start reading this before asking some more simpler of questions.
  • 0

#3 Roger

Roger

    Skadoosh!

  • Administrator
  • 1222 posts
  • Programming Language:C, PHP
  • Learning:Others

Posted 21 October 2010 - 06:10 PM

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

  • 0

New around here? Click here to register and start participating in under a minute?

Or do a quick search and you may find the answer you're looking for.


#4 Graphene

Graphene

    CC Regular

  • Member
  • PipPipPip
  • 34 posts
  • Learning:C, C++, Python, JavaScript

Posted 27 December 2010 - 07:06 PM

Thank you, this answered some old questions I always had.
  • 0

#5 An Alien

An Alien

    CC Addict

  • Senior Member
  • PipPipPipPipPip
  • 322 posts
  • Programming Language:Java
  • Learning:C, Java, PHP, Python, JavaScript, Lisp, Transact-SQL, Others

Posted 09 February 2011 - 05:41 AM

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.
  • 0

#6 Alexander

Alexander

    YOL9

  • Moderator
  • 3963 posts
  • Location:Vancouver, Eh! Cleverness: 200
  • Programming Language:C, C++, PHP, Assembly

Posted 09 February 2011 - 02:03 PM

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
  • 1

All new problems require investigation, and so if errors are problems, try to learn as much as you can and report back.


#7 Orjan

Orjan

    CC Mentor

  • Moderator
  • 2918 posts
  • Location:Karlstad, Sweden
  • Programming Language:C, Java, C++, C#, PHP, JavaScript, Pascal
  • Learning:Java, C#

Posted 04 June 2011 - 04:20 PM

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.
  • 0

I'm a System developer at XLENT Consultant Group mainly working with SugarCRM.
Please DO NOT send mail or PM to me with programming questions, post them in the appropriate forum instead, where I and others can answer you.


#8 webcodez

webcodez

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 143 posts

Posted 27 June 2011 - 11:16 AM

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.
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#9 wcypierre

wcypierre

    CC Newcomer

  • Just Joined
  • PipPip
  • 10 posts

Posted 12 November 2011 - 09:42 AM

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.

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.
  • 0

#10 Alexander

Alexander

    YOL9

  • Moderator
  • 3963 posts
  • Location:Vancouver, Eh! Cleverness: 200
  • Programming Language:C, C++, PHP, Assembly

Posted 31 January 2012 - 11:14 PM

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.

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.
  • 1

All new problems require investigation, and so if errors are problems, try to learn as much as you can and report back.


#11 sazal786

sazal786

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts
  • Location:Dhaka, Bangladesh

Posted 01 November 2014 - 10:04 PM

Thank you for this helpful post. This post is really help me.


  • 1

#12 WardBradley

WardBradley

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 25 August 2015 - 03:33 AM

I'm not sure that I write in the correct topic, but there is one important question: I read an interesting article http://webinerds.com...tion-framework/
I analyzed the advantages and disadvantages, and now I can not choose between Laravel and Symphony 2
Can someone share a personal experience?

Edited by WardBradley, 25 August 2015 - 03:34 AM.

  • 0