#1
  1. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,908
    Rep Power
    6351

    New User Guide & Frequently Asked Questions


    Hello, and welcome to Dev Shed! There are some forum rules you should probably check out in the lounge. This document is designed to replace the old How to Post a Question page and the now-extensive and out of date old FAQ.

    Before you even start, there are five things you need to do.

    #0 Google for it

    Seriously, google it. I guarantee your error-message related questions have been answered. Find the answer. Don't make us type it again.

    #1 Read the manual first!

    The PHP manual and the MySQL Manual are both very well written. If you want to know how to properly use the PHP function date, don't ask us, read the manual page for date, including the comments on the manual page, which usually include bugs, "gotchas," and usage examples.

    How to read the manual:

    Let's use the date function as an example.

    If we look at manual page (http://www.php.net/manual/en/function.date.php) we see this:

    Code:
    string date ( string $format [, int $timestamp ] )

    The first item is "string." This is the type of variable that is returned by the function. Date() returns a string.

    Next is "date": the function name

    between ( and ) is a comma-separated list of the arguments the function takes, in the format "type $variable_name"

    Any arguments in square brackets are optional.

    After the description we then have a parameters section, so for each argument there is a description. On the date page we see "format" with it's description and a very useful reference

    Then we see "timestamp" and a description for that - it explicitly tells us that it is optional and what it defaults to

    From this information one can start using the function. If you're unfamiliar with it then you should be testing on a test server, reading the error messages, printing debug messages and tweaking your code until it is error free and behaves as intended.

    If you have absolutely no knowledge of PHP and MySQL, we'll probably only help you for 5-6 posts before getting frustrated and moving on. Make an effort to learn the languages you're trying to utilize. If it's clear you haven't made an effort to help yourself, we're not going to make any effort to help you.

    #2 Understand the situation

    The follow items are separate languages and technologies that have nothing to do with each other at the fundamental level:
    PHP
    MySQL
    Regular Expressions
    HTML/CSS
    JavaScript/AJAX/Jquery

    Those items above, when combined properly by a person skilled in all 5 of them, create a fully functioning website. They are NOT the same language, and an expert in one of them is not necessarily an expert in another. Most of the moderators of the PHP boards are experts in all 5 simply through virtue of experience (and being awesome). What most new developers fail to understand is that PHP doesn't "know" anything about your HTML form or your MySQL database. PHP "knows" only PHP things. You must tell it, specifically and explicitly, if you want it to fetch information from a database, or receive information from an HTML form.

    Speaking of which, PHP scripts ONLY execute from the moment you click a link until the moment the page is done being displayed. That's all. Scripts can't "wait" for user input, they don't "remember" anything that happened before. Each PHP document is an entirely separate program that has no relation to the OTHER PHP documents on your system. In order to give the impression that your various PHP pages are a cohesive system, you need to make use of cache (APC cache or memcache), databaes, the session, and various other techniques to maintain user flow. You will also have to make sure your HTML output reflects the same styles so the look and feel is maintained. You can do this LATER. Get the PHP working first.

    Because PHP and JavaScript are separate languages and because client-server programming requires the PHP script to die before the JavaScript even begins execution, there is no way to "get a javscript variable from PHP." You have to make your javascript call entirely NEW PHP scripts every time you want to push data from the browser back to the server.

    #3 Debug on your own

    Debugging a PHP script is easy. If you come to us and say "why won't this script work?" and paste 500 lines of code, we will ignore you. Some of us might even "disagree" with you and remove some reputation from your profile. This is how you debug a PHP script in a very general sense:

    0) Know your error types. PARSE errors or SYNTAX mean your PHP isn't valid and has not yet run. Parse errors have nothing to do with your input, database, network, etc. Parse errors will almost always be missing special characters in your code, be they brackets, parens, dollar signs, etc. You will often see parse errors in the format of "UNEXPECTED T_SOMETHING." The tokens (that's why they begin with T) can be found in the manual, but they're normally easy to understand. If you have an unexpected T_STRING, that's a bare string where PHP didn't want one, usually because you've forgotten a semicolon.

    FATAL errors mean that your code is broken in such a way that PHP cannot hope to continue. Fatal error messages are even more explanatory than the parse errors, they will normally contain messages like "using a non-object in object context." This means that something you're using as if it was an object is NOT an object. The line number will tell you exactly where you've messed up.

    1) By default PHP hides error messages from you (for security reasons). See "FAQ #30: Why do I see a blank screen/page when I visit my PHP script?" (later in this guide) to learn how to enable the display of error messages.

    Before asking for help, enable error messages so that you know what is going wrong with your script. PHP will give you a line number and hint as to what's wrong. Fix ALL errors and warnings before you ask a question (unless your question is "what does this warning even mean?"; If that's your question, google it first and read when the last guy asked).

    2) Scatter echo statements throughout your code so that you know what's going on. Believe it or not, professional developers making upwards of six figures do this every day. My debugging consists of statements like:
    echo __FILE__ . '::' . __LINE__ . ' userId is ' . $userId . "<br />\n";

    Do that as often as you need to until you figure out which portion of your script is causing the issue. Use the var_dump function to dump a variable's contents and datatype, which is handy for boolean values.

    3) Check your database connection. If you believe your script is malfunctioning or the database is incorrect, make sure you're doing it right at all. Check the connection information, the username, the password, and the argument(s) to mysql_select_db/mysqli_select_db. When working with MySQLi, you can find further information in the MySQLi-link object's connect_error and error properties. If you've created a "test" database and your script is using THAT while you've connected your PHPMyAdmin to the "real" database, of course it's not working.

    4) Ensure you're not using deprecated functionality and that you've fully updated everything. If you're running PHP4, stop reading right now and go fix that. Same with MySQL4 and Apache1. Check the manual page for everything you're using to make sure it's still ok. session_is_registered should not be used. ereg_match should not be used. $HTTP_POST_VARS should not be used. The list goes on and on.

    5) See if there's a built-in function to do what you're trying to do. Never write your own implementation of search, sort, reverse, chunk, push, pop, or anything relating to arrays. It's been done. Find it.

    6) Have someone look over the code with you. Explain to them how it's supposed to work every step of the way, describe what each line and block are doing. Heck, tell an action figure. I have a Chewbacca bobble head on my desk that I explain bugs to. Simply saying it out loud fixes it half the time.

    7) Try your code with other "interferences" removed. If it's a web page, try the code through the command line. If it's a soap service, try it right on the server. If you've written a web/database app that interfaces with a cell phone through ajax and something is broken, you're way too vaue. Build it in pieces, test it in pieces. Nobody puts an entire car together before finding out nothing happens when you turn the key.

    8) Use the error reporting built in to your database software. Echoing the mysql_error() return value, the connect_error and error properties of the mysqli link object and the mssql_error() function results will at least tell you what to look for. Note that SQL is a different language than PHP, "Error on Line 1" SQL error messages mean line 1 of your SQL, not line 1 of your PHP script.

    #4 Your Question is NOT Urgent

    If you believe your question is urgent, if you will fail your class or lose your job if you don't get the proper answer within a specific amount of time, break out your wallet and hire someone. This is a volunteer community that does not respond well to being rushed or scolded.



    Bad Questions


    Once you've done everything above, it's time to come to the forums and ask for help. The following are the questions that are asked so frequently that we already have answers prepared for you. But first, some BAD questions:

    "PHP isn't executing my script properly." -or- "My script is broken." Nonsense, it works just the way you wrote it. You wrote it wrong.

    "I've found a bug in PHP." Unless your name is in the list of moderators at the bottom of the forum list, no you have not. In fact, last time I claimed to have found a bug in PHP, I discovered upon further research that it was a very clever feature I hadn't thought about hard enough yet.

    "Newbie!!! PLZ HEEEEEELLLPPPPPPP :-( :-(" I wanted to hit myself just for writing that. Use descriptive subject names so we know if we should bother to click or not. A descriptive subject name also helps YOU identify the problem better. "My site don't work" doesn't tell us anything. "cURL failing on HTTPS requests" gives us enough data to click the link, and gives YOU enough thought to maybe google for a solution.

    "I tried this code I found and it doesn't work!" That's because the code you found was written for a specific purpose, or may have even been example code that was never intended to work. You can debug it on your own, read it to try to understand it, or use it as a pseudocode study guide for writing your own code fresh. Copy/pasted code will probably never work. Even code you receive in your own threads isn't guaranteed to work. You're not paying anyone for it.

    "Please someone write this for me!" No. Go hire someone, we have a whole sub forum for that.


    How to Post

    #1 Ask how to solve your problem. Do not ask how to implement what you've decided is the solution.

    "Help retrieving data from an HTML table on a remote website" is a good thread. "preg_match help" is not. There are 15 other ways to fetch HTML, maybe your way is the wrong one.

    #2 Your post title should summarize the problem.

    Do not post "Please someone HELP!@!!!!!@#!!!!" Nobody will help you, you'll get a warning, and your thread will be deleted or moved. Make the thread title informative and narrow so that people know exactly what they're getting into.

    #3 Use [ CODE ] and [ PHP ] tags where appropriate.

    When posting code or plaintext output, wrap the code in [ CODE ] and [ /CODE ] tags (no spaces). Similarly, PHP code should always be wrapped in [ PHP ] and [ /PHP ] tags, that's what keeps the formatting correct and adds automatic coloring. If your code is not indented properly or it's all on one line, you will not receive decent help. See the How to use BBCode tags reference page for more.

    #4 Don't ask for a handout

    We're not your employees, your mother, or your teacher. We don't care if you fail your class or lose your job. We're here because we enjoy solving problems and answering questions, not because we're just dying to write a crappy login form for someone. If it's clear you're only asking for us to do your work for you, you'll be ignored. This is a help forum for enthusiasts and professionals who are trying to increase their knowledge of PHP.




    Now, on to the real FAQ.

    In the interest of keeping this short and unconfusing, any code samples more than 10 lines long will just be called "google for this." In general, for something as easy as these FAQ entries, the google results are good enough.

    #1 Why isnít my form data showing up?
    If you have an input called "name" you will need to use $_POST['name'] to access it. Use var_dump($_POST) to examine the contents of the post array if you aren't seeing the proper data. Note that if your form is malformed (ha!) you might not see any data. Inputs must be inside <form> tags, and the <form> tag must have a proper action and method.

    #2 How do I use sessions?
    The sessions section of the PHP manual is magnificent. Remember to call session_start() at the top of every page!

    #3 Only the first word of my variable is showing up!

    For URLs, you need to pass your string through [phpnet=urlencode]urlencode[/phpnet] before you put them into links.

    For form fields, remember that HTML tag attributes need to be quoted. WRONG: <input type=text name=data value=Hello World! /> RIGHT: <input type="text" name="data" value="Hello World!" />

    #4 I'm using time() in my query, but it's not getting into the table.

    PHP's time function is called time(). MySQL's time function is called now(). Remember, PHP and MySQL are different languages.

    #5 Why can't I get my variable inside my function?

    This is a job for variable scope. Functions don't have access to ANYTHING other than what you pass in (with the exception of super-globals like $_SESSION and $_POST). If you need something inside a function, pass it into the function.

    #6 What is "Invalid Result Resource"?
    #7 How do I fetch the results from my database query?
    #8 When I print the results of my query, all I get is "Resource ID #1"


    All of these are related. Recalling that MySQL and PHP are separate languages, what you're actually doing when you query a database is sending a request to a completely different program, which hopefully returns a result, but may return an error, or even die entirely.

    There are currently four ways available to access MySQL databases:


    The old mysql extension is still heavily in use in a lot of common scripts. Still, its not recommended for use any longer and when creating new script, you should rather chose either MySQLi or PDO. ODBC and the old MySQL extension are just the last alternatives.

    When you perform a MySQL query using the old MySQL extension, the result can EITHER be a MySQL result resource, or FALSE. You must check to see if it's false before you attempt to use it. If it's false, the function mysql_error() will return the last error that MySQL gave. The errors returned by this function are identical to the errors you'd get from running that same query on the command line of MySQL directly.

    When you echo a MySQL result resource, you simply get the resource's ID. You must use the resource properly with the built-in MySQL functions like mysql_fetch_array.

    This is the proper way to handle a MySQL query with the old extension:

    php Code:
    $sql = "SELECT name, address, phone FROM people WHERE age > 20";
    $result = mysql_query( $sql );
    if ( $result === false )
    {
      echo "ERROR: " . mysql_error();
    }
    else
    {
      while ( $row = mysql_fetch_assoc( $result ) ) 
      {
        echo "Name: {$row['name']}<br />\n";
        echo "Address: {$row['address']}<br />\n";
        echo "Phone: {$row['phone']}<br />\n";
      }
    }


    Using the new MySQLi extension, the same can be done either this way:

    php Code:
    $sql = "SELECT name, address, phone FROM people WHERE age > 20";
    $result = mysqli_query( $returnValueFromConnect , $sql );
    if ( ! $result instanceOf mysqli_result  )
    {
      echo "ERROR: " . $returnValueFromConnect->error;
    }
    else
    {
      while ( $row = $result->fetch_assoc() ) 
      {
        echo "Name: {$row['name']}<br />\n";
        echo "Address: {$row['address']}<br />\n";
        echo "Phone: {$row['phone']}<br />\n";
      }
    }


    or this way:

    php Code:
    $sql = "SELECT name, address, phone FROM people WHERE age > 20";
    $result = mysqli_query( $returnValueFromConnect , $sql );
    if ( ! $result instanceOf mysqli_result  )
    {
      echo "ERROR: " . mysqli_error( $returnValueFromConnect );
    }
    else
    {
      while ( $row = mysqli_fetch_assoc( $result ) ) 
      {
        echo "Name: {$row['name']}<br />\n";
        echo "Address: {$row['address']}<br />\n";
        echo "Phone: {$row['phone']}<br />\n";
      }
    }


    And lastly, this would be one way for doing things using PDO:

    php Code:
    $sql = "SELECT name, address, phone FROM people WHERE age > 20";
    $result = $pdo->query( $sql );
    if ( ! $result instanceOf PDOStatement  )
    {
      echo "ERROR: " .  $pdo->errorInfo[2];
    }
    else
    {
      foreach( $result as $row ) 
      {
        echo "Name: {$row['name']}<br />\n";
        echo "Address: {$row['address']}<br />\n";
        echo "Phone: {$row['phone']}<br />\n";
      }
    }


    #9 How do I get the auto_increment value of the row I just created?

    mysql_insert_id()
    mysqli_insert_id()
    PDO::lastInsertId()

    #10 My data isn't sorting correctly! 10 shouldn't come before 2!

    Your data is being stored (and therefore sorted) as TEXT instead of numbers. When you sort strings, they're sorted alphabetically, rather than numerically. 10 comes before 2 just like ba comes before c.

    #11 What is the best editor to use for PHP?

    Whatever you're comfortable with. PHP can be written enitrely in a plaintext editor like Notepad (though it's not recommended). GEdit, VI, Emacs, Crimson, Eclipse, Notepad++, and many other programs offer syntax highlighting and line numbering. That's really all you need.

    #12 Should I use echo or print?

    It doesn't matter. Echo is a language construct (so it doesn't get parentheses) while print is a function (so it gets them, and it can return a value). There are many other ways to output text however, including closing your PHP tags and allowing the web server to simply output your raw strings.

    #13 I get a parse error on this line, but there's nothing wrong there!

    The parse errors given by PHP are given on the line where PHP finally realized there was a problem. Since PHP is a semicolon-delimited language, commands can spread over more than one line. PHP stops when a command stops making sense, which is usually a line or two AFTER the bug. If you forget a semicolon, PHP will complain about the NEXT line.

    #14 I need help with this regular expression!

    Lucky day for you my friend, we have a whole forum for that.

    #15 How do I make my results have pages?

    That's called "pagination" and there are so many tutorials out there just begging to be read.

    #16 Why am I getting the error "Headers already sent"?

    If you try to send a header using the header() function (like for a redirect) and headers have already been sent previously, the call will fail. ANY kind of output will send the plaintext headers, preventing a Location header from being sent. The error message contains the file and line that sent the output. Go there, find the problem, and remove it. Whitespace and Byte Order Markers (BOM) outside of the PHP tags count as output. It's best to remove the closing PHP tag from all your files anyway.

    #17 Why doesn't my code work in a specific browser?

    We don't know, but it has NOTHING to do with PHP (99% of the time). If you're having problems with forms, var_dump($_POST). If you're having problems with rendering, use firebug, IE developer tools, or chrome inspector to inspect the CSS of the elements that look wrong. If you're having javascript problems, use those tools' javascript consoles to debug your javascript. Post the relevant questions in the appropriate forum, they are not PHP questions.

    #18 How do I do this and ignore case?

    There's a case-insensitive version of every function. str_replace? str_ireplace. strpos? stripos. strcmp? strncasecmp. etc. View the "see also" section of the function's manual page to find its related functions.

    Regular expressions become case-sensitive when you add an "i" at the very end of the string, after the closing delimiter.

    #19 I upgraded PHP and now I'm getting all kinds of errors!

    Major changes happen with PHP upgrades. Specifically, deprecated features are removed. You may experience problems with register_globals being turned off (meaning any form field names are no longer automatically PHP variables) or existing super-globals (like $HTTP_POST_VARS) disappearing. Turn error reporting all the way up, and walk through your code fixing all the problems. Read the upgrade log next time, too.

    #20 How can I have my form fields "remember" on subsequent submit?

    Easily! Simply make use of isset() and the PHP ternary operator to give your form field a value only if a specific variable is set:
    PHP Code:
    echo '<input type="text" name="demo" value="' . ( isset( $_POST['demo'] ) ? favorite_escaping_function($_POST['demo']) : '' ) . '" />'
    (Substitute the "favorite_escaping_function" with whatever you use to escape user input: htmlspecialchars(), htmlentities(), filter_var(), etc.)

    #21 How do I set up and configure PHP?

    This is generally outside the scope of the actual PHP development forums. XAMPP and WAMP packages are easily available, and the PHP manual has an entire chapter on installation for various operating systems and environments.

    #22 How do I do date math?

    If you have PHP 5.3 or higher, check out the new DateTime library.

    Otherwise, note that PHP can handle timestamps generated by time() and mktime(). Time stamps are integers and they're measured in seconds. To get the time one hour from now, use time() + 3600. You can infer the rest, I'm sure.

    #23 How can I perform an action every X times? How can I do alternating row colors? How can I do a 3-column layout?

    All of this can be accomplished by modular division. By using the % operator, you can say "do this every X times." If you want alternating row colors...
    php Code:
    $rowCount = 0;
    foreach( $myData as $record ) 
    {
      if ( $rowCount++ % 2 == 0 ) 
      {
        $color = "white";
      }
      else
      {
        $color = "blue";
      }
    }


    #24 My output is unformatted! I can't see my <tags>! My newlines are gone!

    Not true! You're viewing your output in a browser, which is NOT a text viewer. Your browser strips newlines automatically (as it should, since it expects HTML) and converts any tags like <this> into HTML tags, which aren't printed. View the SOURCE of the page to view the actual output.

    #25 How can I have a select box populate another select box?

    Google for this, it can be done easily with AJAX or with a simple page refresh.

    #26 My PHP.ini changes aren't taking effect!

    You must be chaning the proper PHP.ini file and you must restart your webserver.

    #27 Why can't I use my javascript variables in PHP?

    Because as mentioned at the top of this document, PHP and javascript are different languages. Specifically, Javascript won't execute on the same computer that PHP does. PHP executes on your server. Javascript executes on the client machine.

    #28 What language should I learn? Why is PHP better than {some other language}?

    Requinix covered this in detail in the last version of this FAQ

    #29 Why are accented characters displaying incorrectly

    If your non-ASCII/non-English/accented/UTF-8/special characters are not showing up, showing up as question marks or block symbols or showing up incorrectly in general, it usually indicates a character encoding problem. You need to make sure you use UTF-8 encoding at every point where your data is transferred or stored. It most cases you should not use the utf8_encode or utf8_decode functions, as these will not do what you need.

    (1) Make sure your code editor is set to save all files in UTF-8 mode (without the BOM). All of your .php/.html/.tpl/.css/.js/etc files should be saved using UTF-8. This step is necessary to ensure that the characters stored in your files are encoded consistently.

    (2) Make sure your MySQL database character set is set to UTF-8. Depending on your MySql configuration, you might need to configure this for each field individually. Each string field (including text/varchar/char/etc. type fields) in a database table can have an independent character set. This step is necessary to ensure that the characters stored in your MySQL database are encoded consistently.

    (3) Make sure your MySQL connection is set to use UTF-8. Do this using the mysql_set_charset, mysqli_character_set_name function or the charset attribute of the PDO dsn (depending on which MySQL interface you're using). You do not need to execute a "SET NAMES" or "SET CHARACTER SET" query, as the mysql_set_charset function handles the necessary queries for you and changes the client charset to the appropriate values. In fact, running these queries manually is not enough, because neither query updates the client charset and you will run into problems. Execute this function as soon as you connect to MySQL (and every time you connect). Your character set needs to be the same when you insert values and when you read values. This step ensures that you're data is transferred between the web server and the database server without the characters becoming corrupted.

    (4) When you send output to the browser make sure you tell the browser that it is UTF-8 encoded. There are two ways to do this, but I recommend doing both to be sure:

    Send the header:
    php Code:
    header('Content-Type: text/html; charset=utf-8');


    Use this meta tag:
    html Code:
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />


    ===============================================

    Big thanks to JClasen for updating these examples to the PDO and MySQLi
    Last edited by requinix; June 24th, 2013 at 12:25 AM.
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.
  2. #2
  3. No Profile Picture
    Lost in code
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 2004
    Posts
    8,317
    Rep Power
    7170
    --- Hit the post size limit so continuing the FAQ in a new post ---

    #30 Why do I see a blank screen/page when I visit my PHP script?

    Often this indicates that a fatal PHP error is occurring, and your server is not configured to display PHP errors.

    You should enable full error reporting on your development server. You can enable error reporting from within your PHP code to a limited extent, but this is best done by editing the php.ini file or .htaccess file (if running PHP as an Apache module).

    To enable error reporting within your PHP code add this to the top:
    PHP Code:
    error_reporting(E_ALL);
    ini_set("display_errors""on"); 
    This will cause PHP to display all error messages that occur after that point in the script. However, this will not work for fatal syntax errors that exist in the file containing those two lines. Thus, it is still very possible to receive a blank and unhelpful screen after enabling error reporting in this way.

    The best way to enable error reporting is to set the directive via a php.ini or .htaccess file. Almost all web hosts will allow you to do this, but the method in which you do it varies depending on your web host. If none of the following methods work for you, you should contact your web host for assistance.

    You can test whether a particular method worked by creating a test PHP file that intentionally contains a syntax error. For example:
    PHP Code:
    <?php <
    If you execute this file it should display the error message:
    Code:
    Parse error: syntax error, unexpected '<' in (path to file) on line 1
    If you see the error message then you know that error reporting has been enabled. If you see a blank screen then error reporting has not been enabled.

    Method 1: The .htaccess file
    If your server runs PHP as an Apache module you can specify the error reporting level in an .htaccess file. Create or open the .htaccess file in the web root (public_html) directory of your web site and add these lines to it:
    Code:
    php_value error_reporting -1
    php_flag display_errors on
    After saving the .htaccess file one of three things will happen:
    1) You continue seeing a blank screen: either your server is not running Apache or .htaccess overrides are disbled (you cannot use this method)
    2) Your server shows a 500 error: your server is not running PHP as an Apache module (you cannot use this method)
    3) You see a proper PHP error message (you're done, now go fix the error)

    Method 2: The php.ini file
    This method will work with any web server, as long as you have write access to one of PHP's php.ini files. The following code needs to be added to the php.ini file (preferably at the end):
    Code:
    error_reporting = E_ALL
    display_errors = on
    The php.ini file can be located in many different places. Some web hosts allow you to place a php.ini file in any directory, others allow it only in the web root directory (public_html) and others have a specific directory where it is located. Also note that some web hosts name the file php5.ini instead of php.ini. Some web hosts allow you to edit the php.ini via a web based control panel. If you can't find the file, contact your web host for instructions on editing it.

    Important security note: You should NOT display PHP error messages on a production website. You should only display them on development copies of the site that are not accessible to the public. PHP error messages can leak information to attackers that help them exploit your code. You SHOULD enable logging of PHP error messages on production websites. There are additional directives for doing this. Consult the PHP manual for details if you responsible for configuring a production PHP website.

    #31 What does the "undefined index" error mean? How do I fix it?

    Happens most often with forms:
    PHP Code:
    $username $_POST["username"]; // Undefined index: username 
    The problem is that $_POST["username"] doesn't exist. The "username" key is not in the array at all so when you try to get it PHP will complain.

    You need to check if the key exists before you use it, with something isset or empty:
    PHP Code:
    if (isset($_POST["username"])) {
        
    $username $_POST["username"];
    } else {
        
    // username wasn't submitted. display an error message?

    Using
    PHP Code:
    if ($_POST["username"]) { 
    is not the same: it tells PHP to grab the value, but the problem is that there is no value to grab. isset() and empty() are special in that they'll look into the array to see if the key exists.

    Comments on this post

    • ManiacDan agrees : Thanks
    Last edited by requinix; July 1st, 2012 at 05:36 AM. Reason: added 31
    PHP FAQ

    Originally Posted by Spad
    Ah USB, the only rectangular connector where you have to make 3 attempts before you get it the right way around

IMN logo majestic logo threadwatch logo seochat tools logo