Jump to content

cobusbo

Members
  • Posts

    224
  • Joined

  • Last visited

Posts posted by cobusbo

  1. Hi Ive made a database with the option to kick someone for a certain amount of time but seems like I'm doing something wrong somewhere can anybody please assist

     

    My full script is 

     

    (Admin panel)

    <?
    include "./emoticon_replace1.php";
    
    
      if ($_POST["DeletePost"]) {
        $id = $_POST["id"];
        $query = "DELETE FROM ".$dbTable." WHERE id='".$id."'"; 
        mysql_query($query);
        echo "ID removed from system: ".$id;
      }
      if ($_POST["BanIP"]) {
        $IP_To_Add = $_POST["ip"];
        if(eregi("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$", $IP_To_Add))
        {
          $sql = "INSERT INTO ".$IPBanTable." (ip) VALUES (\"$IP_To_Add\")";
          $result = mysql_query($sql);
        } else {
          echo "Error: Not a valid IP: ".$IP_To_Add;
        }
      }
      if ($_POST["purge"]) {
        $query = "TRUNCATE TABLE ".$dbTable; 
        mysql_query($query);
        echo "StringyChat purged";
      }
      if(!$_POST["update"] || !$_POST["StringyChat_name"] || !$_POST["StringyChat_message"]) {
      } else {
        $id = $_POST["id"];
        $name = $_POST["StringyChat_name"];
        $message = $_POST["StringyChat_message"];
    
    
        include("emoticon_replace.php");
    
    
        $query = "UPDATE ".$dbTable." SET StringyChat_name='$name', StringyChat_message='$message' WHERE id='".$id."'";
        $result = mysql_query($query, $db) or die("Invalid query: " . mysql_error());
      }
      if ($_POST["EditPost"]) {
        $id = $_POST["id"];
        $result = mysql_query("SELECT * FROM ".$dbTable." WHERE id='".$id."'", $db); 
        $myrow = mysql_fetch_array($result);
    ?>
        <form name="StringyChat_form" method="POST" action="?mode=postman">
          Name:<br>
          <input name="StringyChat_name" class="StringyChatFrm" type="text" size="20" maxlength="<? echo $name_size; ?>" value="<? echo $myrow["StringyChat_name"]?>">
          <br>
          Message:<br>
          <textarea name="StringyChat_message" class="StringyChatFrm" cols="20" rows="4"><? echo $myrow["StringyChat_message"]?></textarea>
          <br>
          <input type="hidden" name="id" value="<? echo $id ?>">
          <input name="update" class="StringyChatFrm" type="submit" value="Update">
        </form>
    
    
    <?
      }
    ?>
    
    
      <a href="<? echo $_SERVER['REQUEST_URI']; ?>&m=purge">Purge StringyChat</a><br>
        <br>
    
    
      <?
      // Load up the last few posts.  The number to load is defined by the "ShowPostNum" variable.
      $result = mysql_query("SELECT * FROM ".$dbTable." ORDER BY StringyChat_time DESC",$db);
    
    
      while ($myrow = mysql_fetch_array($result)) {
        $msg = $myrow["StringyChat_message"];
    
    
        $msg = strip_tags($msg);
        $msg = eregi_replace("im#([a-z]{3})", "<img src=\"/stringychat/images/\\1.gif\" alt=\"emoticon\">",$msg);
    
    
    printf("<div class=\"StringyChatItem\"><h4>%s<br>\n", $myrow["StringyChat_name"]);
    printf("%s<p>\n",$myrow["StringyChat_ip"],"%s</p>\n");
        printf("%s</h4>\n", date("H:i - d/m/y", $myrow["StringyChat_time"]));
        printf("%s</div>\n", $msg);
    
    
    
    
    if ($_POST["1h"]) {
        $mxitid1= $_POST["1h"];
        if(eregi("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$", $IP_To_Add))
        {
          $sql1 = "UPDATE ".$dbTable." SET unban_time = DATE_ADD(NOW(), INTERVAL 1 DAY) WHERE mxit_id = $mxitid1)";
          $result1 = mysql_query($sq1l);
        } else {
          echo "Error: Cannot Kick: ".$IP_To_Add;
        }
      }
    function checkban($mxitid) 
        { 
            // querys database 
            $q = mysql_query("SELECT 1 FROM ".$dbTable." WHERE unban_time > NOW() AND mxit_id = '$mxitid'",$db); 
            $get = mysql_num_rows($q); 
            // if found 
            if ($get == "1") 
                {  
                    // deny user access 
                    $r=mysql_fetch_array($q); 
                    die("You have been banned from this website until $r[legnth]. If you feel this is in error, please contact the webmaster at ."); 
                } 
        }
    
    
    
    
    
    
    
    
    ?>
        <form name="form<? echo $myrow["id"];?>" method="post" action="?mode=postman">
          <input name="id" type="hidden" value="<? echo $myrow["id"];?>">
          <input name="ip" type="hidden" value="<? echo $myrow["StringyChat_ip"];?>">
          <input name="EditPost" type="submit" id="EditPost" value="Edit">
          <input name="DeletePost" type="submit" id="DeletePost" value="Delete">
          <input name="BanIP" type="submit" id="BanIP" value="Ban <? echo $myrow["StringyChat_ip"];?>">
    <input name="1h" type="submit" id="1" value="Kick <? echo $myrow["mxit_id"];?>">
    <input name="1d" type="submit" id="1d" value="Kick <? echo $myrow["StringyChat_ip"];?> for 24 hours ">
    <input name="7d" type="submit" id="7d" value="Kick <? echo $myrow["StringyChat_ip"];?> for 7 days ">
        </form>
      <?
      }   
    ?>
    

    The part I added to the above script which is giving me pain is 

     

    if ($_POST["1h"]) {
        $mxitid1= $_POST["1h"];
        if(eregi("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$", $IP_To_Add))
        {
          $sql1 = "UPDATE ".$dbTable." SET unban_time = DATE_ADD(NOW(), INTERVAL 1 DAY) WHERE mxit_id = $mxitid1)";
          $result1 = mysql_query($sq1l);
        } else {
          echo "Error: Cannot Kick: ".$IP_To_Add;
        }
      }
    function checkban($mxitid) 
        { 
            // querys database 
            $q = mysql_query("SELECT 1 FROM ".$dbTable." WHERE unban_time > NOW() AND mxit_id = '$mxitid'",$db); 
            $get = mysql_num_rows($q); 
            // if found 
            if ($get == "1") 
                {  
                    // deny user access 
                    $r=mysql_fetch_array($q); 
                    die("You have been banned from this website until $r[legnth]. If you feel this is in error, please contact the webmaster at ."); 
                } 
        }
    

    What I'm trying to do is to ban the person for 1 day. And by banning the person I want them to be blocked from my Index page from submitting a form (sending a message) which is stored as tik.php on my index page

     

     

    index.php

    <?php
    require_once('common.php');
    
    
    include "ip-ban-time-limit.php";
    checkban($_SERVER['HTTP_X_MXIT_USERID_R']);
    
    
    
    
    
    
    checkUser();
    ?>
    
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
    <html>
    <head>
       <title>Galaxy Universe Chat</title>
       <link href="style/style.css" rel="stylesheet" type="text/css" />
    </head>
    <body><br>
        <div id="main">
          <div class="caption">Galaxy Universe Chat</div>
          <div id="icon"> </div>
          <div id="result">
    Hello <?php echo $_SESSION['userName']; ?> ! <br/>
    <div style="color:red"><b><p>Please keep it clean and in English or you will be banned!</p></b></div>
    <br>
    <?PHP
    
    
    include "./stringychat.inc.php";
    require_once ( 'tik.php' );
    
    
    ?>
    
    
    <br>
    
    
    
    
    <p><a href="index1.php">Refresh</a> | <a href="logout.php">Log Out</a></p>
     </div> 
     <div id="source">Galaxy Wars chat @ cobusbo</div>
        </div>
    </body>   
    

    Seems like I've been doing something wrong with my queries...

     

  2.  

    The changes you made will have no effect because the form in your admin script is not being submitted to your  ip-ban-time-limit.php script!  

     

    The changes you need to make to both scripts will be

     

    In the admin script, when the ban form is submitted you need to an add a new entry containing the following information into the ip-log.txt file

    • the users ip address
    • and the timestamp for when the ban will be lifted. For example if the user is band for 1 hour use strtotime('+1 hour')  to generate the timestamp for when the ban is lifted. See strtotime for more info

    The ip-ban-time-limit.php script will need to be written from scratch. The steps you need to take here are

    • get the user ip
    • check to see if the ip is listed in ip-log.txt
    • if it is found in the file. Check to see if the current time is greater than the recorded timestamp
    • restrict access if sufficient time has not passed.
    • only when sufficient time has passed you can remove the users ip from ip-log.txt

     

     

    Thank you I decided to move to MySQL database rather

    Before you jump to the technical details, I think the concept itself needs a reality check.

     

    Do you honestly believe that anybody on the Internet will wait 7 days for you to unban their IP address? I don't think so. Chances are they're back in 7 seconds with a new IP. I mean, even the dumbest script kiddie knows how to use a proxy, use ToR or simply reset their router.

     

    At the same time there's a huge risk of blocking legitimate users just because they happen to share their IP address with somebody else. If you hit a big proxy or VPN, you'll lock out hundreds or thousands of people who haven't done anything. Is your site so incredibly popular that you can live with that?

     

    I understand why programmers like IP bans: They're easy, they're cheap, and they give you the illusion of “doing something”. But I fear they solve no problems while creating new ones.

     

    I'm sure there's a better approach. What are you trying to do? Is this a public chat where you want to block certain participants? Then I'd use a cookie-like mechanism. Of course you shouldn't use actual cookies, because those are a bit too obvious. But if you search for Evercookie, you'll find a lot of more creative techniques.

     

    Another interesting concept is the hellban: Instead of actually blocking the user, you just ignore their messages. So while they believe they're still taking part in the discussion, they cannot be seen by anybody.

     

    Of course no technique is perfect. Anybody with a decent level of knowledge can circumvent any ban. What you can and should do, however, is keep the average troll busy without locking out half of the world's population.

    Thank You I saw I can use another Method to block people

  3.  

    A simple checkup before you go for the query should work this out. Just check if the value has been stored into the variable, else put some default value there.

    $mxitid = $_SERVER["HTTP_X_MXIT_USERID_R"];
    
    if(!isset($mxitid))
    {
    	$mxitid = "DEFAULT";
    }
    

    Thank you

  4. Hi Im having some trouble implementing info into a database

     

    I got the line

     

     



    $mxitid = $_SERVER["HTTP_X_MXIT_USERID_R"];


     

    Which I'm importing to my database via

     

     

     



    $sql = "INSERT INTO ".$dbTable." (StringyChat_ip,StringyChat_name,StringyChat_message,StringyChat_time,mxit_id) VALUES (\"$ip\",\"$name\",\"$message\",$post_time,$mxitid)";
                      $result = mysql_query($sql);


     

    well its working perfectly, but the problem I'm experiencing is that if my value

     



    $_SERVER["HTTP_X_MXIT_USERID_R"]


    cannot be retrieved I can't insert any info to my database.

     

    the

     



    $_SERVER["HTTP_X_MXIT_USERID_R"]


    is being used via a specific platform called mxit, so if I use any other platform it don't work. Is there maybe a way to change the line

     



    $mxitid = $_SERVER["HTTP_X_MXIT_USERID_R"];


    to a function if the info couldn't be retrieved to insert another default value like "ADMIN" rather in the place of it?

  5. The problem with your code is you have not told it who to ban. It just blindly records every visitors ip and does not allow them to access the page again until 36 seconds have passed.  You need to alter the code so it only blocks the visitors who you want to ban.

    Ok I tried to do the following

     

    in

     
    <?php
    // Published at: www.TakeTwoApps.com
       include("chat_code_header.php");
    require_once('common.php');
    
    
    
    
    $ipLog='ip-log.txt'; // Your logfiles name here
    $timeout='0.01'; // How many hours to block IP
    $goHere='tik.php'; // Allowed pages name here
    
    
    
    
    $register_globals = (bool) ini_get('register_gobals');
    if ($register_globals) $vis_ip = $k2;
    else $vis_ip = $k2;
    
    
    
    
    function recordData($vis_ip,$ipLog,$goHere)
    { 
        $log=fopen("$ipLog", "a+"); 
        fputs ($log,$vis_ip."][".time()."\n"); 
        fclose($log); 
    
    
        // The below header function was causing errors in apache 
        //so I changed it to echo the script tag. 
        //Header ("Location: $goHere"); exit(0);  
        echo "<?php include('$goHere')?>"; exit(0);
    } 
    function checkLog($vis_ip,$ipLog,$timeout) 
    {
        global $valid; $ip=$vis_ip;
        $data=file("$ipLog"); $now=time();
    
    
        foreach ($data as $record) 
        {
            $subdata=explode("][",$record);
            if ($now < ($subdata[1]+3600*$timeout) && $ip == $subdata[0]) 
            {
                $valid=0; echo "You have been banned from accessing this page. Try again in $timeout hours.";
                break;
            }
        }
    } 
    checkLog($vis_ip,$ipLog,$timeout);
    if ($valid!="0") recordData($vis_ip,$ipLog,$goHere); 
    
    
    ?>

    I changed the lines

    
       $register_globals = (bool) ini_get('register_gobals');
        if ($register_globals) $vis_ip = getenv(REMOTE_ADDR);
        else $vis_ip = $_SERVER['REMOTE_ADDR'];

    to

    $register_globals = (bool) ini_get('register_gobals');
    if ($register_globals) $vis_ip = $k2;
    else $vis_ip = $k2;
    

    an in my admin script 

     

     

    <?
    include "./emoticon_replace1.php";
    
    
      if ($_POST["DeletePost"]) {
        $id = $_POST["id"];
        $query = "DELETE FROM ".$dbTable." WHERE id='".$id."'"; 
        mysql_query($query);
        echo "ID removed from system: ".$id;
      }
      if ($_POST["BanIP"]) {
        $IP_To_Add = $_POST["ip"];
        if(eregi("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$", $IP_To_Add))
        {
          $sql = "INSERT INTO ".$IPBanTable." (ip) VALUES (\"$IP_To_Add\")";
          $result = mysql_query($sql);
        } else {
          echo "Error: Not a valid IP: ".$IP_To_Add;
        }
      }
      if ($_POST["purge"]) {
        $query = "TRUNCATE TABLE ".$dbTable; 
        mysql_query($query);
        echo "StringyChat purged";
      }
      if(!$_POST["update"] || !$_POST["StringyChat_name"] || !$_POST["StringyChat_message"]) {
      } else {
        $id = $_POST["id"];
        $name = $_POST["StringyChat_name"];
        $message = $_POST["StringyChat_message"];
    
    
        include("emoticon_replace.php");
    
    
        $query = "UPDATE ".$dbTable." SET StringyChat_name='$name', StringyChat_message='$message' WHERE id='".$id."'";
        $result = mysql_query($query, $db) or die("Invalid query: " . mysql_error());
      }
      if ($_POST["EditPost"]) {
        $id = $_POST["id"];
        $result = mysql_query("SELECT * FROM ".$dbTable." WHERE id='".$id."'", $db); 
        $myrow = mysql_fetch_array($result);
    ?>
        <form name="StringyChat_form" method="POST" action="?mode=postman">
          Name:<br>
          <input name="StringyChat_name" class="StringyChatFrm" type="text" size="20" maxlength="<? echo $name_size; ?>" value="<? echo $myrow["StringyChat_name"]?>">
          <br>
          Message:<br>
          <textarea name="StringyChat_message" class="StringyChatFrm" cols="20" rows="4"><? echo $myrow["StringyChat_message"]?></textarea>
          <br>
          <input type="hidden" name="id" value="<? echo $id ?>">
          <input name="update" class="StringyChatFrm" type="submit" value="Update">
        </form>
    
    
    <?
      }
    ?>
    
    
      <a href="<? echo $_SERVER['REQUEST_URI']; ?>&m=purge">Purge StringyChat</a><br>
        <br>
    
    
      <?
      // Load up the last few posts.  The number to load is defined by the "ShowPostNum" variable.
      $result = mysql_query("SELECT * FROM ".$dbTable." ORDER BY StringyChat_time DESC",$db);
    
    
      while ($myrow = mysql_fetch_array($result)) {
        $msg = $myrow["StringyChat_message"];
    
    
        $msg = strip_tags($msg);
        $msg = eregi_replace("im#([a-z]{3})", "<img src=\"/stringychat/images/\\1.gif\" alt=\"emoticon\">",$msg);
    
    
    printf("<div class=\"StringyChatItem\"><h4>%s<br>\n", $myrow["StringyChat_name"]);
    printf("%s<p>\n",$myrow["StringyChat_ip"],"%s</p>\n");
        printf("%s</h4>\n", date("H:i - d/m/y", $myrow["StringyChat_time"]));
        printf("%s</div>\n", $msg);
    
    
    
    
    if (isset($_POST['$k2'])) {
        echo $myrow["StringyChat_ip"]
        return;
    }
    
    
    
    
    ?>
        <form name="form<? echo $myrow["id"];?>" method="post" action="?mode=postman">
          <input name="id" type="hidden" value="<? echo $myrow["id"];?>">
          <input name="ip" type="hidden" value="<? echo $myrow["StringyChat_ip"];?>">
          <input name="EditPost" type="submit" id="EditPost" value="Edit">
          <input name="DeletePost" type="submit" id="DeletePost" value="Delete">
          <input name="BanIP" type="submit" id="BanIP" value="Ban <? echo $myrow["StringyChat_ip"];?>">
    <input name="$k2" type="submit" id="1" value="Kick <? echo $myrow["StringyChat_ip"];?> for 1 hour ">
    <input name="1d" type="submit" id="1d" value="Kick <? echo $myrow["StringyChat_ip"];?> for 24 hours ">
    <input name="7d" type="submit" id="7d" value="Kick <? echo $myrow["StringyChat_ip"];?> for 7 days ">
        </form>
      <?
      }   
    ?>
    
    
      

     i added the function

     

    if (isset($_POST['$k2'])) {
        echo $myrow["StringyChat_ip"]
        return;
    }

    but still every time I refresh my index page I get banned...

     

    Any help please...

     
  6. The problem with your code is you have not told it who to ban. It just blindly records every visitors ip and does not allow them to access the page again until 36 seconds have passed.  You need to alter the code so it only blocks the visitors who you want to ban.

    Ok I was trying to specify who to kick via this page and form for the administrator

     

    <?
    include "./emoticon_replace1.php";
    
    
      if ($_POST["DeletePost"]) {
        $id = $_POST["id"];
        $query = "DELETE FROM ".$dbTable." WHERE id='".$id."'"; 
        mysql_query($query);
        echo "ID removed from system: ".$id;
      }
      if ($_POST["BanIP"]) {
        $IP_To_Add = $_POST["ip"];
        if(eregi("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$", $IP_To_Add))
        {
          $sql = "INSERT INTO ".$IPBanTable." (ip) VALUES (\"$IP_To_Add\")";
          $result = mysql_query($sql);
        } else {
          echo "Error: Not a valid IP: ".$IP_To_Add;
        }
      }
      if ($_POST["purge"]) {
        $query = "TRUNCATE TABLE ".$dbTable; 
        mysql_query($query);
        echo "StringyChat purged";
      }
      if(!$_POST["update"] || !$_POST["StringyChat_name"] || !$_POST["StringyChat_message"]) {
      } else {
        $id = $_POST["id"];
        $name = $_POST["StringyChat_name"];
        $message = $_POST["StringyChat_message"];
    
    
        include("emoticon_replace.php");
    
    
        $query = "UPDATE ".$dbTable." SET StringyChat_name='$name', StringyChat_message='$message' WHERE id='".$id."'";
        $result = mysql_query($query, $db) or die("Invalid query: " . mysql_error());
      }
      if ($_POST["EditPost"]) {
        $id = $_POST["id"];
        $result = mysql_query("SELECT * FROM ".$dbTable." WHERE id='".$id."'", $db); 
        $myrow = mysql_fetch_array($result);
    ?>
        <form name="StringyChat_form" method="POST" action="?mode=postman">
          Name:<br>
          <input name="StringyChat_name" class="StringyChatFrm" type="text" size="20" maxlength="<? echo $name_size; ?>" value="<? echo $myrow["StringyChat_name"]?>">
          <br>
          Message:<br>
          <textarea name="StringyChat_message" class="StringyChatFrm" cols="20" rows="4"><? echo $myrow["StringyChat_message"]?></textarea>
          <br>
          <input type="hidden" name="id" value="<? echo $id ?>">
          <input name="update" class="StringyChatFrm" type="submit" value="Update">
        </form>
    
    
    <?
      }
    ?>
    
    
      <a href="<? echo $_SERVER['REQUEST_URI']; ?>&m=purge">Purge StringyChat</a><br>
        <br>
    
    
      <?
      // Load up the last few posts.  The number to load is defined by the "ShowPostNum" variable.
      $result = mysql_query("SELECT * FROM ".$dbTable." ORDER BY StringyChat_time DESC",$db);
    
    
      while ($myrow = mysql_fetch_array($result)) {
        $msg = $myrow["StringyChat_message"];
    
    
        $msg = strip_tags($msg);
        $msg = eregi_replace("im#([a-z]{3})", "<img src=\"/stringychat/images/\\1.gif\" alt=\"emoticon\">",$msg);
    
    
    printf("<div class=\"StringyChatItem\"><h4>%s<br>\n", $myrow["StringyChat_name"]);
        printf("%s</h4>\n", date("H:i - d/m/y", $myrow["StringyChat_time"]));
        printf("%s</div>\n", $msg);
    ?>
        <form name="form<? echo $myrow["id"];?>" method="post" action="?mode=postman">
          <input name="id" type="hidden" value="<? echo $myrow["id"];?>">
          <input name="ip" type="hidden" value="<? echo $myrow["StringyChat_ip"];?>">
          <input name="EditPost" type="submit" id="EditPost" value="Edit">
          <input name="DeletePost" type="submit" id="DeletePost" value="Delete">
          <input name="BanIP" type="submit" id="BanIP" value="Ban <? echo $myrow["StringyChat_ip"];?>">
    <input name="1" type="submit" id="1" value="Kick <? echo $myrow["StringyChat_ip"];?> for 1 hour ">
    <input name="1d" type="submit" id="1d" value="Kick <? echo $myrow["StringyChat_ip"];?> for 24 hours ">
    <input name="7d" type="submit" id="7d" value="Kick <? echo $myrow["StringyChat_ip"];?> for 7 days ">
        </form>
      <?
      }   
    ?>

    via the input buttons 1, 1d, 7d since I want to make 3 different Banning option 1 hour, 1 day and 7 days. What should I do to change it?

  7. So why are you trying to use it? All of the above code needs to be thrown away.

    Because it's the only example on how to implement timed banning I could find. I would have loved to add it to a MySQL table im not sure how to implement it. And with the above code it's basically standalone.

  8. Hi I found a very old outdated script for temporary banning people. But I'm having some problems running the functions.

     

    First off here is my banning functions script named ip-ban-time-limit.php

     

     



        <?php
        // Published at: www.TakeTwoApps.com
        
        
        $ipLog='ip-log.txt'; // Your logfiles name here
        $timeout='0.01'; // How many hours to block IP
        $goHere='tik.php'; // Allowed pages name here
        
        
        $register_globals = (bool) ini_get('register_gobals');
        if ($register_globals) $vis_ip = getenv(REMOTE_ADDR);
        else $vis_ip = $_SERVER['REMOTE_ADDR'];
        
        
        function recordData($vis_ip,$ipLog,$goHere)
        { 
            $log=fopen("$ipLog", "a+"); 
            fputs ($log,$vis_ip."][".time()."\n"); 
            fclose($log); 
         
            // The below header function was causing errors in apache 
            //so I changed it to echo the script tag. 
            //Header ("Location: $goHere"); exit(0);  
            echo "<?php include('$goHere')?>"; exit(0);
        } 
        function checkLog($vis_ip,$ipLog,$timeout) 
        {
            global $valid; $ip=$vis_ip;
            $data=file("$ipLog"); $now=time();
        
            foreach ($data as $record) 
            {
                $subdata=explode("][",$record);
                if ($now < ($subdata[1]+3600*$timeout) && $ip == $subdata[0]) 
                {
                    $valid=0; echo "You have been banned from accessing this page. Try again in $timeout hours.";
                    break;
                }
            }
        } 
        checkLog($vis_ip,$ipLog,$timeout);
        if ($valid!="0") recordData($vis_ip,$ipLog,$goHere); 
        
        ?>


     

    I wanted to add the file tik.php which contains a form to post underneath a chat script if the person isn't banned with the above script. so I changed  the line

    echo "<?php include('$goHere')?>"; exit(0);

    from location.replace to the include function.

     

     

    Then I added 

    require_once ( 'ip-ban-time-limit.php' );

    on my index page

     



        <?php
        require_once('common.php');
        
        
        
        
        checkUser();
        ?>
        
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
        <html>
        <head>
           <title>Galaxy Universe Chat</title>
           <link href="style/style.css" rel="stylesheet" type="text/css" />
        </head>
        <body><br>
            <div id="main">
              <div class="caption">Galaxy Universe Chat</div>
              <div id="icon"> </div>
              <div id="result">
        Hello <?php echo $_SESSION['userName']; ?> ! <br/>
        <div style="color:red"><b><p>Please keep it clean and in English or you will be banned!</p></b></div>
        <br>
        <?PHP
        
        include "./stringychat.inc.php";
        require_once ( 'ip-ban-time-limit.php' );
        
        ?>
        
        <br>
        
        
        <p><a href="index1.php">Refresh</a> | <a href="logout.php">Log Out</a></p>
         </div>
         <div id="source">Galaxy Wars chat @ cobusbo</div>
            </div>
        </body>   


     

    But now I have the problem that every time I refresh my index page I'm getting banned as well. How can I change it so that I'm not getting banned every time I'm trying to refresh the page?

  9. Hi guys im having trouble implementing functions into some buttons. I got a kicking script from the internet that looks as follow

     

     
    <?php
    // Published at: www.TakeTwoApps.com
    
    
    
    
    $ipLog='ip-log.txt'; // Your logfiles name here
    $timeout='0.01'; // How many hours to block IP
    $goHere='allowed-page.html'; // Allowed pages name here
    
    
    
    
    $register_globals = (bool) ini_get('register_gobals');
    if ($register_globals) $vis_ip = getenv(REMOTE_ADDR);
    else $vis_ip = $_SERVER['REMOTE_ADDR'];
    
    
    
    
    function recordData($vis_ip,$ipLog,$goHere)
    { 
        $log=fopen("$ipLog", "a+"); 
        fputs ($log,$vis_ip."][".time()."\n"); 
        fclose($log); 
    
    
        // The below header function was causing errors in apache 
        //so I changed it to echo the script tag. 
        //Header ("Location: $goHere"); exit(0);  
        echo "<script>location.replace('$goHere')</script>"; exit(0);
    } 
    function checkLog($vis_ip,$ipLog,$timeout) 
    {
        global $valid; $ip=$vis_ip;
        $data=file("$ipLog"); $now=time();
    
    
        foreach ($data as $record) 
        {
            $subdata=explode("][",$record);
            if ($now < ($subdata[1]+3600*$timeout) && $ip == $subdata[0]) 
            {
                $valid=0; echo "You have been banned from accessing this page. Try again in $timeout hours.";
                break;
            }
        }
    } 
    checkLog($vis_ip,$ipLog,$timeout);
    if ($valid!="0") recordData($vis_ip,$ipLog,$goHere); 
    
    
    ?>
    
    
    

    but what im trying to do is to make 3 different times for kicking. lets say a kick for 1h, 24h and one for 7 days. So it will mean I will have to make 3 of the above scripts. But now my problem is that I want to implement the above functions into the following buttons

     

    <input name="1" type="submit" id="1" value="Kick <? echo $myrow["StringyChat_ip"];?> for 1 hour ">
    <input name="1d" type="submit" id="1d" value="Kick <? echo $myrow["StringyChat_ip"];?> for 24 hours ">
    <input name="7d" type="submit" id="7d" value="Kick <? echo $myrow["StringyChat_ip"];?> for 7 days ">
    
    

     in the following script

     

    <?
    include "./emoticon_replace1.php";
    
    
      if ($_POST["DeletePost"]) {
        $id = $_POST["id"];
        $query = "DELETE FROM ".$dbTable." WHERE id='".$id."'"; 
        mysql_query($query);
        echo "ID removed from system: ".$id;
      }
      if ($_POST["BanIP"]) {
        $IP_To_Add = $_POST["ip"];
        if(eregi("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$", $IP_To_Add))
        {
          $sql = "INSERT INTO ".$IPBanTable." (ip) VALUES (\"$IP_To_Add\")";
          $result = mysql_query($sql);
        } else {
          echo "Error: Not a valid IP: ".$IP_To_Add;
        }
      }
      if ($_POST["purge"]) {
        $query = "TRUNCATE TABLE ".$dbTable; 
        mysql_query($query);
        echo "StringyChat purged";
      }
      if(!$_POST["update"] || !$_POST["StringyChat_name"] || !$_POST["StringyChat_message"]) {
      } else {
        $id = $_POST["id"];
        $name = $_POST["StringyChat_name"];
        $message = $_POST["StringyChat_message"];
    
    
        include("emoticon_replace.php");
    
    
        $query = "UPDATE ".$dbTable." SET StringyChat_name='$name', StringyChat_message='$message' WHERE id='".$id."'";
        $result = mysql_query($query, $db) or die("Invalid query: " . mysql_error());
      }
      if ($_POST["EditPost"]) {
        $id = $_POST["id"];
        $result = mysql_query("SELECT * FROM ".$dbTable." WHERE id='".$id."'", $db); 
        $myrow = mysql_fetch_array($result);
    ?>
        <form name="StringyChat_form" method="POST" action="?mode=postman">
          Name:<br>
          <input name="StringyChat_name" class="StringyChatFrm" type="text" size="20" maxlength="<? echo $name_size; ?>" value="<? echo $myrow["StringyChat_name"]?>">
          <br>
          Message:<br>
          <textarea name="StringyChat_message" class="StringyChatFrm" cols="20" rows="4"><? echo $myrow["StringyChat_message"]?></textarea>
          <br>
          <input type="hidden" name="id" value="<? echo $id ?>">
          <input name="update" class="StringyChatFrm" type="submit" value="Update">
        </form>
    
    
    <?
      }
    ?>
    
    
      <a href="<? echo $_SERVER['REQUEST_URI']; ?>&m=purge">Purge StringyChat</a><br>
        <br>
    
    
      <?
      // Load up the last few posts.  The number to load is defined by the "ShowPostNum" variable.
      $result = mysql_query("SELECT * FROM ".$dbTable." ORDER BY StringyChat_time DESC",$db);
    
    
      while ($myrow = mysql_fetch_array($result)) {
        $msg = $myrow["StringyChat_message"];
    
    
        $msg = strip_tags($msg);
        $msg = eregi_replace("im#([a-z]{3})", "<img src=\"/stringychat/images/\\1.gif\" alt=\"emoticon\">",$msg);
    
    
    printf("<div class=\"StringyChatItem\"><h4>%s<br>\n", $myrow["StringyChat_name"]);
        printf("%s</h4>\n", date("H:i - d/m/y", $myrow["StringyChat_time"]));
        printf("%s</div>\n", $msg);
    ?>
        <form name="form<? echo $myrow["id"];?>" method="post" action="?mode=postman">
          <input name="id" type="hidden" value="<? echo $myrow["id"];?>">
          <input name="ip" type="hidden" value="<? echo $myrow["StringyChat_ip"];?>">
          <input name="EditPost" type="submit" id="EditPost" value="Edit">
          <input name="DeletePost" type="submit" id="DeletePost" value="Delete">
          <input name="BanIP" type="submit" id="BanIP" value="Ban <? echo $myrow["StringyChat_ip"];?>">
    <input name="1" type="submit" id="1" value="Kick <? echo $myrow["StringyChat_ip"];?> for 1 hour ">
    <input name="1d" type="submit" id="1d" value="Kick <? echo $myrow["StringyChat_ip"];?> for 24 hours ">
    <input name="7d" type="submit" id="7d" value="Kick <? echo $myrow["StringyChat_ip"];?> for 7 days ">
        </form>
      <?
      }   
    ?>
    
    
      

    but im not sure how to connect the function to kick someone to the button 1, 1d and 7d... can anybody assist me with this please.

     

    And lastly my kicking script at the top. got the function

        echo "<script>location.replace('$goHere')</script>"; exit(0);
    

    to redirect me to another page. but how can I change the line to rather include a specific page on the current page when the ban has been lifted... and how do I check on the page if the ban has been lifted or not?

  10. the syntax error is because your source code contains an error. you are using the Ternary operator on the line where the error is being reported. the Ternary operator doesn't use an if().

     

    next, the best, general purpose method to use to highlight/change words in text, based on database entries would be -

     

    1) get a unique list of words from all the content you are going to display on the page. this would require that you retrieve the rows from your pagination query. if you store these rows into an array, you can simply loop over this array later when displaying the information. as you are retrieving the rows from the pagination query, split them on the white-space/word boundaries and add all the words to an array. then use array_unique() to reduce this array to just the unique list of words.

     

    2) using the unique list of words from step #1, run a query against your banned word table to get just the entries from that table that  are found in the unique list of words from the content. you can implode the unique list of words and use WHERE word  IN('word1','word2','word3', ...) comparison in the query.

     

    3) retrieve the list of matching bad words into an array, then when you have the full list, implode that array using a | character. this makes a regular expression OR'ed pattern of all the found bad words.

     

    4) as you loop through the content (the first array from step #1) to display it, you can use a preg_replace() statement, with the regular expression pattern from step #3, to find and replace any bad words with the replacement string.

     

    Thank you I solved my problem  :happy-04:

    <?php
    
    
    
    
    
    
    // database connection info
    $conn = mysql_connect('mysql.2freehosting.com','u506124311_cobus','92295454') or trigger_error("SQL", E_USER_ERROR);
    $db = mysql_select_db('u506124311_chat',$conn) or trigger_error("SQL", E_USER_ERROR);
    
    
    
    
    // find out how many rows are in the table 
    $sql = "SELECT COUNT(*) FROM StringyChat";
    $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
    $r = mysql_fetch_row($result);
    $numrows = $r[0];
    
    
    // number of rows to show per page
    $rowsperpage = 5;
    // find out total pages
    $totalpages = ceil($numrows / $rowsperpage);
    
    
    // get the current page or set a default
    if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
       // cast var as int
       $currentpage = (int) $_GET['currentpage'];
    } else {
       // default page num
       $currentpage = 1;
    } // end if
    
    
    // if current page is greater than total pages...
    if ($currentpage > $totalpages) {
       // set current page to last page
       $currentpage = $totalpages;
    } // end if
    // if current page is less than first page...
    if ($currentpage < 1) {
       // set current page to first page
       $currentpage = 1;
    } // end if
    
    
    // the offset of the list, based on current page 
    $offset = ($currentpage - 1) * $rowsperpage;
    
    
    // get the info from the db 
    $sql = "SELECT StringyChat_time, StringyChat_name, StringyChat_message FROM StringyChat ORDER BY id DESC LIMIT $offset, $rowsperpage";
    $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
    
    
    
    
    
    
    function filterBadWords($str)
    {
    
    
    
    
        $result1 = mysql_query("SELECT word FROM StringyChat_WordBan") or die(mysql_error()); 
        $replacements = ":-x";
        
        while($row = mysql_fetch_assoc($result1))
        {
              $str = eregi_replace($row['word'], str_repeat(':-x', strlen($row['word'])), $str);
        }  
        
        return $str;
    }
    
    
    
    
    
    
    // while there are rows to be fetched...
    while ($list = mysql_fetch_assoc($result)) 
    //while (($pmsg = $list['StringyChat_message'] == $bwords) ? ":-x" : $list['StringyChat_message'])
     {
       // echo data
       //echo ($pmsg = ($list['StringyChat_message'] == $bwords) ? ":-x" : $list['StringyChat_message'])
    
    
       echo '<span style="color:#828282">' . '(' . date( 'D H:i:s', $list['StringyChat_time'] )  . ') ' . '</span>' . '<b>' . $list['StringyChat_name'] . '</b>' . ' : ' . filterBadWords($list['StringyChat_message']) . '<br />';
    } 
    
    
    // end while
    
    
    /******  build the pagination links ******/
    // range of num links to show
    $range = 3;
    
    
    // if not on page 1, don't show back links
    if ($currentpage > 1) {
       // show << link to go back to page 1
       echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
       // get previous page num
       $prevpage = $currentpage - 1;
       // show < link to go back to 1 page
       echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
    } // end if 
    
    
    // loop to show links to range of pages around current page
    for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
       // if it's a valid page number...
       if (($x > 0) && ($x <= $totalpages)) {
          // if we're on current page...
          if ($x == $currentpage) {
             // 'highlight' it but don't make a link
             echo " [<b>$x</b>] ";
          // if not current page...
          } else {
             // make it a link
             echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
          } // end else
       } // end if 
    } // end for
    
    
    // if not on last page, show forward and last page links        
    if ($currentpage != $totalpages) {
       // get next page
       $nextpage = $currentpage + 1;
        // echo forward link for next page 
       echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
       // echo forward link for lastpage
       echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
    } // end if
    /****** end build pagination links ******/
    ?>
  11. Hi I have a column in my database showing Banned words. What im trying to do is to recall the list of bad words from my database and if some of them is going to be displayed they should replace it with :-x well I made the `$bwords` to recall the info from the database.
    Here is the snippet
     // the offset of the list, based on current page 
    $offset = ($currentpage - 1) * $rowsperpage;
    
    
    // get the info from the db 
    $sql = "SELECT StringyChat_time, StringyChat_name, StringyChat_message FROM StringyChat LIMIT $offset, $rowsperpage";
    $bwords = "SELECT word FROM StringyChat_WordBan";
    $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
    $test = mysql_query($bwords, $conn) or trigger_error("SQL", E_USER_ERROR);
    
    
    //$pmsg = ($list['StringyChat_message'] == $bwords) ? ":-x" : $list['String//yChat_message'];
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    // while there are rows to be fetched...
    //while ($list = mysql_fetch_assoc($result)) 
    while ($list = mysql_fetch_assoc($result, $test)) 
    //while (($pmsg = $list['StringyChat_message'] == $bwords) ? ":-x" : $list['StringyChat_message'])
     {
       // echo data
       //echo ($pmsg = ($list['StringyChat_message'] == $bwords) ? ":-x" : $list['StringyChat_message'])
    
    
       echo '<span style="color:#828282">' . '(' . date( 'D H:i:s', $list['StringyChat_time'] )  . ') ' . '</span>' . '<b>' . if($list['StringyChat_message'] == $test) ? ":-x" : $list['StringyChat_message'] . '</b>' . ' : ' . $pmsg . '<br />'
    } 
    
    
    // end while

    and here is the full code

     

    <?php
    
    
    // database connection info
    $conn = mysql_connect('...','...','...') or trigger_error("SQL", E_USER_ERROR);
    $db = mysql_select_db('...',$conn) or trigger_error("SQL", E_USER_ERROR);
    
    
    // find out how many rows are in the table 
    $sql = "SELECT COUNT(*) FROM StringyChat";
    $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
    $r = mysql_fetch_row($result);
    $numrows = $r[0];
    
    
    // number of rows to show per page
    $rowsperpage = 5;
    // find out total pages
    $totalpages = ceil($numrows / $rowsperpage);
    
    
    // get the current page or set a default
    if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
       // cast var as int
       $currentpage = (int) $_GET['currentpage'];
    } else {
       // default page num
       $currentpage = 1;
    } // end if
    
    
    // if current page is greater than total pages...
    if ($currentpage > $totalpages) {
       // set current page to last page
       $currentpage = $totalpages;
    } // end if
    // if current page is less than first page...
    if ($currentpage < 1) {
       // set current page to first page
       $currentpage = 1;
    } // end if
    
    
    // the offset of the list, based on current page 
    $offset = ($currentpage - 1) * $rowsperpage;
    
    
    // get the info from the db 
    $sql = "SELECT StringyChat_time, StringyChat_name, StringyChat_message FROM StringyChat LIMIT $offset, $rowsperpage";
    $bwords = "SELECT word FROM StringyChat_WordBan";
    $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
    $test = mysql_query($bwords, $conn) or trigger_error("SQL", E_USER_ERROR);
    
    
    $pmsg = ($list['StringyChat_message'] == $bwords) ? ":-x" : $list['StringyChat_message'];
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    // while there are rows to be fetched...
    //while ($list = mysql_fetch_assoc($result)) 
    while ($list = mysql_fetch_assoc($result, $test)) 
    //while (($pmsg = $list['StringyChat_message'] == $bwords) ? ":-x" : $list['StringyChat_message'])
     {
       // echo data
       //echo ($pmsg = ($list['StringyChat_message'] == $bwords) ? ":-x" : $list['StringyChat_message'])
    
    
       echo '<span style="color:#828282">' . '(' . date( 'D H:i:s', $list['StringyChat_time'] )  . ') ' . '</span>' . '<b>' . if($list['StringyChat_message'] == $test) ? ":-x" : $list['StringyChat_message'] . '</b>' . ' : ' . $pmsg . '<br />'
    } 
    
    
    // end while
    
    
    /******  build the pagination links ******/
    // range of num links to show
    $range = 3;
    
    
    // if not on page 1, don't show back links
    if ($currentpage > 1) {
       // show << link to go back to page 1
       echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
       // get previous page num
       $prevpage = $currentpage - 1;
       // show < link to go back to 1 page
       echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
    } // end if 
    
    
    // loop to show links to range of pages around current page
    for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
       // if it's a valid page number...
       if (($x > 0) && ($x <= $totalpages)) {
          // if we're on current page...
          if ($x == $currentpage) {
             // 'highlight' it but don't make a link
             echo " [<b>$x</b>] ";
          // if not current page...
          } else {
             // make it a link
             echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
          } // end else
       } // end if 
    } // end for
    
    
    // if not on last page, show forward and last page links        
    if ($currentpage != $totalpages) {
       // get next page
       $nextpage = $currentpage + 1;
        // echo forward link for next page 
       echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
       // echo forward link for lastpage
       echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
    } // end if
    /****** end build pagination links ******/
    ?>

    The current error I receive is 

    Parse error: syntax error, unexpected T_IF in/home/u506124311/public_html/ag/page.php on line 63

     

     

    But im even sure if the snippet part is correct in what im trying to do...

  12. Is this any better?

     

    My current code is as follow

     

     



        <?php
        
        ####################################################################
        # File Upload Form 1.1
        ####################################################################
        # 
        ####################################################################
        
        ####################################################################
        #  SETTINGS START
        ####################################################################
        
        // Folder to upload files to. Must end with slash /
        define('DESTINATION_FOLDER','/www/zubrag/tmp/');
        
        // Maximum allowed file size, Kb
        // Set to zero to allow any size
        define('MAX_FILE_SIZE', 0);
        
        // Upload success URL. User will be redirected to this page after upload.
        define('SUCCESS_URL','http://www.example.com/upload-success.html');
        
        // Allowed file extensions. Will only allow these extensions if not empty.
        // Example: $exts = array('avi','mov','doc');
        $exts = array();
        
        // rename file after upload? false - leave original, true - rename to some unique filename
        define('RENAME_FILE', true);
        
        // put a string to append to the uploaded file name (after extension);
        // this will reduce the risk of being hacked by uploading potentially unsafe files;
        // sample strings: aaa, my, etc.
        define('APPEND_STRING', '');
        
        // Need uploads log? Logs would be saved in the MySql database.
        define('DO_LOG', true);
        
        // MySql data (in case you want to save uploads log)
        define('DB_HOST','localhost'); // host, usually localhost
        define('DB_DATABASE','mydb'); // database name
        define('DB_USERNAME','myusername'); // username
        define('DB_PASSWORD','password-here'); // password
        
        /* NOTE: when using log, you have to create mysql table first for this script.
        Copy paste following into your mysql admin tool (like PhpMyAdmin) to create table
        If you are on cPanel, then prefix _uploads_log on line 205 with your username, so it would be like myusername_uploads_log
        
        CREATE TABLE _uploads_log (
          log_id int(11) unsigned NOT NULL auto_increment,
          log_filename varchar(128) default '',
          log_size int(10) default 0,
          log_ip varchar(24) default '',
          log_date timestamp,
          PRIMARY KEY  (log_id),
          KEY (log_filename)
        );
        
        */
        
        ####################################################################
        ###  END OF SETTINGS.   DO NOT CHANGE BELOW
        ####################################################################
        
        // Allow script to work long enough to upload big files (in seconds, 2 days by default)
        @set_time_limit(172800);
        
        // following may need to be uncommented in case of problems
        // ini_set("session.gc_maxlifetime","10800");
        
        function showUploadForm($message='') {
          $max_file_size_tag = '';
          if (MAX_FILE_SIZE > 0) {
            // convert to bytes
            $max_file_size_tag = "<input name='MAX_FILE_SIZE' value='".(MAX_FILE_SIZE*1024)."' type='hidden' >\n";
          }
        
          // Load form template
          include ('file-upload.html');
        }
        
        // errors list
        $errors = array();
        
        $message = '';
        
        // we should not exceed php.ini max file size
        $ini_maxsize = ini_get('upload_max_filesize');
        if (!is_numeric($ini_maxsize)) {
          if (strpos($ini_maxsize, 'M') !== false)
            $ini_maxsize = intval($ini_maxsize)*1024*1024;
          elseif (strpos($ini_maxsize, 'K') !== false)
            $ini_maxsize = intval($ini_maxsize)*1024;
          elseif (strpos($ini_maxsize, 'G') !== false)
            $ini_maxsize = intval($ini_maxsize)*1024*1024*1024;
        }
        if ($ini_maxsize < MAX_FILE_SIZE*1024) {
          $errors[] = "Alert! Maximum upload file size in php.ini (upload_max_filesize) is less than script's MAX_FILE_SIZE";
        }
        
        // show upload form
        if (!isset($_POST['submit'])) {
          showUploadForm(join('',$errors));
        }
        
        // process file upload
        else {
          
          while(true) {
        
            // make sure destination folder exists
            if (!@file_exists(DESTINATION_FOLDER)) {
              $errors[] = "Destination folder does not exist or no permissions to see it.";
              break;
            }
        
            // check for upload errors
            $error_code = $_FILES['filename']['error'];
            if ($error_code != UPLOAD_ERR_OK) {
              switch($error_code) {
                case UPLOAD_ERR_INI_SIZE: 
                  // uploaded file exceeds the upload_max_filesize directive in php.ini
                  $errors[] = "File is too big (1).";
                  break;
                case UPLOAD_ERR_FORM_SIZE: 
                  // uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form
                  $errors[] = "File is too big (2).";
                  break;
                case UPLOAD_ERR_PARTIAL:
                  // uploaded file was only partially uploaded.
                  $errors[] = "Could not upload file (1).";
                  break;
                case UPLOAD_ERR_NO_FILE:
                  // No file was uploaded
                  $errors[] = "Could not upload file (2).";
                  break;
                case UPLOAD_ERR_NO_TMP_DIR:
                  // Missing a temporary folder
                  $errors[] = "Could not upload file (3).";
                  break;
                case UPLOAD_ERR_CANT_WRITE:
                  // Failed to write file to disk
                  $errors[] = "Could not upload file (4).";
                  break;
                case 8:
                  // File upload stopped by extension
                  $errors[] = "Could not upload file (5).";
                  break;
              } // switch
        
              // leave the while loop
              break;
            }
        
            // get file name (not including path)
            $filename = @basename($_FILES['filename']['name']);
        
            // filename of temp uploaded file
            $tmp_filename = $_FILES['filename']['tmp_name'];
        
            $file_ext = @strtolower(@strrchr($filename,"."));
            if (@strpos($file_ext,'.') === false) { // no dot? strange
              $errors[] = "Suspicious file name or could not determine file extension.";
              break;
            }
            $file_ext = @substr($file_ext, 1); // remove dot
        
            // check file type if needed
            if (count($exts)) {   /// some day maybe check also $_FILES['user_file']['type']
              if (!@in_array($file_ext, $exts)) {
                $errors[] = "Files of this type are not allowed for upload.";
                break;
              }
            }
        
            // destination filename, rename if set to
            $dest_filename = $filename;
            if (RENAME_FILE) {
              $dest_filename = md5(uniqid(rand(), true)) . '.' . $file_ext;
            }
            // append predefined string for safety
            $dest_filename = $dest_filename . APPEND_STRING;
        
            // get size
            $filesize = intval($_FILES["filename"]["size"]); // filesize($tmp_filename);
        
            // make sure file size is ok
            if (MAX_FILE_SIZE > 0 && MAX_FILE_SIZE*1024 < $filesize) {
              $errors[] = "File is too big (3).";
              break;
            }
        
            if (!@move_uploaded_file($tmp_filename , DESTINATION_FOLDER . $dest_filename)) {
              $errors[] = "Could not upload file (6).";
              break;
            }
        
            if (DO_LOG) {
              // Establish DB connection
              $link = @mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD);
              if (!$link) {
                $errors[] = "Could not connect to mysql.";
                break;
              }
              $res = @mysql_select_db(DB_DATABASE, $link);
              if (!$res) {
                $errors[] = "Could not select database.";
                break;
              }
              $m_ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
              $m_size = $filesize;
              $m_fname = mysql_real_escape_string($dest_filename);
              $sql = "insert into _uploads_log (log_filename,log_size,log_ip) values ('$m_fname','$m_size','$m_ip')";
              $res = @mysql_query($sql);
              if (!$res) {
                $errors[] = "Could not run query.";
                break;
              }
              @mysql_free_result($res);
              @mysql_close($link);
            } // if (DO_LOG)
        
        
            // redirect to upload success url
            header('Location: ' . SUCCESS_URL);
            die();
        
            break;
        
          } // while(true)
        
          // Errors. Show upload form.
          $message = join('',$errors);
          showUploadForm($message);
        
        }
        
        ?>


     

    I know I should change the lines




           // destination filename, rename if set to
            $dest_filename = $filename;
            if (RENAME_FILE) {
              $dest_filename = md5(uniqid(rand(), true)) . '.' . $file_ext;


     

    and

     

     

     

     


       if (!@move_uploaded_file($tmp_filename , DESTINATION_FOLDER . $dest_filename)) {
              $errors[] = "Could not upload file (6).";
              break;

     

    Im not sure how to implement the changes to select from database and to implement it into here

     

    and I heard the while(true) is wrong how should it be like then?

  13. Ok I made the switch to Mysql upload form

    <?php
    include('config.php');
    if (!isset($_FILES['image']['tmp_name'])) {
    	echo "";
    	}else{
    	$file=$_FILES['image']['tmp_name'];
    	$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
    	$image_name= addslashes($_FILES['image']['name']);
    			
    			move_uploaded_file($_FILES["image"]["tmp_name"],"photos/" . $_FILES["image"]["name"]);
    			
    			$location="photos/" . $_FILES["image"]["name"];
    			$caption=$_POST['caption'];
    			
    			$save=mysql_query("INSERT INTO photos (location, caption) VALUES ('$location','$caption')");
    			header("location: index.php");
    			exit();					
    	}
    ?>
    
    

    My SQL looks like

     

    CREATE TABLE IF NOT EXISTS `photos` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `location` varchar(100) NOT NULL,
      `caption` varchar(100) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
    

    So ID must be the field I should rename my photo upload to... so how would I change the line... And another question is the caption and location option can be removed from the database since it will be unnecessary 

  14. I'm not talking about a multi-user upload. You have the exact same problem if you upload multiple files, use tabbed browsing or whatever. Any situation which results in two uploads in quick succession can break your system.

     

    The belief that private applications don't need any security is also somewhat problematic. First of all, who says the application is actually private? Is it online? Are you sure that your authentication layer is absolutely perfect? Secondly, a lot of the things which people call “security” is much more than that. It's about making sure that the application works correctly under all circumstances. This is needed in any case, regardless of whether the application is used by you, your friends or the whole world.

     

    So we have no database and no ambition? Then I'd use a synchronized counter:

    <?php
    
    ini_set('display_errors', 1);
    
    $filename = null;
    
    $counter_path = '/path/to/counter';
    $counter_fp = fopen($counter_path, 'r+');
    if ($counter_fp)
    {
    	if (flock($counter_fp, LOCK_EX))
    	{
                    // read current value
    		$current_index = fread($counter_fp, filesize($counter_path));
    
                    // increment counter
    		ftruncate($counter_fp, 0);
    		rewind($counter_fp);
    		if (fwrite($counter_fp, $current_index + 1))
    		{
    			$filename = $current_index;
    		}
    		else
    		{
    			trigger_error('Failed to increment counter.');
    		}
    
    		flock($counter_fp, LOCK_UN);
    	}
    	else
    	{
    		trigger_error('Failed to lock counter file.');
    	}
    
    	fclose($counter_fp);
    }
    else
    {
    	trigger_error('Failed to open counter file.');
    }
    
    if ($filename)
    {
    	// now we can use the counter value
    }
    

    Like I said, it's a PITA. And if anything goes wrong when the counter is incremented, we lose the value entirely.

    Ok as you said above this could cause bigger trouble for me in the future... Would you guys recommend me to use a upload script that is connected via MySQL? If so where can I find a good example... I'm a rookie at this, but im trying my best to solve the problem.

     

    The main use for it is the following:

    1. Upload .jpg images to specific directory - Mustn't create thumbs etc... in the same folder
    2. Max file size limit 150kb.
    3. Must auto increase number as file name.

    The only reason I used the above script were because its the only good example I could find and is very simple to setup.

  15. Yes, but he said for his own use so it didn't sound like that would be an issue. I have an invoicing app that I created that runs on my local machine and I am the only one who accesses it. If I was coding it for multiuser use I would have coded it differently than I did. There is 0 security in it as I'm the only one who uses it. I do agree with your points.

    Any Example's to point me in the right direction?

  16. The reason I want it to use numbers is because I use a gallery script that show the images in descending order. So every time I upload a picture I want it be to be the latest shown image on my gallery... And doing it manually takes a lot of time...

  17.  

    We've already discussed this problem dozens of times, the last thread is just a few items below yours.

     

    I generally recommend random filenames, because they're foolproof and don't expose the upload behaviour of your users. However, if you insist on numbering the files, you should use an AUTO_INCREMENT column in your database. You'll have to store the original filename, anyway. So insert the metadata of the file into your database, retrieve the ID of the inserted row and use that as the filename.

     

    Besides this, your code has some major security issues. You check the MIME type in the $_FILES array, but this information comes from the user and can be anything they want. For example, I could upload a malicious PHP script, declare it as a JPEG image, and you would happily accept it.

     

    Checking the file type actually doesn't protect you at all, because even a perfectly valid image may very well contain malicious code. What matters is how the file is interpreted. As long as your webserver treats the file as an image, you're safe, no matter what the actual file content is. However, if that same file is treated as a script (due to a “.php” extension, for example), it may suddenly turn into malware and attack your server. So that's what you need to worry about.

    • Never accept the user-provided file extension. Always set the extension yourself.
    • Make sure there's only one extension.
    • Turn off script execution in the upload folder.

     

    I'm aware of the security problems, i've buried this this for deep in subfolders and is for my own use. Im not using any database... Is there maybe a way to do it without a database present?

  18. Hi Is there a way I can change my script to auto name the file when its being stored? Maybe by numbers lets say each time I upload a picture it should rename it to the number after the previous number.

     

    like example"

    Upload 1: 1.jpg

    Upload 2: 2.jpg etc..

     

    My current code I have is as follow

     

    Form.html

     

    <html>
    <body><br>
    <h1>My upload file form.</h1>
    
    
    <form enctype="multipart/form-data" action="process.php" method="post">
    
    
    Enter File Name:<input type="text" name="name" value="Please enter file name:" /><br>
    
    
    Enter Description:<input type="text" name="desc" value="Description:" /><br>
    
    
    Select image:<input type="file" name="prodImg"><br>
    
    
    <input type="submit" value="Submit Page" />
    
    
    </form>
    <?php
    
    
    
    
    
    
    include "menu3.php";
    
    
    ?>
    
    
    </body>
    </html>

    And my processing script

     

    process.php

     

    <?php
    
    
    extract($_POST);
    
    
    $name;
    
    
    $desc;
    
    
    $fileType = $_FILES['prodImg']['type'];
     $fileSize = $_FILES['prodImg']['size'];
    
    
    if($fileSize/1024 > '150') {
     echo 'Filesize is not correct it should equal to 2 MB or less than 2 MB.';
     exit();
     } //FileSize Checking
    
    
    if($fileType != 'image/gif' &&
     $fileType != 'image/jpg' &&
     $fileType != 'image/jpeg' 
    
    
     )     {
     echo 'Sorry this file type is not supported we accept only. Jpeg, Gif, PNG, or ';
     exit();
     } //file type checking ends here.
     $upFile = 'files/galaxywars/'.date('Y_m_d_H_i_s').$_FILES['prodImg']['name'];
    
    
    if(is_uploaded_file($_FILES['prodImg']['tmp_name'])) {
     if(!move_uploaded_file($_FILES['prodImg']['tmp_name'], $upFile)) {
     echo 'Problem could not move file to destination. Please check again later. <a href="index.php">Please go back.</a>';
     exit;
     }
     } else {
     echo 'Problem: Possible file upload attack. Filename: ';
     echo $_FILES['prodImg']['name'];
     exit;
     }
     $prodImg = $upFile;
      //File upload ends here.
    
    
    $upFile;
    echo "Thank you for sending your file";
    
    
     ?>
    <?php
    
    
    
    
    
    
    include "menu3.php";
    
    
    ?>
    

    Can anyone assist me with this problem please?

     

  19. Hello cobusbo! Did you write the script you posted or did you find it somewhere? What you should do is to create a couple of files in a directory and just create small, standalone PHP file. In this file, try to list all the name of the files in this directory. Then, try to do it by date. You should be able to do it with what Ch0cu3r said. 

     

    Tell me if you're able to do that or not. :)

    Hi I found it http://www.lateralcode.com/simple-php-gallery-pagination/

     

    I made a few changes to display names etc... already the only thing that is keeping me back from publishing is the sort function. The reason I chosen this file is because it plain and simple, and I don't want to add any fancy styles etc.. and Im planning on launching it via a mobi portal on an IM called "mxit" so I need to keep everything simple since not all functions are supported.

    I tried adding the above code into my original code. but it didn't work. I'm a beginner coder and most of the things are totally new for me. By looking at the PHP manual they show you the functions but not good examples.

  20. Hi I have the following script to show images from a directory and make thumbs , but I would like to know how to sort the images from newest to oldest and how to implement it in this script

    I'm a rookie at this...

    Many Thanks in Advance!

    <?php
        # SETTINGS
        $max_width = 800;
        $max_height = 600;
        $per_page = 10;
    
        $page = $_GET['page'];
    
        $has_previous = false;
        $has_next = false;
    
        function getPictures() {
            global $page, $per_page, $has_previous, $has_next;
            if ( $handle = opendir(".") ) {
                $lightbox = rand();
                echo '<ul id="pictures">';
    
                $count = 0;
                $skip = $page * $per_page;
    
                if ( $skip != 0 )
                    $has_previous = true;
    
                while ( $count < $skip && ($file = readdir($handle)) !== false ) {
                    if ( !is_dir($file) && ($type = getPictureType($file)) != '' )
                        $count++;
                }
                $count = 0;
                while ( $count < $per_page && ($file = readdir($handle)) !== false ) {
        if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
    
            // make the thumbs directory if it doesn't already exist
            if ( ! is_dir('thumbs') ) {
                mkdir('thumbs');
            }
            // make a thumbnail if it doesn't already exist
            if ( ! file_exists('thumbs/'.$file) ) {
                makeThumb( $file, $type );
            }
    
            // create a link to $file, add the thumbnail
            echo '<li><a href="' . $file . '">';
            echo '<img src="thumbs/'.$file.'" alt="" /></a></li>';
            $count++;
    echo substr($file,strlen($folder),strpos($file, '.')-strlen($folder));
    
        }
    }
    
                echo '</ul>';
    
                while ( ($file = readdir($handle)) !== false ) {
                    if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
                        $has_next = true;
                        break;
                    }
                }
            }
        }
    
        function getPictureType($file) {
            $split = explode('.', $file); 
            $ext = $split[count($split) - 1];
            if ( preg_match('/jpg|jpeg/i', $ext) ) {
                return 'jpg';
            } else if ( preg_match('/png/i', $ext) ) {
                return 'png';
            } else if ( preg_match('/gif/i', $ext) ) {
                return 'gif';
            } else {
                return '';
            }
        }
    
        function makeThumb( $file, $type ) {
            global $max_width, $max_height;
            if ( $type == 'jpg' ) {
                $src = imagecreatefromjpeg($file);
            } else if ( $type == 'png' ) {
                $src = imagecreatefrompng($file);
            } else if ( $type == 'gif' ) {
                $src = imagecreatefromgif($file);
            }
            if ( ($oldW = imagesx($src)) < ($oldH = imagesy($src)) ) {
                $newW = $oldW * ($max_width / $oldH);
                $newH = $max_height;
            } else {
                $newW = $max_width;
                $newH = $oldH * ($max_height / $oldW);
            }
            $new = imagecreatetruecolor($newW, $newH);
            imagecopyresampled($new, $src, 0, 0, 0, 0, $newW, $newH, $oldW, $oldH);
            if ( $type == 'jpg' ) {
                imagejpeg($new, 'thumbs/'.$file);
            } else if ( $type == 'png' ) {
                imagepng($new, 'thumbs/'.$file);
            } else if ( $type == 'gif' ) {
                imagegif($new, 'thumbs/'.$file);
            }
            imagedestroy($new);
            imagedestroy($src);
        }
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UFT-8" />
    <title>Pictures</title>
    <link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" />
    <style type="text/css">
    body {
        width:780px;
        margin:0 auto;
    }
    #pictures li {
        float:left;
        height:<?php echo ($max_height + 10); ?>px;
        list-style:none outside;
        width:<?php echo ($max_width + 10); ?>px;
        text-align:center;
    }
    img {
        border:0;
        outline:none;
    }
    .prev {
        float:left;
    }
    .next {
        float:right;
    }
    </style>
    </head>
    <body>
    
    <?php getPictures(); ?>
    
    <div style="clear:both"></div>
    
    <?php
        if ( $has_previous )
            echo '<p class="prev"><a href="?page='.($page - 1).'">← Previous Page</a></p>';
    
        if ( $has_next )
            echo '<p class="next"><a href="?page='.($page + 1).'">Next Page →</a></p>';
    ?>
    
    <div style="clear:both"></div>
    
    <script type="text/javascript" src="js/prototype.js"></script>
    <script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script>
    <script type="text/javascript" src="js/lightbox.js"></script>
    </body>
    </html>
    
  21. Since these are coming from a directory and not the database, I'd suggest using array_chunk(). Here's some pseudocode. Hopefully you can see what's going on.

    //grab the page number from the url, if not set assume it's page 1
    ​$page_number = (isset($_GET['page'])) ? filter_input(INPUT_GET, 'page', FILTER_SANITIZE_NUMBER_INT) : 1;
    $folder = 'img/';
    $filetype = '*.*';
    $files = glob($folder.$filetype);
    
    //you'll need this total to determine how many "page" links to build
    $count = count($files); 
    $per_page = 10; //show 10 images per page
    
     //split up the files array into chunks of 10 (number per_page)
    $files = array_chunk($files, $per_page); 
    
    $files = $files[$page - 1]; //grab the files for this page from the chunked array based on index
    
    //now cycle through $images and display them
    ...
    
    //determine how many pages there will be based on total images and $per_page
    $total_pages = ceil($count / $per_page);
    
    //build your page links based on how many pages there are
    ...

    As far as the "&nbsp", search for it. Its not coming from this code. It is missing the ";" at the end so that's why it's showing up.

    How and where should I implement this snippet? Sorry I'm totally new at this...

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.