This section gathers many common errors that you may face while writing PHP scripts.
<?php |
<pre> |
1. I would like to write a generic PHP script that can handle data coming from any form. How do I know which POST method variables are available?
PHP offers many predefined variables, like the superglobal $_POST. You may loop through $_POST as it's an associate array of all POSTed values. For example, let's simply loop through it with foreach, check for empty() values, and print them out.
<?php |
Суперглобальные переменные: замечание о доступности: Начиная с PHP 4.1.0, стали доступными суперглобальные массивы, такие как $_GET, $_POST, $_SERVER и т.д. Дополнительную информацию смотрите в разделе руководства superglobals
2. I need to convert all single-quotes (') to a backslash followed by a single-quote (\'). How can I do this with a regular expression? I'd also like to convert " to \" and \ to \\.
The function addslashes() will do this. See also mysql_escape_string(). You may also strip backslashes with stripslashes().
Замечание о директиве: magic_quotes_gpc: Директива PHP magic_quotes_gpc имеет значение по умолчанию on (включена). По сути это применяет функцию addslashes() ко всем вашим GET-, POST-, и COOKIE-данным. Чтобы удалить добавленные косые черты, вы можете использовать stripslashes().
3. All my " turn into \" and my ' turn into \', how do I get rid of all these unwanted backslashes? How and why did they get there?
The PHP function stripslashes() will strip those backslashes from your string. Most likely the backslashes magically exist because the PHP directive magic_quotes_gpc is on.
Замечание о директиве: magic_quotes_gpc: Директива PHP magic_quotes_gpc имеет значение по умолчанию on (включена). По сути это применяет функцию addslashes() ко всем вашим GET-, POST-, и COOKIE-данным. Чтобы удалить добавленные косые черты, вы можете использовать stripslashes().
5. Hey, what happened to my newlines?
<pre> |
In PHP, the ending for a block of code is either "?>" or "?>\n" (where \n means a newline). So in the example above, the echoed sentences will be on one line, because PHP omits the newlines after the block ending. This means that you need to insert an extra newline after each block of PHP code to make it print out one newline.
Why does PHP do this? Because when formatting normal HTML, this usually makes your life easier because you don't want that newline, but you'd have to create extremely long lines or otherwise make the raw page source unreadable to achieve that effect.
6. I get the message 'Warning: Cannot send session cookie - headers already sent...' or 'Cannot add header information - headers already sent...'.
The functions header(), setcookie(), and the session functions need to add headers to the output stream but headers can only be sent before all other content. There can be no output before using these functions, output such as HTML. The function headers_sent() will check if your script has already sent headers and see also the Output Control functions.
The getallheaders() function will do this if you are running PHP as an Apache module. So, the following bit of code will show you all the request headers:
<?php |
See also apache_lookup_uri(), apache_response_headers(), and fsockopen()
The security model of IIS is at fault here. This is a problem common to all CGI programs running under IIS. A workaround is to create a plain HTML file (not parsed by PHP) as the entry page into an authenticated directory. Then use a META tag to redirect to the PHP page, or have a link to the PHP page. PHP will then recognize the authentication correctly. With the ISAPI module, this is not a problem. This should not effect other NT web servers. For more information, see: http://support.microsoft.com/support/kb/articles/q160/4/22.asp and the manual section on HTTP Authentication .
9. My PHP script works on IE and Lynx, but on Netscape some of my output is missing. When I do a "View Source" I see the content in IE but not in Netscape.
Netscape is more strict regarding HTML tags (such as tables) then IE. Running your HTML output through a HTML validator, such as validator.w3.org, might be helpful. For example, a missing </table> might cause this.
Also, both IE and Lynx ignore any NULs (\0) in the HTML stream, Netscape does not. The best way to check for this is to compile the command line version of PHP (also known as the CGI version) and run your script from the command line. In *nix, pipe it through od -c and look for any \0 characters. If you are on Windows you need to find an editor or some other program that lets you look at binary files. When Netscape sees a NUL in a file it will typically not output anything else on that line whereas both IE and Lynx will.
In order to embed <?xml straight into your PHP code, you'll have to turn off short tags by having the PHP directive short_open_tags set to 0. You cannot set this directive with ini_set(). Regardless of short_open_tags being on or off, you can do something like: <?php echo '<?xml'; ?>. The default for this directive is on.
11. How can I use PHP with FrontPage or some other HTML editor that insists on moving my code around?
One of the easiest things to do is to enable using ASP tags in your PHP code. This allows you to use the ASP-style <% and %> code delimiters. Some of the popular HTML editors handle those more intelligently (for now). To enable the ASP-style tags, you need to set the asp_tags php.ini variable, or use the appropriate Apache directive.
Read the manual page on predefined variables as it includes a partial list of predefined variables available to your script. A complete list of available variables (and much more information) can be seen by calling the phpinfo() function. Be sure to read the manual section on variables from outside of PHP as it describes common scenarios for external variables, like from a HTML form, a Cookie, and the URL.
register_globals: важное замечание: Начиная с PHP 4.2.0, значением директивы PHP register_globals по умолчанию является off (выключено). Сообщество PHP рекомендует всем не полагаться на эту директиву, а использовать вместо этого иные средства, такие как superglobals.
13. How can I generate PDF files without using the non-free and commercial libraries ClibPDF and PDFLib? I'd like something that's free and doesn't require external PDF libraries.
There are a few alternatives written in PHP such as http://www.ros.co.nz/pdf/, http://www.fpdf.org/, http://www.gnuvox.com/pdf4php/, and http://www.potentialtech.com/ppl.php. There is also the Panda module.
14. I'm trying to access one of the standard CGI variables (such as $DOCUMENT_ROOT or $HTTP_REFERER) in a user-defined function, and it can't seem to find it. What's wrong?
It's important to realize that the PHP directive register_globals also affects server and environment variables. When register_globals = off (the default is off since PHP 4.2.0), $DOCUMENT_ROOT will not exist. Instead, use $_SERVER['DOCUMENT_ROOT'] . If register_globals = on then the variables $DOCUMENT_ROOT and $GLOBALS['DOCUMENT_ROOT'] will also exist.
If you're sure register_globals = on and wonder why $DOCUMENT_ROOT isn't available inside functions, it's because these are like any other variables and would require global $DOCUMENT_ROOT inside the function. See also the manual page on variable scope. It's preferred to code with register_globals = off.
Суперглобальные переменные: замечание о доступности: Начиная с PHP 4.1.0, стали доступными суперглобальные массивы, такие как $_GET, $_POST, $_SERVER и т.д. Дополнительную информацию смотрите в разделе руководства superglobals
Пред. | Начало | След. |
Build Problems | Уровень выше | PHP and HTML |
HIVE: All information for read only. Please respect copyright! |