www.webdeveloper.com
Results 1 to 14 of 14

Thread: Using Mysql connection in an included file.

  1. #1
    Join Date
    Jan 2006
    Location
    Israel
    Posts
    178

    Using Mysql connection in an included file.

    I was wondering whether it possible to use an Mysql connection in an included file, which was established in the original file.
    Example:
    PHP Code:
    Page1.php
    $query
    ="SELECT * FROM posts Where author=' ".$-POST['searchstring']."'";
    $result=mysql_query($query);

    main.php
    mysql_connect
    ("""""");
    mysql_select_db("");
    include(
    "http://www.something.com/...../....../page1.php"); 
    Any help will be highly appreciated!.

  2. #2
    Join Date
    Jan 2005
    Location
    Alicante (Spain)
    Posts
    7,736
    Yes! By the way if you include a page using an http wrapper it will be parsed individually before inclusion, i.e. you will only be able to include the output, not any functions etc.
    Last edited by bokeh; 01-18-2006 at 03:35 PM.

  3. #3
    Join Date
    Jan 2006
    Location
    Israel
    Posts
    178
    And if i want to include more then the output?, i will need to establish an individual
    separate connection to the DB?.

  4. #4
    Join Date
    Oct 2005
    Location
    Erie, PA
    Posts
    401

    Yes!!

    Yes for instance you can build a Function Library. And put all your functions in that file and import the whole library and call only the functions you need. Here is some tidbits of my Library and how I call them


    I Import In the PHP file I want to view during using the function:
    PHP Code:
    <?php
    require("listingsfunc.php");

    dbconnect();
    eventreg($connection);
    ?>

    And here is the function Library
    PHP Code:
    <?php
    //connects to my database for future querys

    function dbconnect() {
    global 
    $connection;
    $db_name "markbad_markbadsql";
    $connection = @mysql_connect ("localhost""markbad_drpl1""****")
     or die (
    'I cannot connect to the database because: ' mysql_error());
    $db mysql_select_db ($db_name$connection)
     or die (
    'I cannot connect to the database because: ' mysql_error());
    }


    // Shows a regular listing of events from the past week.
    function eventreg($connection) {
    global 
    $display_block;
    $table_name "events";
     
    $sql "SELECT * FROM $table_name WHERE `date` BETWEEN DATE_SUB(CURDATE(), INTERVAL 6 DAY) and DATE_ADD(CURDATE(), INTERVAL 1 DAY) ORDER BY 'bar'"
    $result mysql_query($sql)
     or die (
    mysql_error());
    $display_block =""
    //While loop will create an array called $row
    while ($row mysql_fetch_array($result)) {
    // get individual elements from events
      
    $date = ($row['date']);
      
    $bar = ($row['bar']);
      
    $updated = ($row['updated']);
      
    $details = ($row['details']);
      
    $map_url = ($row['map_url']);
      
    // assume $text has been populated with the desired text from the DB
    $details preg_replace('/\b(erie|bands?|events?|bars?|drinks?|dj?|shows?)\b/i'"<strong>$1</strong>"$details); 
      
       
    $display_block .= "        
            <h4>
    $bar <span class=\"date\"> added on:$updated</span></h4>
            <p>
    $details</p>
            <div align=\"right\"><span class=\"map\"><a href=\"
    $map_url\" target=\"_blank\" title=\"Erie Bar :: $bar\">Get Directions</a></span></div>
            "
    ;        
        }

    }



    The Structure of a Function is this:
    PHP Code:
    function [function_name](arguments) {
     
    //code


  5. #5
    Join Date
    Jan 2005
    Location
    Alicante (Spain)
    Posts
    7,736
    Your problem is here:
    PHP Code:
    include("http://www.something.com/...../....../page1.php"); 
    That is an http path (for external use) you should be using a server file path (internal use) then your code would work fine.

  6. #6
    Join Date
    Jan 2006
    Location
    Israel
    Posts
    178
    If i'll use require instead, the PHP manual indicates that i send a GET array to the included page, can i build athorization system using this?.
    I'll send the clearance that the page riqures as a GET variable.
    Example:
    PHP Code:
    Admin.php
    require("global/Athorization.php?clearance=5"); 
    Can i use exsisting external Mysql connectin when including a page using
    'require'?.

  7. #7
    Join Date
    Jan 2005
    Location
    Alicante (Spain)
    Posts
    7,736
    include() is fine but it will work in neither case if the argument for the function is an http link. And you can certainly not send a query string when using a file path as shown in post #6.
    Last edited by bokeh; 01-19-2006 at 02:02 AM.

  8. #8
    Join Date
    Jan 2006
    Location
    Israel
    Posts
    178
    Then how should i understand the example at the official site?:
    http://il2.php.net/manual/en/function.include.php

    Also how can i terminate the processing of the page from an included page?,
    die() refuses to work.
    Thanks guys!.
    PHP Code:
    <?php

    /* This example assumes that www.example.com is configured to parse .php
     * files and not .txt files. Also, 'Works' here means that the variables
     * $foo and $bar are available within the included file. */

    // Won't work; file.txt wasn't handled by www.example.com as PHP
    include 'http://www.example.com/file.txt?foo=1&bar=2';

    // Won't work; looks for a file named 'file.php?foo=1&bar=2' on the
    // local filesystem.
    include 'file.php?foo=1&bar=2';

    // Works.
    include 'http://www.example.com/file.php?foo=1&bar=2';

    $foo 1;
    $bar 2;
    include 
    'file.txt';  // Works.
    include 'file.php';  // Works.

    ?>
    Last edited by HellgY; 01-19-2006 at 03:40 AM.

  9. #9
    Join Date
    Jan 2005
    Location
    Alicante (Spain)
    Posts
    7,736
    Ok. The difference is this: when you call an http link (URL) you are calling the output that the http link produces, not the file itself. (You would be including the exact same output as if you were to call that URL directly with your browser). On the other hand when you use a server file path you are including the file itself and not just it's output. You may use a query string with the http link but you cannot when using a file path. The reason you can't use a query string in the second instance is because the query string from the original http request is the one applied. Trying to add a query string will result in an error.
    Last edited by bokeh; 01-19-2006 at 04:23 AM.

  10. #10
    Join Date
    Jan 2006
    Location
    Israel
    Posts
    178
    OK, if i got you right, if i use an absolute path(Http://me.com/page.php)
    I may not use external Mysql connections, but i am authorized to add a query in this case. when i use a dynamic path(/page.php) i can use external Mysql connection
    but can't add a query?. That's not a problem, i can just initial a variable in the original page that defines the clearance that it requires.

    I used what i understand as server path, and received the following error:
    Warning: main(/login.php): failed to open stream: No such file or directory in /home/nitay/domains/opend4u.net/public_html/Oleg/EditMessages.php on line 14

    Warning: main(): Failed opening '/login.php' for inclusion (include_path='.:/usr/local/lib/php') in /home/nitay/domains/opend4u.net/public_html/Oleg/EditMessages.php on line 14
    For this line:
    PHP Code:
    include("/login.php"); 
    The original file is at the same directory as the file I'm attempting to include.
    Last edited by HellgY; 01-19-2006 at 09:23 AM.

  11. #11
    Join Date
    Jan 2005
    Location
    Alicante (Spain)
    Posts
    7,736
    Quote Originally Posted by HellgY
    PHP Code:
    include("/login.php"); 
    What is the http path to this file? Or s it in a non public directory.

    If the remote file was stored with a .txt extension you would be able to use the code in it in your script but:
    • doing so would mean the whole world could see the code the file contains.
    • running code from external sources is a major security risk for your server
    Last edited by bokeh; 01-19-2006 at 09:52 AM.

  12. #12
    Join Date
    Jan 2006
    Location
    Israel
    Posts
    178
    What about .lib extension files?, are they a major risk too?, why can't i run the PHP source from these files?, i use a "server path" as you advised...
    the permission code is 755.
    The http path for the original file is:
    http://www.opend4u.net/Oleg/EditMessages.php
    and for the file that i'm attempting to include:
    http://www.opend4u.net/Oleg/login.php

    Thanks!.
    Last edited by HellgY; 01-19-2006 at 10:49 AM.

  13. #13
    Join Date
    Aug 2005
    Location
    The Garden State
    Posts
    5,634
    different extensions are going to behave differently based on the configuration of your server. in general though, you should stick to php files for includes. How does your FTP look when you login? For example, if you have this:
    /
    -www/

    and you put all of your files in www/ and have a parent that you can add anoter folder on, you can include from that folder, and it won't be files that your webserver will pick up on so you could do this:
    /
    -www/
    -hidden/

    and if you have Oleg as a subdirectory to www/ you could include hidden/login.php like this:
    include('../../hidden/login.php');
    or atleast in theory that's how it works.

    with your current setup though, you can just use include('login.php'); to get the file.
    Acceptable Use | SQL Forum FAQ | celery is tasteless | twitter

    celery is tasteless - currently needing some UI time

  14. #14
    Join Date
    Jan 2006
    Location
    Israel
    Posts
    178
    I suppose that the folder that I'm redirected to automatically is the 'root' folder...
    There i have the 'public_html' folder, and my folder which is named 'Oleg',
    When i use HTTP path i can refer directly to the folders within 'public_html'.
    So your advices applies to me!.
    Now i just need to figure out whether i receive the syntax of the page, or only it's output, when including with server path(include("name.php").
    Thanks!.

    Great now i get:
    Parse error: parse error, unexpected T_ELSE in /home/nitay/domains/opend4u.net/public_html/Oleg/login.php on line 63
    For the Code, on the line maskwd with //, The error keep appearing even if i mask the line as an comment:\, I call it out from EditMessages.php to varify that the user is logged in and athorized:
    PHP Code:
    <?php
    $destination
    =referred();
    function 
    referred()
    {
    if(
    stristr($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) !== FALSE)
    $target=$_SERVER['HTTP_REFERER'];
    else
      
    $target=$home;
    return 
    $target;
    }
    if(
    $_COOKIE['session']==1)
    {
    setcookie("name"$_COOKIE['name'], time(60*60), "/Oleg/login"$_SERVER['HTTP_HOST'], 1);
    }
    if(
    $_GET['do']=="disconnect")
      {
      
    $query="SELECT status FROM useres WHERE name='".$_COOKIE['name']."' AND password='".
      
    $_COOKIE['password']."'";
      
    $result=mysql_query($query$link) or die(mysql_query()."--".$query);
      
    $row=mysql_fetch_array($resultMYSQL_ASSOC);
      if(
    $row['status']==3)
        {
            print(
    "You have no access to this page due to your ban");
            }
            else
            {
        
    setcookie("name"NULLtime()-3600"/Oleg/login"$_SERVER['HTTP_HOST'], 1);
        
    setcookie("password"NULLtime()-3600"/Oleg/login"$_SERVER['HTTP_HOST'], 1);
        print(
    "All the cookies was deleted, Now redirecting to the previous page");
        }
      include(
    "/Redirect.php");
      die();
      }
    mysql_free_result($result);
    if(
    $_GET['do']=="login")
       {
       if(
    $_POST['name']!=NULL and $_POST['password']!=NULL)
        {
      
    $query="SELECT status FROM useres WHERE name='".$_POST['name']."' AND password=".
      
    md5($_POST['password'])."";
      
    $result=mysql_query($query$link) or die(mysql_error()."--".$query);
      if(@
    mysql_num_rows($result)==1)
         {
             if(
    $_POST['remember']==1)
               {
               
    $expire=2147483647;
               
    setcookie("session"NULLtime()-3600"/Oleg/login"$_SERVER['HTTP_HOST'], 1);
               }
             else
                {
                
    $expire=time()+(60*60);
                
    setcookie("session"12147483647"/Oleg/login"$_SERVER['HTTP_HOST'], 1);
                 }
                    
    setcookie("name"$_POST['name'], $expire"/oleg/login"$_SERVER['HTTP_HOST'], 1);
                    print(
    "You have successfuly loggen into the system, Now redirecting to the previous page");
                    include(
    "/Redirect.php");
                    die();
              }
              
    mysql_free_result($result);
              else
               print(
    "The information that you supplied is not correct");
        }
    //elseif(isset($_POST['name']) and isset($_POST['password']))
    print("Please fill out all the fields in the form");
    }
       print(
    "<form action=\"".$_SERVER['PHP_SELF']."?do=login\" method=\"post\">
    <table align=\"right\", dir=\"rtl\" cellpadding=\"0\" cellspacing=\"0\" width=\"60%\">
    <tr align=\"right\" dir=\"rtl\">
    <td width=\"68%\" align=\"right\" dir=\"rtl\"></td>
    <td width=\"32%\" align=\"right\" dir=\"rtl\"></td>
    </tr>
    <tr align=\"right\" dir=\"rtl\">
    <td dir=\"rtl\" align=\"right\">
    User Name</td>
    <td dir=\"rtl\" align=\"right\">
    <input type=\"text\" dir=\"ltr\" lang=\"en\" align=\"right\" name=\"name\" ></td>
    </tr>
    <tr align=\"right\" dir=\"rtl\">
    <td dir=\"rtl\" align=\"right\">
    Password</td>
    <td dir=\"rtl\" align=\"right\">
    <input align=\"right\" dir=\"ltr\" lang=\"en\" type=\"password\" name=\"password\"></td>
    </tr>
    <tr align=\"right\" dir=\"rtl\">
    <td dir=\"rtl\" align=\"right\">
    Remember me</td>
    <td dir=\"rtl\" align=\"right\">
    <input align=\"right\" dir=\"ltr\" lang=\"en\" name=\"remember\" type=\"checkbox\" value=\"1\"></td>
    </tr>
    <tr><td collspan=\"2\"><input type=\"submit\" dir=\"rtl\" align=\"center\" value=\"Login\"></td></tr>
    </table>
    </form>"
    );
       }

    if(isset(
    $_COOKIE['name']) and isset($_COOKIE['password']))
      {
       
    $query="SELECT name, password, status FROM users WHERE name='".$_COOKIE['name']."' AND password='"
       
    .$_COOKIE['password']."'";
       
    $result=mysql_query($query$link) or die(mysql_error()."--".$query);
       if(@
    mysql_num_rows($result)==0)
       {
          print(
    "you have illigal cookies<br><a target=\"_self\" href=\"".$_SERVER['PHP_SELF'].      "?do=disconnect\">Erase the cookies</a>");
              die();
       }

       
    $row=mysql_fetch_array($resultMYSQL_ASSOC);
       if(
    $clearance==0)
         {
              if(
    $row['status']==3)
                {
                     print(
    "You are banned and cannot access any of this site's pages");
                     die();
                    }
             }
             
    mysql_free_result($result);
       else
         {
              if(
    $row['clearance']<$clearance)
                 {
                     switch(
    $_GET['clearance'])
                          {
                     case 
    '1':
                       print(
    "You must activate your account before accessing this page");
                     break;
                     case 
    '2':
                       print(
    "This page is not available for your user group");
                   break;
                     case 
    '3':
                       print(
    "This page is not available for your user group");
                       break;
                      case 
    '4':
                      print(
    "This is not available for you user group");
                      break;
                      case 
    '5';
                      print(
    "Only the site owner can access this page");
                         }
                     }
             }
       }
       else
       {
       if(
    $_GET['clearance']!=0)
          {
          print(
    "you must log-im before you can access this page<br>click <a target\"_SELF\" href=".
          
    $_SERVER['PHP_SELF']."?do=login>here</a>");
              die();
          }
       }

      
    ?>
    Last edited by HellgY; 01-19-2006 at 12:36 PM.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles