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

    PHP - Frequently Asked Questions

    Ok, Im starting this FAQ thread for the PHP forum. This will work pretty much the same as all the other FAQ threads.

    We seriously need some new tutorials added, if you have the time, please go here: <http://www.codingforums.com/showthread.php?t=36142> and consider submitting a tutorial!

    Please do not reply to this thread asking for help, if you are still having problems, start a new topic in the relevant forum describing your problem

    General Rules
    • Please feel welcome to contribute to this thread, but please dont post unless you are adding a good answer to a frequently asked question.
    • If you do contribute, each post should contain one question and answer, no more, no less.
    • Please put keywords or function names that are not within PHP code blocks in blue text.
    • PHP code should be placed in PHP code blocks.
    • When you write a reply, please include links to php.net with the relevant resources.


    For further information on how to add a reply, or if you would rather have your answer proof-read before you post it here (reccomended), then please visit <http://www.codingforums.com/showthread.php?t=36142>

    FAQ Index
    1. My code isn't working, and I get no errors!
    2. Why PHP/JavaScript?
    3. GPC Stripping Tutorial - Magic Quotes
    4. Outputting Data/Common Mistypes
    5. What is the difference between using $HTTP_POST_VARS and $_POST for accessing POST variables?
    6. How do I write to a file using PHP?
    7. How do I read a file using PHP?
    8. Permission denied ... why ? File permissions
    9. How do I resolve the 'headers already sent' error?
    10. How do I make a random password function ?
    11. What is the difference between addslashes() and mysql_real_escape_string() when running MySQL queries?
    12. Sending HTML email with PHP
    13. TIP: Coding styles and $end errors
    14. TIP: Quotes / Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in..
    15. The IE if (isset($_POST['submit'])) bug explained.


    As FAQ entries get added I will add them to the index here.

    Resources

    php.net - The official PHP site, where you can download the latest versions of PHP or lookup functions and syntax.
    mysql.com - MySQL is the database technology that is most often used with PHP, to make dynamic data driven websites and scripts
    Last edited by Fou-Lu; 10-07-2011 at 12:24 AM. Reason: Updated FAQ Index to include newer posts

  • #2
    Senior Coder missing-score's Avatar
    Join Date
    Jan 2003
    Location
    UK
    Posts
    2,194
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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>



    How to write to the beginning of a file?
    A common question is ,'how do you write to the beginning of a file' , the answer is not a new magic mode but a different approach , it should be noted that you can write to the beginning of a file by opening 'r+' and using fseek() to rewind to the start of a file then fputs() etc , however this will overwrite byte for byte the files existing contents.

    To add a line to the beginning of a text file the most straightforward method is to read the file into memory , manipulate and then rewrite the file.
    Newer PHP versions have handy functions such as file_get_contents() to get the files data into a variable , you can also use the above noted functions to read a file into memory or the old sausage <?$str = implode( '', file( $filename ) ) ;?>

    e.g. (no filelocking for clarity)
    PHP Code:
    read the file contents into a variable
    <?php
    $filename 
    'cars.txt' ;
    $str implode'' file$filename ) ) ;
    ?>
    append your data
    <?php
    $str 
    "porche 911sc\n" $str ;
    ?>
    open (overwrite) your existing file
    <?
    $fp 
    fopen$filename ,'w' ) ;
    fputs$fp $str ) ;
    fclose$fp ) ;
    ?>
    Note that the above method becomes resource intensive with larger files.

    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
    Super Moderator
    Join Date
    May 2002
    Location
    Perth Australia
    Posts
    4,058
    Thanks
    10
    Thanked 96 Times in 94 Posts

    permission denied ... why ? file permissions

    <help>I would really appreciate those of you who understand all of this to please check the below is in order since it is a sticky , I am not a unix user , not a trained administrator so any pointers errata are welcomed !!!</help>

    OK so many questions regarding this subject so...here we go.

    Files on any *NIX system have a, at first glance ,complex ownership/permission system , its actually not that complex but can be intimidating at first.
    Now you may think you don't need to understand them (and for most web-related work you probably don't ), however knowledge is power & once you do understand them , you will never again worry about the dreaded `permission denied` , dont skip though , read from the beginning , it makes more sense if you do.

    The 3 common (there are more) *NIX permissions 'r' , 'w' , 'x' ( often 'e' or 'o' ) are applicable to 3 entities , the files 'owner' the files 'group' and 'others' (AKA 'everyone else' 'the world' )

    Ownage
    All files have an owner , who that owner is depends on who created them , when you upload a file via FTP the file is owned by the user that you logged in as.
    So if your FTP login is 'joe' then the file is most likely owned by user 'joe'.

    When however you create a file via script (fopen() etc) the file is still owned by whoever created it , however that user is no longer 'joe' , its the user that your webserver runs as , which is normally NOT your *UNIX username (except in chrooted or suexec environments) , it is normally 'apache' or 'nobody' .

    [b]Groups[b/]
    Groups are a bit of a sticky subject because how groups are assigned varies from system to system , often at the whim of the server administrator or hosting control panel interface , plesk for example assigns all file uploaded via FTP to the 'psacln' group , redhat however by default creates a new group for each user and assigns group ownership to that group (e.g. user 'joe' gets his own group 'joe').

    Others AKA everyone else , the world
    As far as *NIX is concerned , if someone is not the owner of the file or does not belong to the same group as a file , then you are classed as 'others' , contrary to popular belief external applications can not modify files which allow write access to 'others' , only other users of the same system or local network can actually do that (on shared hosting this is a real issue)

    Permissions
    All *NIX files have permissions assigned , there are 3 permissions a file can be given , 'r' for read , 'w' for write & 'x' for executable , a file can have 0 or more permissions . e.g. a file can have both 'r' and 'w' permissions , so they are both readable and writable , 'rwx' means you can do pretty much anything with the file.

    Now the permissions above r,w & x are applied individually to the files owner , the files group and others ! so

    owner group others user group
    myfile rwx r r joe joe

    With the above, the owner of the file (joe) can read write & execute (if applicable , e.g. the file is a script) the file , any members of the 'joe' group (usually just the user joe) can read and write to the file , 'others' can only read the file. when your webserver requests myfile , it does so as 'apache' or nobody' and as such is given read access.

    However , when your script which is probably running as 'apache' comes along and tries to write to the file , it finds it can not .. why? , well 'apache' is not the owner of the file , nor does it belong to the group 'joe' , therefore as far as this file is concerned it belongs to the 'world' group which is only allowed to read, not write to the file.

    to allow apache to write to the file you would need to change the file permissions to ...

    owner group others user group
    myfile rwx rw rw joe joe

    e.g. give 'others' write 'w' access , so an outsider , such as apache , could write to the file.

    vice-versa
    Now lets say you created a file via a PHP script , the file created by PHP (actually by apache with mod_php) will be owned by 'apache' , if you then chmod the file (again via script) to say 0700 (rwx------) then you would not have permission to delete that file via FTP , since you would then be considered as 'others' !
    Luckily if you created a file by script you can chmod it to something more accessible via script <?php chmod( 'myfile' , 0766 );?> , this will then allow you to read and write to the file via FTP.

    so with the following
    owner group others user group
    myfile rwx r r joe joe

    You can not chmod the script via PHP/apache since it only has read access , however if via FTP you (as 'joe') chmod to 0766 or 0777 , then your PHP script can read and write to the file.

    Directories
    Its often assumed that if a directory is not writable then nor are is contents , that however is <B>not</B> the case , a writable file in a read-only directory can still be altered by anyone with the right credentials , however you will not be able to write to that directory unless the directory is writable to the user or application that attempts the write.
    Also to be able to list the directories contents , the directory must be executable to the application attempting to do so , 'read' is not enough (in fact you don't even need the directory to be readable , 'x' is enough.

    scripts
    Need to be executable , HTML & text files etc can simply be read-only , but if a file is a script , then make it executable !

    .................................................................................................... .............................

    modes
    file permissions can be represented as octal modes , but that's easier than it sounds , if ...
    r (read) = 4
    w (write) = 2
    x (execute) = 1

    if the owner of a file has read & write permissions that's 4+2 = 6
    if the group just has read permission that's 4
    if others also only have read permissions , again that's 4

    so myfile below has the mode 0644
    owner group others user group
    myfile rw r r joe joe

    .................................................................................................... .............................

    chmod
    As noted above chmod() can change the permissions of a given file , for a user or an application to change these permissions however the user or application needs to have write access to the file in the first place !!

    for PHP its important when chmod()'ding to use octal values
    chmod( 'myfile' , '0644' ) ; will cause issues , since we are passing the mode as a string
    chmod( 'myfile' , 644 ) ; here 644 , is , as far as PHP is concerned, decimal ! again be prepared for problems
    chmod( 'myfile' , 0644 ) ; is correct !

    .................................................................................................... .............................

    chown & ghgrp
    PHP has the chown & chgrp commands, however only a superuser can use them , so unless your webserver runs as 'root' or similar , you can't use them.

    .................................................................................................... .............................

    CGI disclaimer
    If your server runs PHP as a CGI then much of the above may change , its is not common for CGI scripts to be run as a different user than the webserver via Apaches mod_suexec or phpsuexec etc

    .................................................................................................... .............................

    chrooted environments
    If you webserver runs in a chrooted environment then its possible (probable) that the webserver (above stated as 'apache' or 'nobody') may well run as another user , often as the user account e.g the same as your FTP login , if this is the case then you will have less issues with file ownership & generally be in a much safer playground.

    umask
    Not really important here , but you may wonder why when you create a file via FTP or script that it is given e.g. 0755 for FTP or 0644 for scripts , this is decided by the umask , the responsibility of the server administrator

    .................................................................................................... .............................
    .................................................................................................... .............................

    So , if you read the above , and if it made any sense at all , you will understand why you can't ,immediately alter your files uploaded by FTP via a PHP script, if you don't then read again , if I am making no sense then please post and say so & I will try and clarify , if anyone wants to add to this document , post & I will add/amend
    resistance is...

    MVC is the current buzz in web application architectures. It comes from event-driven desktop application design and doesn't fit into web application design very well. But luckily nobody really knows what MVC means, so we can call our presentation layer separation mechanism MVC and move on. (Rasmus Lerdorf)

  • #4
    New to the CF scene
    Join Date
    Mar 2005
    Location
    Montréal, Canada
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    How can i do a random password function ?

    Q: How can i do a random password function ?

    There it is,
    First of all, you need a character bank as well abcdefghijklm...etc..,
    It looks that you want a password generated by the server, so you need to specify all your chars and yes, Upper cases too..

    1. STEP 1 , Create a file called functions.php and add this content..
      PHP Code:
       // File functions.php
      <?
      function randompassword() {  // Declaring the function
      //Config Start
        
      $salt "abchefghjkmnpqrstuvwxyz0123456789"// Your characters bank
        
      $n "8";                                   // Number of character to return
      //end config
        
      $v strlen($salt);
        
      srand((double)microtime()*1000000);
            
      $i 1;
            while (
      $i <= $n) {
                  
      $num rand() % $v;
                  
      $tmp substr($salt$num1);
                  
      $pass $pass $tmp;
                  
      $i++;
            }
            return 
      $pass;
      }
      Please note, that functions with those structures doesnt called by itself, so you must call it to get results..Let's do it..
    2. STEP 2, in any files who needs a random password, add this to require the file who contain functions at page load, and declare the variable to get the password..

      PHP Code:
       // File index.php
      <? require("functions.php"); ?>
      <html>
      <head>
           Some meta-head infos
           Some javascript scripts..etc..
      </head>
      <body>
           Some contents
      <? 
      $password 
      randompassword(); // $password gonna call the function randompassword and return it into  the variable..
      echo "There's my password:  ".$password."     ";
      ?>
          Some contents   


      </body>
      </html>



    Functions used in this scripts are:

    substr Return parts of a $string
    $i++ Increment / Decrement variables
    srand Seed the random number generator < PHP 4.2
    microtime Return current Unix timestamp with microseconds
    rand Generate a random integer
    strlen Return lenght of a string
    Last edited by tomahack; 03-06-2005 at 01:20 AM.

  • #5
    New Coder
    Join Date
    Sep 2004
    Posts
    51
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Very begginner question:

    Why PHP/JavaScript?

    PHP is server side, while JavaScript is client side, meaning that JavaScript can make popups and other things happen on someones PC, while PHP is server-side, so it does stuff with the server.

  • #6
    Senior Coder
    Join Date
    Aug 2003
    Location
    One step ahead of you.
    Posts
    2,815
    Thanks
    0
    Thanked 3 Times in 3 Posts
    Q: How to resolve the 'headers already sent' error?
    A: This is one of the most common errors. You often get it when your using session_start() or header().
    Headers are sent automatically when any output is sent to the user. You send output with print/echo (and some other functions) as well as having anything outside php tags. This includes blank lines spaces, tabs and all other characters. You must send the header BEFORE the output. You must watch out not to have any blank lines before the <?php tag and after the ?> tag
    PHP Code:
    <?php // There should be no spaces before tag.
    session_start();
    ?>
    // A new line which shouldn't be here. This is important especially the file is included to another file.
    Coding in such a way might be difficult, so you might ask if there is a way to wait with sending the output until the end of script execution. This is where output buffering (ob for short) comes in to play. If you start ob it will save all output and headers into memory instead of sending it. You can send all output at once with the headers.
    PHP Code:
    <?php 
    ob_start
    (); // Send the output. 
    ?> 
    <html> 
    <head> 
    <title>OB test</title> 
    </head> 
    <body> 
    <?php 
    session_start
    (); 
    print 
    SID
    ?> 
    </body> 
    </html> 
    <?php 
    header
    ('Content-type: text/plain'); // An example header.
    ob_end_flush(); // Send the output. 
    ?>
    You can try commenting out the ob_start();

    Functions used:
    ob_start()
    ob_end_flush()
    -mentioned but not OB functions
    session_start()
    header()
    Good to read:
    output buffering

    If you spot an error (or have a suggestion) PM me. I'll fix it as fast as I can.
    I'm not sure if this was any help, but I hope it didn't make you stupider.

    Experience is something you get just after you really need it.
    PHP Installation Guide Feedback welcome.

  • #7
    New Coder
    Join Date
    Jun 2005
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by thewickedjester
    Very begginner question:

    Why PHP/JavaScript?

    PHP is server side, while JavaScript is client side, meaning that JavaScript can make popups and other things happen on someones PC, while PHP is server-side, so it does stuff with the server.
    PHP and JavaScript can be used together also (you can put <?php echo whatnot ?> in <SCRIPT> tags, just as you can put <script>some js here</script> in <?php ?> tags (with the echo before each js command, of course)
    PHP is used to load a page and can be put into certain js variables etc (for instance taking items from a database and putting them into js variables, you would use php in script tags OR if you want to make a certain part of your page scale to the length of your database but have JS inside of it, you would use php to make the length of whatever it is (say <TD>s) and put JavaScript inside each TD.
    Just because JS and PHP are client-side and server-side respectively does not mean they cannot be used together. JS makes pages dynamic (on the client side) while PHP makes pages dynamic (on the server side, when the page actually loads (the user does not see how the php affects the page)).

  • #8
    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();"

  • #9
    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();"

  • #10
    New Coder
    Join Date
    Jun 2006
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Macintosh How do I read a file using PHP?

    How do I read a file using PHP?
    The following are basic steps followed in reading a file using PHP
    Open a file using fopen
    lock the file using flock
    read the contents of the file using fread
    unlock the file using flock
    close the file using fclose
    PHP Code:
    <?php 
    $filename 
    "../example/file.txt"//name of file
    $handle fopen($filename"r"); //open the file using fopen
    flock($handle,LOCK_SH);//lock the file using shared lock for reading
    $contents fread($handlefilesize($filename));//read the file using fread
    echo $contents//display the contents of file
    flock($handle,LOCK_UN);
    fclose($handle);//close the file using fclose
    ?>
    1. The first line of the code specifies name of the file.
    2. Then open the file using fopen in "r" read mode. If the file doesn't exists, it will show you an error.
    3.Lock the file using flock.using an shared lock,which is set by putting LOCK_SH.When a statement reads data without making any modifications, its transaction obtains a shared lock on the data.
    4.Read the data from the file using fread. Read the file until end of the file will be reached.
    5.unlock the file using flockby putting LOCK_UN
    6.close the file using fclose

  • #11
    New to the CF scene
    Join Date
    Jan 2007
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Sending HTML email with PHP

    I read a really good article about the PHP emailing program PHPmailer and decided to check it out.

    Heres how I use it to send HTML emails on my sites:

    Code:
    <?php
    require("class.phpmailer.php");
    require("class.smtp.php");
    
    class MyMailer extends PHPMailer {
        public $From = "form-results@google";
        public $FromName = "Google.com";
        public $Host = "mail.google";
        public $Hostname = "google";
        public $Mailer = "smtp";
        public $Sender = "form-results@google";
        public $SMTPAuth = true;
        public $Username = "form-results@google";
        public $Password = "youwish";
    }
    
    
    $emailresults = '<html><head><title></title></head><body>
    <div style="position:relative; margin:40px 0; padding:1px;">'.$myformss.$debugger.$mess.'</div></body></html>';
    
    session_start();
    
    if(!isset($_SESSION['mailsent'])) $_SESSION['mailsent']=0;
    else $_SESSION['mailsent']++;
    
    
    if ($_SESSION["mailsent"] < 10) {
        $_SESSION["mailsent"]++;
        $mail = new MyMailer();
        $mail->IsHTML(true);
        $mail->AddAddress("post-to-blog@google");
        $mail->AddBCC("webmaster@google");
        $mail->Subject = $mysubject;
        $mail->Body = $emailresults;
        $mail->AltBody = "You are viewing this message because your email client is not configured for html emails.$mess";
        $mail->SetLanguage('en');
        if(!$mail->Send())
        {
            $mail->ClearAllRecipients();
            echo "Message was not sent<br>";
            echo "Mailer Error: " . $mail->ErrorInfo;
        } else $mail->ClearAllRecipients();
        
    } else die('MAILSENT OVER LIMIT!');
    
    ?>

  • #12
    New to the CF scene
    Join Date
    Oct 2007
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Outputting Data
    • echo "Hello<br/>$name"; // Works!
    • echo "Hello\n$name"; // Works!
    • echo 'Hello\n$name'; // outputs "Hello\n$name"

    Why is this?
    functions used with single quotes is used as direct/literal input, and text within single quotes does not get parsed.

    Common Mistypes
    PHP Code:
    if ($variable $condition)  // will always return as true
    if ($variable == $condition)  // correct usage 
    PHP Code:
    if ($variable !== $condition)  // enforces type comparison: http://php.net/language.operators.comparison
    if ($variable != $condition)  // correct usage 
    PHP Code:
    fputs($fp'This is text\n'); // does not make a new line
    fputs($fp"This is text\n"); // this does make a new line 
    Note from Inigoesdr: While you can use any of these and/or examples, you probably want the one marked "correct". See this manual page for more info; specifically precedence.
    PHP Code:
    if ($variable == $condition AND $other != $condition)  // incorrect usage
    if ($variable == $condition && $other != $condition)  // correct usage

    if ($variable == $condition OR $other != $condition)  // incorrect usage
    if ($variable == $condition || $other != $condition)  // correct usage 
    PHP Code:
    // Incorrect
    if ($variable == $condition
          
    execute(); 
          exit; 
    else 
    do_not_execute();
    // Correct
    if ($variable == $condition) {
          
    execute();
          exit;
    }
    else 
    do_not_execute(); 
    More info on control structure syntax is available here.

    There's also the alternative syntax for control structures available to you.
    Last edited by Inigoesdr; 02-23-2008 at 02:19 PM. Reason: Consolidating posts

  • #13
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,647
    Thanks
    2
    Thanked 406 Times in 398 Posts
    My code isn't working, and I get no errors!

    First and foremost: Turn on error reporting at the very beginning of your script.
    PHP Code:
    <?php
    ini_set
    ('display_errors',1);
    ini_set('display_startup_errors',1);
    error_reporting (E_ALL);
    ?>
    If you have MySQL queries that aren't working add some error logic to find out why. See the manual for some examples.

    Also, be sure output buffering is off: ob_end_flush()

    And if you can't figure it out after that, post a new thread in this forum with as much relevant information as possible, and any code that we might need so we can help you as quickly as possible.
    Last edited by Inigoesdr; 11-16-2008 at 06:20 PM.

  • #14
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts

    Alternating Rows

    How do I determine alternating rows?
    Common question when using loops and css divs or tables. There are two ways to determine whether you're current iteration is odd or even. One way is through modulus (remainder) division, and the other way is through bitwise comparison. Bitwise comparison is faster than modulus since only the least significant bit needs to be checked. This equates to approximately 2 - 3 times faster than modulus division.

    PHP Code:
    $aItems = array('Cat''Dog''Mouse''Rabbit');
    $cItems sizeof($aItems);
    for (
    $i 0$i $cItems; ++$i)
    {
        
    printf("<div>%s</div>\n"$aItems[$i]);

    In the above example, $i represents even if one of the following is true:
    PHP Code:
    $bIsEven = ($i == 0); // Most common way
    $bIsEven = !($i 1); // Faster though less used. 
    Conversely, $i is odd if the above are false:
    PHP Code:
    $bIsOdd = ($i != 0);
    $bIsOdd = ($i 1); 
    Using this with the previous loop, the alternating rows would correspond with the classes 'evenRow' and 'oddRow':
    PHP Code:
    $aItems = array('Cat''Dog''Mouse''Rabbit');
    $cItems sizeof($aItems);
    for (
    $i 0$i $cItems; ++$i)
    {
        
    $sClass 'evenRow';
        if (
    $i 1)
        {
            
    $sClass 'oddRow';
        }

        
    printf("<div class=\"%s\">%s</div>\n"$sClass$aItems[$i]);

    Results in:
    Code:
    <div class="evenRow">Cat</div>
    <div class="oddRow">Dog</div>
    <div class="evenRow">Mouse</div>
    <div class="oddRow">Rabbit</div>
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • Users who have thanked Fou-Lu for this post:

    fsmobilez (01-31-2009)

  • #15
    Regular Coder
    Join Date
    Dec 2009
    Location
    UK
    Posts
    495
    Thanks
    0
    Thanked 58 Times in 58 Posts
    go here
    http://www.phpvideotutorials.com/free and check out the free lessons (the first teaches you how to install WAMP)
    My site: JayGilford.com
    Resources:
    PHP Pagination Class | Getting all page links | Handling PHP Errors properly
    If you like a users help, show your appreciation with the rep and thanks buttons :)


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