[FAQ] FAQ Thread (Rev 5)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • R. Rajesh Jeba Anbiah

    #1

    [FAQ] FAQ Thread (Rev 5)

    -----------------------------------------------------------------
    This is the FAQ thread where the FAQ compilation project goes.
    * If you wish to improve the contents, please copy the whole content,
    fix it and then post it. When posting, please change the revision
    number (increase by 1) in the subject line.
    * If you want to comment, do it without changing the subject line.
    * Do NOT add new question and answers here. Add here only after
    posting it to the separate thread; subject line should begin with
    "[FAQ]" tag, for example: [FAQ] What is foo?
    * Always use www.example.com for example URLs.
    -----------------------------------------------------------------
    PHP installation:
    =============== =
    Q: How to run PHP?
    A:
    1. Use command line php and pass php file as an argument. Hardly used.
    2. Run with an webserver preferably Apache. (Access via browser like
    http://localhost/foo.php )

    Q: Where to get PHP?
    Q: How to install PHP?
    A: Install the webserver first. Apache is available at

    Stable PHP version is available at http://www.php.net/downloads.php
    Windows users should note that the installer/exe version is CGI alone;
    for mod_php (aka SAPI), has to download zip version.

    Refer:




    Q: How to install PHP quickly?
    A: XAMPP, a 3rd party provides extensive installation bundle that helps
    the user to install PHP, MySQL, Apache and many extensions in just one
    click.

    Refer:


    Q: Where to get up-to-date PHP builds?
    A:
    Windows: http://snaps.php.net/win32/php5-win32-latest.zip
    Linux: http://snaps.php.net/php5-latest.tar.gz
    Caveats:
    These developement versions may not be stable to use in production.

    Q: Where to get old PHP versions?
    A: http://museum.php.net/

    Q: When using a PHP function, I'm getting "Fatal error: Call to
    undefined function xxxx()".
    A: This says that the function is not available or not enabled. Using
    manual find the extension name that this function belongs to.
    Windows: Open your php.ini and uncomment that extension dll file (eg,
    extension=php_c url.dll).
    Linux: Compile your php source with that library

    Q: Why I'm getting unparsed PHP file in browser?
    A: You might not have instructed your Apache to parse PHP files. You
    have to check httpd.conf

    Refer:


    +++++
    @todo Grammar. More info?
    -----------------------------------------------------------------
    Error reporting:
    ===============
    Q: Why I don't get any errors?
    A: You might have turned the "display errors" off. Turn it on:
    1. By changing 'display_errors ' to true in php.ini (May require
    Apache restart if it is mod_php)
    2. Or with the ini_set('displa y_errors', 1) via script

    Refer:

    Sets the value of a configuration option


    Q: Why certain errors are not displayed?
    A: The error reporting level might be low. Set it to higher value; via
    script error_reporting (E_ALL|E_STRICT )

    Refer:


    Q: What does @ (at-sign) do?
    A: @ is an operator, which, when prepended to an expression,
    suppresses error messages. However the usage is discouraged.

    Refer:


    Example:

    $x = 'a';
    extract($x);
    @extract($x);

    -----------------------------------------------------------------

    URL grabbing:
    ============
    Q: How do I retrieve a page from a web site?
    A: Pass a URL to file() or file_get_conten ts(). The former returns the
    contents as an array of lines. The latter returns the same as string.

    Example:

    $html = file_get_conten ts('http://www.example.com ');

    Q: How do I retrieve a page from a web site that does browser
    detection?
    A: Use ini_set() to change the configuration option "user_agent ." This
    sets
    the User-Agent header sent by PHP.

    Example:

    ini_set('user_a gent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT
    5.1)');
    $html = file_get_conten ts('http://www.example.com ');

    Q: How do I retrieve a page from a web site that requires a cookie?
    A: Use stream_context_ create() to create a HTTP context with Cookie as
    one of the headers. Then, if you are coding in PHP 5, pass the context
    to
    file() or file_get_conten ts() as the third parameter. In PHP 4 either
    function
    accepts a context, so you need to open the URL with fopen() and
    retrieve the data a chunk at a time with fread().

    Example:

    $opts = array(
    'http'=>array(
    'method'=>"GET" ,
    'header'=>
    "Accept-language: en\r\n" .
    "Cookie: foo=bar\r\n"
    )
    );

    $context = stream_context_ create($opts);
    $f = fopen($url, "rb", false, $context);
    while($data = fread($f, 1024)) {
    echo $data;

    }

    stream_context_ create() is available in PHP 4.3.0 and above. If you are
    using an older version, you would need the cURL functions or use
    fsockopen()
    to open the connection and send the cookie header with fputs().

    Example 1:

    $ch = curl_init();
    curl_setopt($ch , CURLOPT_URL, $url);
    curl_setopt($ch , CURLOPT_HTTPHEA DER,
    array("Cookie: foo=bar"));
    curl_exec($ch);
    curl_close($ch) ;

    Example 2:

    $fp = fsockopen($host , $port);
    fputs($fp, "GET / HTTP/1.0\r\n");
    fputs($fp, "Host: $host\r\n");
    fputs($fp, "Cookie: foo=bar\r\n\r\n ");

    while ($data = fgets($fp, 1024)) {
    echo $data;

    }

    -----------------------------------------------------------------
    Visitor details:
    ===============
    Q: How do I get the address of the referrer?

    A: With the variable $_SERVER['HTTP_REFERER']. However, two
    caveats:

    1. A request might not have a Referer header, in which case
    the variable would not be set. Some browsers do not send
    Referer headers, for example, while others can be configured
    not to.

    'The Refer field MUST NOT be sent if the Request-URI was
    obtained from a source that does not have its own URI, such
    as input from the user keyboard.' [HTTP/1.1]

    2. A Referer header can be faked. The information might not
    be genuine.

    Warning: As with all input, you should be cautious over the
    value of $_SERVER['HTTP_REFERER'].

    Note: The Referer header is misspelt; the word in English
    is 'referrer', with four r's. As the misspelling has made
    it into the HTTP specification, it is too late to correct
    it.
    -----------------------------------------------------------------
    Register Globals:
    =============== =
    Q: Why PHP not parsing forms?
    Q: Why form variables not getting posted?
    Q: Why form variables are always empty?
    [color=blue]
    > <form method="post" action="form.ph p">
    > Enter Your Name
    > <input type="text" name="UserName" ></input><br>
    > <input type="submit" name="submit" value="click"></input>
    > </form>[/color]
    [color=blue]
    > <?php
    > if ($submit == "click"){
    > echo "Hello, $UserName";
    > }[/color]
    [color=blue]
    > </body></html>[/color]

    Since 4.2.0 register_global s [1] is off by default due to security
    reasons [2]. One should use super globals (introduced in 4.1.0) instead
    to get to user supplied data [3]. So either fix:

    -fix your code [4]:
    if(isset($_POST['submit']) && $_POST['submit']=="click")
    {
    echo 'Hello, '.$_POST['UserName'];
    }
    -quick&dirty hack:
    extract($_REQUE ST);
    in the global scope.
    -enable register_global s

    1: http://www.php.net/manual/en/ini.cor...gister-globals
    2: http://www.php.net/manual/en/security.globals.php
    3:
    http://www.php.net/manual/en/languag...ned.php#langua...
    4: $_POST['UserName'] should offcourse be escaped properly (with
    htmlspecialchar s in this particular case).

    -----------------------------------------------------------------
    Q: Why HTML is trunctating PHP text? As in
    [color=blue]
    > $test = "Mary had a little lamb"; ...
    > <input type="text" name="T1" value=<?php echo $test;?>>[/color]

    Take a look at the source (the first place you should look to see what
    PHP is actually doing) and you will see it's all there as:
    <input type="text" name="T1" value=Mary had a little lamb>

    See the html specs on attributes (that is what value is):


    To make a long boring spec short:

    The value should be surrounded by quotes if it contains whitespaces,
    the quotes used to delimit should be escaped within the value.

    eg:
    <input type="text" name="T1" value="<?php echo $test;?>">
    or
    <input type="text" name="T1" value='<?php echo $test;?>'>

    would be fine in this case, but will fail if there are quotes in $test:

    $test = "The lamb will soon be Mary's little \"ham\"";

    will break either quoting style unless escaped with:
    <input type="text" name="T1" value='<?php echo
    htmlspecialchar s($test,ENT_QUO TES);?>'>

    -----------------------------------------------------------------
    Q. How do I differentiate an empty string or numeric zero from false?
    A. Use the === operator.

    Refer:

    -----------------------------------------------------------------
    GD:
    ===
    Q. I'm using the GD functions to create thumbnail images. Why am I
    getting
    such crummy results?

    A. imagecopyresize d() does not do a very good job scaling down images.
    Use
    imagecopyresamp led() instead. If you are already using
    imagecopyresamp led(),
    the problem might be that the destination image has limited color
    range.
    Create it with imagecreatetrue color() instead of imagecreate().
    -----------------------------------------------------------------
    Q. Where can I find PHP programming jobs?
    A. Like Bigfoot, the Loch Ness Monster, and alien abductions, PHP jobs
    are a
    myth. The truth is, no one will pay you to program in PHP. If someone
    tells
    you he works as a PHP programmer, he is probably a spy.

    A: --todo-- The above answer remains for historical reasons;-)
    -----------------------------------------------------------------
    Q: Why am I getting the error message 'Headers already sent'?

    If you get this error your script flow is broken (in most cases). Using
    OB is nothing more than hiding the symptoms of the error.

    The error tells you where the real problem lies:
    1:<?php
    2:error_reporti ng(E_ALL);
    3://do stuff
    4:echo "redirectin g";
    5:
    6://do more stuff
    7:
    8:header("Locat ion: http://localhost/");9:?>

    will produce the error:

    Warning: Cannot modify header information - headers already sent by
    (output started at /path/to/script.php:4) in /path/to/script.php on
    line 8

    What is really is trying to say:

    Error: line 8 at /path/to/script.php can't send headers. The problem is
    at line 4 in /path/to/script.php, it produced some output to the client
    so I already had sent all headers before getting to line 8.

    But since you already have all required userinput you should find out
    wheter you need to sent additional headers (like a redirect) before
    outputting anything to the client. So the equivalent script with
    correct
    top down flow would be:
    1:<?php
    2:error_reporti ng(E_ALL);
    3:if($condition ){
    4:header("Locat ion: http://localhost/");
    5:die("redirect ing");
    6:}
    7:
    8:echo "condition was false";
    9:?>

    The following script:
    1:<?php
    2://do stuff
    3:?>
    4:<html><body>

    ---------------------

    A: PHP produces this error message when you try to set a header for a
    web
    page after you have already started sending out the content of the
    page.

    Web content is always delivered with a few headers at the top, ending
    with a
    blank line. For example, a web page might start like this:
    [color=blue]
    > HTTP/1.1 200 OK
    > Date: Tue, 01 Mar 2005 12:00:00 GMT
    > Content-Type: text/html[/color]
    [color=blue]
    > <html>
    > <body> ... etc...[/color]

    Once you have started sending the content of a document, you can't add
    any
    more headers because they won't appear at the top.

    To get round this problem, use PHP's output control functions to buffer
    the
    output before it is sent. For example, you can generate a
    "Content-Length"
    header as follows:
    [color=blue]
    > <?php[/color]
    [color=blue]
    > ob_start(); // Turn on output buffering[/color]
    [color=blue]
    > // Create your web page/jpeg file/whatever here
    > echo "<html><bod y> ... ";[/color]
    [color=blue]
    > // Generate a "Content-Length" header
    > $clen = ob_get_length() ;
    > header("Content-Length: $clen");[/color]
    [color=blue]
    > // Now send the buffered content
    > ob_flush();[/color]

    Q. After turning on output buffering I am still getting 'Headers
    already
    sent.' What the?
    A. Something, somewhere is sent to the browser prior to the call to
    ob_start().

    One possible culprit is white-spaces contained in an included file. To
    fix
    this, move the call to ob_start() ahead of any include/require
    statements.

    Another possible culprit is UTF-8 encoding. Unicode-capable editor
    often
    place an invisible character at the beginning of a UTF-8 text file to
    mark
    it as UTF-8. This character will be output before any PHP statements
    are
    executed. To fix this, resave the file as ASCII.

    The character in question is the zero-width non-breaking space
    (U+FFEF). In
    UTF-16 text it's used as a byte order indicator. In UTF-8 it's just a
    signature. If you leave it out then an editor might not be able to
    correctly
    sniff out the encoding, leaving to other problems.

    -----------------------------------------------------------------
    Login/Authentication:
    =============== =====
    Q: How to implement a login system?
    A: Login/authentication system can be implemented in many ways:
    1. Basic login system:
    When the user logins, set a cookie or session variable and expect
    that variable in every pages.
    2. Sessions based login:
    a. When the user logins, store the session id in the database and
    then compare the current session id with the one stored in the database
    on every page.
    b. Check logged in user's IP on every page.
    c. Check logged in user's browser on every page. May use the user
    agent string ($_SERVER['HTTP_USER_AGEN T']) or hash of it.

    Caveats:
    (1) will definitely allow multiple logins and may allow session
    hijacking.
    (2a) alone may allow session hijacking.
    (2b) may break if the user is behind proxy.
    (2b)&(2c) If session alone (without storing in database) is used as a
    storage, it may break.
    (1), (2a), (2c with database) may provide enough security.


    Refer:




    +++++
    @revision 2 Fixed answer for clarity. See Chung's comment
    @todo Info about other authentications , better link to the login
    implementation (above links use obsolete PHP style)
    -------------
    Q: How to find the logged in users?
    Q: How to find the number of logged in users?

    A: If you use session based authentication/login mechanism, it is quite
    easy when you use custom-DB-based session--so that the session
    variables will be stored in database instead of default files. As the
    session will be available in the database table, it is easy to query
    it/count the number of sessions or records.

    Refer:


    -----------------------------------------------------------------
    PHP editors/IDE:
    ===============

    Q: What is the best IDE for PHP?
    Q: Which PHP IDE supports debugging, autocompletion, syntax
    highligting, etc?
    A: There are so many IDEs available. Some popular IDEs are:
    Free:
    1. PHPEdit <http://www.waterproof. fr/products/PHPEdit/>
    ..Windows.Comme rcial, Free for personal use
    2. PHP Designer 2005 <http://www.mpsoftware. dk/phpdesigner.php >
    Windows. Freeware
    3. Maguma Open Studio <http://sourceforge.net/projects/openstudio>
    Windows. Open source
    4. PHP Coder <http://www.phpide.de/> Windows. Free
    5. Dev-PHP <http://devphp.sourcefo rge.net/dev3/> Windows. Open source
    6. PHP Eclipse <http://www.phpeclipse. de/> Eclipse plugin

    Commercial:
    1. Zend Studio <http://www.zend.com/store/products/zend-studio/>
    Multi-platform
    2. Macromedia Dreamweaver
    <http://www.macromedia. com/software/dreamweaver/> Multi-platform
    3. Maguma Workbench <http://www.maguma.com/> Multi-platform
    4. ActiveState Komodo <http://www.activestate .com/Products/Komodo/>
    Multi-platform
    5. TruStudio <http://www.xored.com/trustudio> Eclipse plugin

    Refer:


    +++++
    @todo Cleanup
    -----------------------------------------------------------------
    -----------------------------------------------------------------
    Contributors:
    ============
    Chung Leong
    John Dunlop
    Daniel Tryba
    Alan Little
    NSpam
    Philip Ronan
    Jan Pieter Kunst
    Janwillem Borleffs

    +++
    @revision 1 Combined texts. Changed Chung's example URL to

    @revision 2
    @revision 3
    @revision 4 ?
    @revision 5 +Janwillem Borleffs. Nospam->NSpam. Added new Q's from the
    FAQ threads. Ordered the contents.
    @todo Cleanup. Grammar fix. Find proper heading. Trim "headers already
    sent"

  • John Dunlop

    #2
    Re: [FAQ] FAQ Thread (Rev 5)

    R. Rajesh Jeba Anbiah wrote:

    [snip entire FAQ rev. 5]

    Ideas for the next revision:

    * I'm happy with www.example.com as the host name for
    examples, but the address should be normalised to
    http://www.example.com/ with a trailing slash.

    * I think some indentation should be introduced to aid the
    reader, much like that of this list. It's hard to find
    your way about the FAQ at the moment. Together with a
    table of contents, numbered questions would be helpful.
    See the format of the c.l.javascript FAQ:
    news:42381f2e$0 $8754$db0fefd9@ news.zen.co.uk

    * The list of contributors should be ordered alphabetically
    and we should of course add Rajesh.

    * The body of the FAQ should contain its revision date.
    Also, a brief introduction would be good. Perhaps the first
    section should be a meta-FAQ.

    * There are more questions to include, the answers to which
    are in the '[FAQ]' threads. And how about a question like
    'Are there any tutorials, books or web sites on PHP?'?

    An example ToC follows. Some of the questions didn't fit into
    any of the categories, so I made up a miscellaneous one at the
    end, and some of the questions, such as the register_global s
    ones, could be merged.

    Table of Contents
    =============== ==

    1 Downloading & installing
    1.1 Where can I get PHP?
    1.2 Where can I get up-to-date PHP builds?
    1.3 Where can I get old PHP versions?
    1.4 How do I install PHP?
    1.5 How do I install PHP quickly?
    1.6 Why am I getting unparsed PHP in my browser?
    2 Error reporting
    2.1 Why am I getting the error message 'Headers already
    sent'?
    2.2 After turning on output buffering I am still getting
    'Headers already sent.' What the?
    2.3 Why do I get "Fatal error: Call to undefined function
    xxxx()"?
    2.4 Why do I not get any errors?
    2.5 Why are certain errors not displayed?
    2.6 What does @ (commercial at-sign) do?
    3 URL grabbing
    3.1 How do I retrieve a page from a web site?
    3.2 How do I retrieve a page from a web site that does
    browser detection?
    3.3 How do I retrieve a page from a web site that requires a
    cookie?
    4 Getting visitor details
    4.1 How do I get the address of the referrer?
    5 Register Globals
    5.1 Why is PHP not parsing my forms?
    5.2 Why are my form variables getting posted?
    5.3 Why are my form variables always empty?
    5.4 Why is HTML trunctating my PHP text?
    6 Creating images with GD library
    6.1 Why am I getting such crummy results when I use the GD
    functions to create thumbnails?
    7 Logging in & authenticating
    7.1 How do I implement a login system?
    7.2 How to find the logged in users?
    7.3 How to find the number of logged in users?
    8 Choosing editors & IDEs
    8.1 What is the best IDE for PHP?
    8.2 Which PHP IDE supports debugging, autocompletion, syntax
    highligting, etc?
    9 Misc
    9.1 How do I differentiate an empty string or numeric zero
    from false?
    9.2 Where can I find PHP programming jobs?
    9.3 How do I run PHP?

    Comments?

    --
    Jock

    Comment

    • R. Rajesh Jeba Anbiah

      #3
      Re: FAQ Thread (Rev 5)

      John Dunlop wrote:[color=blue]
      > R. Rajesh Jeba Anbiah wrote:
      >
      > [snip entire FAQ rev. 5]
      >
      > Ideas for the next revision:
      >
      > * I'm happy with www.example.com as the host name for
      > examples, but the address should be normalised to
      > http://www.example.com/ with a trailing slash.
      >
      > * I think some indentation should be introduced to aid the
      > reader, much like that of this list. It's hard to find
      > your way about the FAQ at the moment. Together with a
      > table of contents, numbered questions would be helpful.
      > See the format of the c.l.javascript FAQ:
      > news:42381f2e$0 $8754$db0fefd9@ news.zen.co.uk
      >
      > * The list of contributors should be ordered alphabetically
      > and we should of course add Rajesh.
      >
      > * The body of the FAQ should contain its revision date.
      > Also, a brief introduction would be good. Perhaps the first
      > section should be a meta-FAQ.
      >
      > * There are more questions to include, the answers to which
      > are in the '[FAQ]' threads. And how about a question like
      > 'Are there any tutorials, books or web sites on PHP?'?
      >
      > An example ToC follows.[/color]
      <snip>

      Thanks for your great suggestions. The FAQ thread I posted is
      merely a quick dirty way to speed up compilation. Your idea to take
      c.l.js as a template is a great suggestion; but I'm not sure about
      their column width (72?). I'll try to format as c.l.js, hoping GG won't
      mess it up.

      --
      <?php echo 'Just another PHP saint'; ?>
      Email: rrjanbiah-at-Y!com Blog: http://rajeshanbiah.blogspot.com/

      Comment

      • John Dunlop

        #4
        Re: FAQ Thread (Rev 5)

        R. Rajesh Jeba Anbiah wrote:
        [color=blue]
        > Your idea to take c.l.js as a template is a great suggestion; but I'm
        > not sure about their column width (72?).[/color]

        Funny you should mention that. I don't know what the c.l.js
        FAQ's line length is, but mine is normally 62 characters. I
        extended it to 72 for this, in keeping with son-of-RFC1036.

        http://www.chemie.fu-berlin.de/outer...n-of-1036.html

        --
        Jock

        Comment

        Working...