Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 20
  1. #1
    Senior Coder missing-score's Avatar
    Join Date
    Jan 2003
    Location
    UK
    Posts
    2,194
    Thanks
    0
    Thanked 0 Times in 0 Posts

    [ANNC] New PHP FAQ

    I decided to start a new thread for this, as my last one was more asking what anyone thought of it.

    The faq thread is at: <http://www.codingforums.com/showthread.php?t=36143>

    If you want to submit anything, you should use this format, I am going to put what could be an entire post, so you can see how it is meant to look:

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

    Q. How do I write the most basic script?

    A. Possibly the most basic script could be the single echo statement saying "Hello World". Here is an example of what the basic script could look like:

    PHP Code:

    <?php
    echo 'Hello World';
    ?>
    As you can see, the script uses the echo function to print Hello World to the page.

    Resources
    http://www.php.net/echo

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

    Important things to notice
    • I placed PHP code in PHP code blocks.
    • Questions and answers have been bold/underlined in a certain way
    • PHP functions that are not in code blocks have been coloured blue.
    • <?php and ?> tags have been used.. This is important! It ensures that problems wont occur due to the php tags being left out.
    • There is a resources section at the bottom which shows some of the important functions that were used and their links on php.net. For this, please use links in the form of http://www.php.net/function-name, not http://us.php.net/manual/function.whatever.php. (basically, ensure its always http://www.php.net/whatever)


    Making a php.net link is very easy and does not require you to visit the site, simply (assuming its a function), use http://www.php.net/function-name, replace any underscores (_) in the function with hypens (-), and there it is, just a couple of examples:

    strislashes = http://www.php.net/stripslashes
    mysql_select_db = http://www.php.net/mysql-select-db

  • #2
    Senior Coder missing-score's Avatar
    Join Date
    Jan 2003
    Location
    UK
    Posts
    2,194
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Hey guys, I have written this for the PHP FAQ. Before you add it, do you think you could just take a read of it and tell me if there are mistakes or anything I should add. Thanks.



    Q. How do I write to a file using PHP?

    A. This question is often asked in many ways, it could be how to add something to the end of a file, empty a file, or create a file. All of these operations come under writing to a file.

    Firstly, there is a basic pattern to writing to a file, it goes something like this:

    1. Open the file using fopen
    2. Lock the file using flock
    3. Write to the file using fputs or fwrite
    4. Unlock the file using flock
    5. Close the file using fclose


    This is the order that the operations (usually) need to be carried out in. The following example shows you how to create a file, then write a string to the file.

    Jargon
    Handle - The name often given to the variable defined when using the fopen function.
    Mode - A letter that represents how the file should be opened when using fopen.


    PHP Code:
    <?php

    $fp 
    fopen('filename.txt''w'); // set the handle to the variable $fp
    // and open the file in "w" mode.

    $string 'Test String'// set the $string variable

    flock($fpLOCK_EX); // lock the file "exclusivley" for writing

    fputs($fp$string); // write the data to the file

    flock($fpLOCK_UN); // unlock the file

    fclose($fp); // always call fclose to close the file.
    // forgetting to close or lock files is the main cause of
    // files getting corrupted.

    ?>
    1. Now, to go over the example, the first line, where the fopen function is used, opens the file in writeable mode... If the file does not exist it will attempt to create it. The important thing to remember about using the "w" mode in fopen is that any data in the file will be truncated (emptied). There are other file handling modes, which can be looked up on the php website: <http://www.php.net/fopen>. Some of these other modes will also be covered later in this post.

    On the next line, we just simply set the variable $string to the value 'Test String'. This is the data that will get written into the file later on.

    2. Next we lock the file using flock. Using an exclusive lock, which is set by putting LOCK_EX, the file is locked from other scripts writing to the file or reading from it while we put the new information into the file. If the file isn't locked and two scripts try to write to it at the same time, it can get corrupted.

    3. The next part is the part that actually writes the information to the file. Using the fputs function it use the file path and data supplied ($fp and $string in this case), and writes $string to $fp.

    4. From here, the file needs to be unlocked using flock again, otherwise no other scripts would be able to write or read it. To unlock the file, we use LOCK_UN.

    5. Finally, we have finished with the file so we can close it. Using the fclose function we pass it the file handle ($fp) and it closes it. You should always do this as this is another thing that can lead to files getting corrupted.


    Problems?
    If you try this and are still having problems, there are some possible reasons that it is failing, the most likley is that the file or directory you are trying to write to doesn't have the right permissions set. If you are on Linix machines (mosts PHP hosts will be running Linux), then you can CHMOD the file or directory to a value that will allow the scripts to be executed. For testing, I usually set it to 777. You can CHMOD from some FTP programs and online control panels. If you are not sure how to CHMOD on your hosting acount, you should contact your webspace provider.


    This is the basics of writing to a file. Often, however, when you write to a file, you want to be able to add something on to the end of the file, and not delete everything that is in there first. This is very easy to alter, simply change the code:


    PHP Code:
    fopen('filename.txt''w');

    // to

    fopen('filename.txt''a'); 
    This changes the file from opening to write mode (w) to ammend mode (a). When you write to the file now, anything you write to the file gets added onto the end after any existing data.

    Finally, to bring this to a close, just a couple more points...

    1. This only handles with writing to files, you can also read from filed but that is not discussed here
    2. There are many more modes for file handling, look at <http://www.php.net/fopen>
    3. There are also other types of file lock, and you can find these at <http://www.php.net/flock>



    Resources[*]http://www.php.net/fopen[*]http://www.php.net/flock[*]http://www.php.net/fputs[*]http://www.php.net/fwrite[*]http://www.php.net/fclose

  • #3
    Regular Coder
    Join Date
    May 2005
    Posts
    100
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I didnt know about to locking and unlocking thanks.

    But fputs....never heard of that either, cant you just use fwrite?

  • #4
    Senior Coder gsnedders's Avatar
    Join Date
    Jan 2004
    Posts
    2,340
    Thanks
    1
    Thanked 7 Times in 7 Posts
    fputs is an alias of fwrite.
    Last edited by WA; 05-04-2005 at 07:27 AM.

  • #5
    Regular Coder Element's Avatar
    Join Date
    Jul 2004
    Location
    Lynnwood, Washington, US
    Posts
    855
    Thanks
    2
    Thanked 2 Times in 2 Posts
    Q: How do I count using PHP? Eg: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, etc?

    A: Using a loop is the best method of this. Below, I will show you two examples, using for() and while().

    PHP Code:
    <?php
     
    // Using the for() function:
     
    for($i 0$i <= 10$i++) { // $i holds our current count. 10 is where the loop will stop, as indicated by the second condition. Next it will add one too $i and loop again.
    $comma $i// Set this too the current count.
    $comma == 10 $comma "." $comma ", "// If comma equals 10 set it to a period, otherwise set it as a comma.
    echo $i.$comma// Echo the current count and appropriate $comma.
    }
     
    // Using the while() function:
     
    $i 0// Set $i too 0.
    while($i <= 10) { // Continue looping while $i is less then or equals 10.
    $comma $i// Set this too the current count.
    $comma == 10 $comma "." $comma ", "// If comma equals 10 set it to a period, otherwise set it as a comma.
    echo $i.$comma// Echo the current count and appropriate $comma.
    $i++; // Add one to $i to continue counting.
    }
    Be sure to read the pseudo code inside the PHP block. Also, it is a good idea to keep them. Pseudo code is a powerful way to remember and explain what your code is doing, for other viewers and yourself.

    Resources:

    echo()
    for()
    while()

  • #6
    Senior Coder
    Join Date
    Apr 2005
    Location
    Colorado, United States
    Posts
    1,208
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Q: What is the difference between using $HTTP_POST_VARS and $_POST for accessing POST variables?

    A: The difference between $HTTP_POST_VARS and $_POST is that one is depricated, and one is not. $HTTP_POST_VARS (and others such as GET, SERVER, ENV, COOKIE, etc.) were all renamed in PHP 4.1.0 to variables such as $_POST, $_GET, $_SERVER, $_ENV, $_COOKIE, and so on. In later versions of PHP (possibly PHP6) they will be eventually removed.

    It is noteworthy to say that the $HTTP_POST_VARS array and the $_POST superglobal array are not references...that is to say, they are separate variables. Changing the value of $_POST['foo'] will not modify the value of $HTTP_POST_VARS['foo'].

    References:

    Predefined Variables
    "$question = ( to() ) ? be() : ~be();"

  • #7
    Senior Coder missing-score's Avatar
    Join Date
    Jan 2003
    Location
    UK
    Posts
    2,194
    Thanks
    0
    Thanked 0 Times in 0 Posts
    nicely said Velox Letum, feel free to add this to the PHP FAQ at your own convenience.

  • #8
    Regular Coder Element's Avatar
    Join Date
    Jul 2004
    Location
    Lynnwood, Washington, US
    Posts
    855
    Thanks
    2
    Thanked 2 Times in 2 Posts

    Q: Somethings not write with my PHP redirection!

    Q: Something is wrong with my PHP Script. When I use this header() function I get some strange error saying the headers are already sent. What headers? The code is exactly the same as my friends!

    Here is my code:

    PHP Code:
    <html>
    <head>
    <title>Login</title>
    </head>
    <body>
    <?php
    $mypassword 
    "foobar";
    if(isset(
    $_POST['submit']) && $_POST['password'] == $mypassword) { 
      echo 
    "Thank you for logging in, admin!";
      
    header("Location: http://example.com/admin.php?pass=".$_POST['password']);
    } else {
      die(
    "Wrong password!");
    }

    ?>
    </body>
    </html>
    A: The reason your getting this strange error with the header() function is because this function specifically must be placed at the top of your file, or before anything is outputted.

    Lets call anything you see on your browser something thats outputted. We must trigger header() before anything is outputted.

    Also, because you are using this function there is really no need to output anything at all because the function will redirect the client instantly, becuase its redirecting before anything is outputted.

    So, to fix the code you would do the fallowing:

    PHP Code:
    <?php

    $mypassword 
    "foobar"// This is okay, client-side won't read this.

    if(isset($_POST['submit']) && $_POST['password'] == $mypassword) { // This is okay too.
      
    header("Location: http://example.com/admin.php?pass=".$_POST['password']); // Alright! The user is logged in, here we go!
    } else {
      die(
    "<html>\n
            <head>\n
            <title>Login: Failed</title>\n
            </head>\n
            <body>\n
            <strong style="
    color:red;">Wrong password! Please go back and try again.</srong>\n
            </body>\n
            </html>"
    );
    }

    ?>
    Resources:

    isset()
    header()
    die()
    Last edited by Element; 12-19-2005 at 11:11 PM.

  • #9
    New Coder
    Join Date
    Sep 2005
    Location
    Steger, IL
    Posts
    73
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Question:
    What is an include or require?

    Answer:

    An include allows you to run a PHP a script (or some HTML code) from inside another PHP script. A require does basically the same thing, but the difference being when an include fails to run, it produces a warning, whereas a require would produce a fatal error instead.

    Include_once and require_once will execute the include or require, but only once so as not to repeat the script.



    Question:
    How/Why would I do an include?

    Answer:
    How?

    PHP Code:
    <?php include "dbconnect.php"?>
    Why?

    You are placing the same thing (ex:header) on several pages of a website, but it's not desirable to include the entire syntax of it on each and every page. You'd write the script once, save it and then use the include on each page to call the script. This is neater and more efficient.

    Another great example is, you want to call a database on more than one page. You'd write something like this...

    PHP Code:
    //connect to mysql
    $connect mysql_connect("localhost""username""password") or
        die (
    "failed to connect");

    //select the desired database
    mysql_select_db("database"); 
    Last edited by joviyach; 12-21-2005 at 07:10 PM.
    Jim

  • #10
    Senior Coder missing-score's Avatar
    Join Date
    Jan 2003
    Location
    UK
    Posts
    2,194
    Thanks
    0
    Thanked 0 Times in 0 Posts
    joviyach: Could you possibly go into any more depth on your FAQ/Answer. its something that will be useful to post, but you should metion that:

    - Includes and requires will run code from the PHP file you bring in
    - You can use normal HTML as well as PHP, which just gets added to the page output
    - You can use require_once and include_once to avoid repeating code.

    I will be happy to do this for you, but if you would rather do it yourself then please do.

  • #11
    Senior Coder
    Join Date
    Apr 2005
    Location
    Colorado, United States
    Posts
    1,208
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Q: What is the difference between addslashes() and mysql_real_escape_string() when running MySQL queries?

    A: The difference between addslashes() and mysql_real_escape_string() is that mysql_real_escape_string() escapes all characters harmful to a mysql query (such as line feeds, carriage returns, quotes, and a number of other assorted special characters), while addslashes() only escapes quotes (both single and double), backslashes, and the NULL byte.

    Related to this topic is magic quotes. If magic_quotes_gpc is enabled in the PHP config, it automatically runs the equivalent of addslashes() on $_POST, $_GET, and $_COOKIE data (and by proxy, $_REQUEST data). If magic_quotes_runtime is enabled, it runs it on almost all external data (file reads, database results, and so on). Thus, we would want to remove this from our data before entering, as when used with mysql_real_escape_string() it would double-escape values, and would cause errors.

    Snippit:
    PHP Code:
    $username $_POST['username']; // Value is ' OR ''=', which would be executed as part of the query without escaping.

    if (get_magic_quotes_gpc() || get_magic_quotes_runtime()) { // Check if either magic_quotes_gpc or magic_quotes_runtime are enabled.
         
    $username stripslashes($username); // Strip the slashes added by magic quotes.
    }

    $username mysql_real_escape_string($username); // String is now safe to use in a query. 
    One more warning is to not use mysql_real_escape_string() on integers. You can, but all it will do is convert them to strings, and there are ways to do so with far less overhead. You may want to write a function which acts as a wrapper for mysql_real_escape_string() and checks if it is an integer first.

    Resources:

    addslashes()
    stripslashes()
    mysql_real_escape_string()
    get_magic_quotes_gpc()
    get_magic_quotes_runtime()
    Magic Quotes
    "$question = ( to() ) ? be() : ~be();"

  • #12
    Senior Coder missing-score's Avatar
    Join Date
    Jan 2003
    Location
    UK
    Posts
    2,194
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Definatley post that up in the main FAQ thread Velox, Ive been asked that so many times...

  • #13
    Senior Coder
    Join Date
    Apr 2005
    Location
    Colorado, United States
    Posts
    1,208
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I'll do that now. Will this thread be switched in there at some point, or are we just adding these for a different purpose?

    Edit: Oops, I spoke too soon. I saw the link in the main FAQ thread to add 'tutorials'. Should I also include things such as gzipping the output of a webpage to save bandwidth and transfer time?
    Last edited by Velox Letum; 12-21-2005 at 02:00 AM.
    "$question = ( to() ) ? be() : ~be();"

  • #14
    Senior Coder missing-score's Avatar
    Join Date
    Jan 2003
    Location
    UK
    Posts
    2,194
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Velox Letum
    I'll do that now. Will this thread be switched in there at some point, or are we just adding these for a different purpose?

    Edit: Oops, I spoke too soon. I saw the link in the main FAQ thread to add 'tutorials'. Should I also include things such as gzipping the output of a webpage to save bandwidth and transfer time?
    This thread was started in 2004, and is just for posting up tutorials before posting them in the main PHP forum, to check for accuracy and whether its worth posting at all.

    Yeah, you could write something about gzipping output, I dont think thats there already.

  • #15
    New Coder
    Join Date
    Nov 2005
    Location
    Louisville, Kentucky
    Posts
    94
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Sessions (a very brief tutorial)

    Initializing and Destorying Sessions

    Sessions are useful if you want to transmit data between pages without the use of query string (http://localhost/blah.php?user=buchard | this is the query string).

    To begin a session, you place this simple fragment of PHP code at the very top of your .php file:
    PHP Code:
    session_start(); 
    If placed in two pages, you are able to send session varibles, such as:
    PHP Code:
    $_SESSION["data"] = "This is a string which will be seen on another page"
    If you use the following code on another page:
    PHP Code:
    session_start();
    echo 
    $_SESSION["data"]; 
    You will receive the string that you set in the first page.

    To destory a session, you use the follow code:
    PHP Code:
    session_destroy(); 
    You are also able to delete single varibles by using the following code:
    PHP Code:
    unset($_SESSION["data"]); 
    By using this, the session varible, data, no longer exists.
    What was I thinking?
    Email Me


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •