Announcement

Collapse
No announcement yet.

PHP: Frequently Asked Questions

Collapse
This topic is closed.
X
This is a sticky topic.
X
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • PHP: Frequently Asked Questions

    I have noticed a few questions that come up a lot. I would like this to be a thread where your questions could get answered faster than if you posted a question.

    here are some really good links to start
    PHP Manual
    Practical PHP Programming // Thanks To MizzAuction
    Mysql Manual
    www.apache.org

    A Must Read by anybody that wants to be secure
    Php Security Consortium: PHP Security Guide


    A Simple Connection to Mysql
    Various php articles


    +++++++++++++++++++++++++
    to find out what version of php you have, add this to a file and run it.

    <?php
    phpinfo();
    ?>

    that will tell you a lot of info that will help us help you.

    +++++++++++++++++++++++++

    How to setup apache on windows

    +++++++++++++++++++++++++

    if you have read through some of this and it still doesn't help then please make a post. but it helps us a lot to know that you have at least tried on your own and you are truly stuck.

    if you have anything to add please feel free to pm me or another mod and we can see about adding it.

    more to come.
    Have a Script or Snippet you want to share?

    WWW Standards: HTML 4.01,
    HTML 5, CSS2.1, CSS3, XHTML 1.0
    PHP Standards: PHP Standards

  • #2
    as of version 4.1 of php there is new variables called a superglobals. this superglobal is your friend these are available throughout the whole script, even in functions. they generally work with register_globals being off. you can see if yours if off by running the phpinfo from above and looking at it.

    lets do forms:
    if you have a form that is set to post to a page then we need to use the superglobal _POST. this allows us to get all the forms variables.

    <form action="test.php" method="post">
    <input type="text" values="" name="myname">
    <input type="submit" value="Submit" name="submit">
    </form>

    now, once we hit the submit button it will post the name we entered so to grab it from the form we need this
    PHP Code:
    echo $_POST['myname']; //echos out whatever you entered into the text box 
    that will echo the text we entered. pretty easy huh? well this goes with the url variables that you see now and then. stuff like this

    site.com?id=1&foo=bar

    for the url we use another superglobal called _GET.
    PHP Code:
    echo $_GET['id']  // echos out the value of 1
    echo $_GET['foo']; // echoes out the word "bar" 
    there are others as well, _POST, _GET, _FILES, _COOKIE, _SERVER, GLOBALS, _ENV and _REQUEST

    they are your friends, please use them. for more information you can read up on them here. Predefined Variables
    Have a Script or Snippet you want to share?

    WWW Standards: HTML 4.01,
    HTML 5, CSS2.1, CSS3, XHTML 1.0
    PHP Standards: PHP Standards

    Comment


    • #3
      I have seen this more and more often. some of you want to send emails to you or another address. well in php is it way easy.

      to start we need a form, this will do
      Code:
      <form action="test.php" method="post">
      <input type="text" values="" name="myname">
      <input type="submit" value="Submit" name="submit">
      </form>
      this will allow the user to enter a name in the form and have it submit to your email. now we don't neccassarily hav eto stop at a name so you can add more if you want.

      so the page it submits to test.php will look like this
      PHP Code:
      <?php
      $name 
      $_POST['myname'];
      $message "this the body of the email, Hi, $name";
      $subject "this is the subject of the email";
      $headers "From: you@someplace.com <you@someplace.com>\r\n";
      mail("your@email.com",$subject,$message$headers);
      very basic email, text only. if you want html email it is just a little more added.
      PHP Code:
      <?php
      $name 
      $_POST['myname'];
      $message =  "<html><head></head><body><br /><br />";
      $message .= "this the body of the email, Hi, $name";
      $message .= "<br /></body></html>";
      $subject "this is the subject of the email";
      $headers "From: you@someplace.com <you@someplace.com>\r\nContent-type: text/html";
      mail("your@email.com",$subject,$message$headers);
      of course there is a lot more you can add to that but that will send a very basic html email, pretty simple.

      for more information on email you can read up on it here: mail()

      Edit:
      Note: If you have a local install of WAMP,XAMP or Apache php combo, and setup as 127.90.0.1 or localhost, the mail function will not work unless you install a SMTP server which is a real hassle to setup. But as long as you get a Warning: mail() [function.mail]: Failed to connect to mailserver then you are correct in that it will work when you put it on your webhsot.
      Last edited by scoutt; 01-19-2012, 09:17 AM.
      Have a Script or Snippet you want to share?

      WWW Standards: HTML 4.01,
      HTML 5, CSS2.1, CSS3, XHTML 1.0
      PHP Standards: PHP Standards

      Comment


      • #4
        for some very useful links for php resources, please see this thread

        http://www.htmlforums.com/showthread.php?threadid=44024
        Have a Script or Snippet you want to share?

        WWW Standards: HTML 4.01,
        HTML 5, CSS2.1, CSS3, XHTML 1.0
        PHP Standards: PHP Standards

        Comment


        • #5
          Thanks to DemonicPuffin for this post.

          Nobody can tell you exactly what security holes will exist in your code...as it depends on your exact situation.That being said...a few general guidelines:

          Do NOT Use Register Globals!!!!!

          eg:

          always use: $_GET,$_POST,$_COOKIE,etc.


          so if you have a url like file.php?id=1

          use:

          PHP Code:

          $id 
          $_GET["id"];

          echo 
          $id
          NOT

          PHP Code:
          //only works if register globals is set to ON in php.ini

          echo $id
          The reason for this becomes apparent when doing similar using a form with the POST method....depending on register globals will allow a user to set variables via the query string....as if it were a post form..or worse...a cookie!

          Always Use addslashes(); on data being inserted into a db(If magic_quotes_gpc is off)

          PHP Code:

          $string 
          "I am a 'string with quotes in it'";

          @
          mysql_query("INSERT INTO table (column) VALUES ('".addslashes($string)."')"); 
          will add preceeding backslashes to the quotes.

          This is one very simple way to help prevent a very simple method of attack known as an SQL injection...which is purposely adding SQL queries to the input of a script.This vunerability is extremely common...and can cripple/completely destroy a site in seconds...if the right attacker comes along.

          Using addslashes requires stripslashes on output...

          PHP Code:

          $query 
          = @mysql_query("SELECT col FROM table LIMIT 1");

          $row mysql_fetch_array($query);

          echo 
          stripslashes($row["col"]); 
          using the example string from before..this would output:

          Code:
          I am a 'string with quotes in it '
          Whereas without stripslashes...it would output:

          Code:
          I am a \\'string with quotes in it \\'
          Added:

          Note that by default,a feature called magic_quotes_gpc(Magic Quotes Get,Post,Cookie) is enabled which will automatically "add slashes" to input from GET,POST and COOKIE variables...a replacement for addslashes may be:

          PHP Code:
          function EscapeString($text){
          if (!
          get_magic_quotes_gpc()) {
              
          $text addslashes($text);
          }

          return 
          $text;


          Which checks for this feature before escaping the string.

          Note that an alternative to addslashes thats quite useful for SQL insertion/queries is:

          PHP Code:
          mysql_real_escape_string(); 
          So,in keeping with the above....it could be written as:

          PHP Code:
          function EscapeString($text){
          if (!
          get_magic_quotes_gpc()) {
              
          $text mysql_real_escape_string($text);
          }

          return 
          $text;


          To similar effect.

          Sanatize HTML!!!

          This is almost as important as "slashing" data.Use of the function

          PHP Code:
          htmlentities(); 
          will sanatize(eg: disable) any html the user inputs.Why is this important you might ask?very simple...lets say the user posts a reference to a very shady javascript....perhaps one to steal input data from your script...or redirect your users inappropriately.htmlentities will ensure that the script tag...and other html tags...will be nothing more than decorative strings.

          So...whats a suggested way to process user input from a protection point of view?

          PHP Code:
          /*EscapeString Function Originally Posted By Scoutt*/

          function EscapeString($text){
              
          /*
              ENT_NOQUOTES : does not convert the quotes to its ascii format 
              If you want it to convert the quotes, use ENT_QUOTES instead
              */
              
          $text htmlentities($text,ENT_NOQUOTES);
              if (!
          get_magic_quotes_gpc()) {
                  
          $text mysql_real_escape_string($text);
              }

          return 
          $text;


          Is an example of a function which should provide adequate processing.

          Check,Check,And Re-Check!

          If your expecting a variable to be of a certain type...make sure it IS of that type...for example:

          PHP Code:

          $num 
          $_GET["num"];

          if(
          is_numeric($num))
          {
          echo 
          'Is a number';
          }
          else
          {
          echo 
          'Is NOT a number';

          now if you save the above code as num.php...and use: num.php?num=1

          it will output:

          Code:
          Is a number
          but if you pass it,for example... num.php?num=CHICKEN!!!!!

          It will output:

          Code:
          Is NOT a number
          You could also check entry lengths,exact character contents and even type-cast the ones that fail...but this is beyond the scope of this summary.

          Also..it's usually good form to check all form values to ensure they've been completed...for example:

          PHP Code:

          <?
          if($_POST["submit"])
          {
          $txt = trim($_POST["txt"]); //uses trim to remove leading/trailing whitespace
          if($txt == '')
          {
          echo 'You Didnt Enter Your Text';
          exit; //ends script execution
          }
          }
          ?>
          <form action="<?=$_SERVER["PHP_SELF"]?>" method="post">
          Name: <input type="text" name="txt"/><br/>
          </form>
          This would kill the script if the form field is left empty.


          Use Error Suppression On A Live Site

          PHP errors should be left on for debugging...but never on a live site.You can either suppress errors for functions individually by preceeding them with @...eg:

          PHP Code:

          @mysql_query("..."); 
          or set them for the whole script by putting

          PHP Code:
          error_reporting(E_NONE); 
          as the first line in your script.

          It's also worth mensioning that giving your visitors friendly errors may be a good idea..eg:

          PHP Code:

          @mysql_query("...") or die('An Error Has Occured...please contact the webmaster'); 
          This is by no means exaustive...but I hope it at least helps.

          Please feel free to ask questions.


          Credits: This post was updated to make references to mysql_escape_string(),htmlentities(); and magic_quotes_gpc.Special Credit goes to Scoutt for suggesting these.
          Have a Script or Snippet you want to share?

          WWW Standards: HTML 4.01,
          HTML 5, CSS2.1, CSS3, XHTML 1.0
          PHP Standards: PHP Standards

          Comment


          • #6
            Php Security must read for beginners or experts
            http://www.htmlforums.com/showthread.php?t=75764
            Have a Script or Snippet you want to share?

            WWW Standards: HTML 4.01,
            HTML 5, CSS2.1, CSS3, XHTML 1.0
            PHP Standards: PHP Standards

            Comment


            • #7
              Basic magic quotes information:
              http://www.htmlforums.com/serverside...on-100193.html

              Thanks Vege
              Have a Script or Snippet you want to share?

              WWW Standards: HTML 4.01,
              HTML 5, CSS2.1, CSS3, XHTML 1.0
              PHP Standards: PHP Standards

              Comment


              • #8
                Faster, safer queries using PDO:
                http://www.htmlforums.com/serverside...do-146858.html

                Comment

                Working...
                X