sEnte Posted March 7, 2013 at 05:12 PM Report #498286 Posted March 7, 2013 at 05:12 PM (edited) como podem ver isto pede o username, escrevo o nome e clico enter, ele insere na BD. Depois a parte da mensagem, primeiro deveria aparecer a mensagem No chats found. Be the first e não aparece, e depois mesmo que eu escreva uma mansagem e a envie ela é adicionada à DB mas não me mostra o que inseri index.php <?php session_start(); ?> <!doctype html> <html> <head> <meta charset=utf-8> <title>Ajax Chat</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js%22></script> <style type="text/css"> #chatbox { background-color: #DDD; border: 1px solid #000; width: 600px; height: 300px; } #chatbox #initial { text-align: center; margin: auto; width: 250px; padding-top: 100px; } #chatbox #primary { display: none; } #chatbox #primary #window { width: 100%; height: 265px; background-color: #FFF; border-bottom: 1px solid #AAA; overflow: scroll; } #chatbox #primary #window .list1 { background-color: #EEE; padding: 5px; border-bottom: 1px solid #AAA; } #chatbox #primary #window .list2 { background-color: #DDD; padding: 5px; border-bottom: 1px solid #AAA; } #chatbox #primary #form { width: 100%; } </style> <script type="text/javascript"> var updateTime = 5; var running = false; var counter = 0; function chat_initial() { var user = document.getElementById("chat_user").value; $.post('./chat.php', {stage:"initial", user:user}, function(data) { if (data == "good") { $('#chatbox #initial').css('display', 'none'); $('#chatbox #primary').css('display', 'inline'); } else alert("The username is taken. Please try another!"); }); } function chat_update() { if (counter == updateTime) chat_load(); else counter ++; if (running == true) setTimeout("chat_update();", 1000); } function chat_load() { $('#chatbox #primary #window').html(data); $.post('./chat.php', {stage:"load"}, function(data){ $('#chatbox #primary #window').html(data); counter = 0; setTimeout("chat_update();", 1000*updateTime); }); } function chat_send() { var text = document.getElementById("chat_text").value; $.post('./chat.php', {stage:"send", text:text}, function(data) { document.getElementById("chat_text").value = ''; if (data == "good") { chat_load(); } else alert("No username was found. Please. Please reload the chat window"); }); } </script> </head> <body> <div id="chatbox"> <div id="initial"> <table> <tr align="center"> <td>Enter a username</td> </tr> <tr align="center"> <td><input type="text" name="chat_user" id="chat_user" style="width: 250px;" onkeypress="if(event.keyCode == 13){ chat_initial(); }" /></td> </tr> <tr align="center"> <td><input type="button" value="Continue" onclick="chat_initial();"></td> </tr> </table> </div> <div id="primary"> <div id="window"></div> <div id="form"> <table style="width: 100%;"> <tr> <td width="90%"><input type="text" name="chat_text" id="chat_text" style="width: 100%;" onkeypress="if(event.keyCode == 13){ chat_send(); }" /></td> <td align="center"><input type="button" id="chat_send" value="Chat!" onclick="chat_send();"/></td> </tr> </table> </div> </div> </div> </body> </html> chat.php <?php // session_start(); // Connect to the database mysql_connect('127.0.0.1', 'root', ''); mysql_select_db('tutorials'); // Reads the stage $stage = $_POST['stage']; // primary code if ($stage == "initial") { // check the username $user = $_POST['user']; $query = mysql_query("SELECT * FROM chat_active WHERE user='$user'"); if(mysql_num_rows($query) == 0){ $time = time(); // mysql_query("INSERT INTO chat_active VALUES ('$user', '$time')"); // set the session $_SESSION['user'] = $user; echo 'good'; } else echo 'taken'; } else if ($stage == "send") { // get the text $text = $_POST['text']; // check for a user if (isset($_SESSION['user'])) { $user = $_SESSION['user']; $time = time(); mysql_query("INSERT INTO chat_chats VALUES ('$user', '$time', '$text')"); echo 'good'; } else echo 'no user'; } else if($stage == "load"){ $num = 1; $query = mysql_query("SELECT * FROM chat_chats ORDER BY time DESC"); if (mysql_num_rows($query) > 0) { while ($row = mysql_fetch_assoc($query)) { $user = $row['user']; $time = $row['time']; $content = $row['content']; $content = htmlentities($content); echo '<div class="list'.$num.'">'; echo '<b>'. $user.'</b> at <i>'.date("M d, Y", $time).'</i> - '.$content; echo '</div>'; if ($num = 1) $num = 2; else $num = 1; } } else echo 'No chats found. Be the first'; } else echo 'error'; ?> Por agora parece resolvido reparei que aqui function chat_load() { $('#chatbox #primary #window').html(data); $.post('./chat.php', {stage:"load"}, function(data){ $('#chatbox #primary #window').html(data); counter = 0; setTimeout("chat_update();", 1000*updateTime); }); } tenho parte do código duplicado. Nada como um console.log(data) para me mostrar isso lol Edited March 7, 2013 at 06:34 PM by sEnte "If It Ain't Broke, Break it and build something Cooler!" Unknown
sEnte Posted March 7, 2013 at 07:26 PM Author Report #498323 Posted March 7, 2013 at 07:26 PM Afinal não está resolvido. se por exemplo inserir uma palavra tipo " I'm " ele não é adicionad à bd :S "If It Ain't Broke, Break it and build something Cooler!" Unknown
N3lson Posted March 7, 2013 at 08:29 PM Report #498342 Posted March 7, 2013 at 08:29 PM Vê se isto resolve o teu problema http://php.net/manual/pt_BR/function.addslashes.php You can't do it, kid. But don't worry, my boy. You're not the only one. No one else can do it.
sEnte Posted March 7, 2013 at 10:07 PM Author Report #498394 Posted March 7, 2013 at 10:07 PM sim resolveu. @N3lson Obrigado 🙂 "If It Ain't Broke, Break it and build something Cooler!" Unknown
brunoais Posted March 10, 2013 at 09:41 AM Report #498597 Posted March 10, 2013 at 09:41 AM (edited) Resolveu tão bem que o teu programa ficou muito vulnerável. Só aqui vejo 2 gafes: Usas ainda o grupo de funções mysql_* Não tratas do input do utilizador para ser metido numa DB em segurança. Edited March 10, 2013 at 04:44 PM by brunoais "[Os jovens da actual geração]não lêem porque não envolve um telecomando que dê para mirar e atirar, não falam porque a trapalhice é rainha e o calão é rei" autor: thoga31 Life is a genetically transmitted disease, induced by sex, with death rate of 100%.
sEnte Posted March 10, 2013 at 03:46 PM Author Report #498621 Posted March 10, 2013 at 03:46 PM 1 - O grupo de funções mysql_* é mais vulnerável? Não sabia. Como posso melhorar então? talvez PDO? já segui um tutorial sobre isso mas nada de mais. 2 - realmente não tratei dessa parte. Será o próximo passo quando melhorar. "If It Ain't Broke, Break it and build something Cooler!" Unknown
brunoais Posted March 10, 2013 at 04:53 PM Report #498635 Posted March 10, 2013 at 04:53 PM (edited) 1 - O grupo de funções mysql_* é mais vulnerável? Não sabia. Como posso melhorar então? talvez PDO? já segui um tutorial sobre isso mas nada de mais. A filtragem funciona por um blacklist. Prepared statements é melhor pq qq input é tratado como texto. Podes usar as mysqli_* e prepared statements, não precisa de ser o PDO. 2 - realmente não tratei dessa parte. Será o próximo passo quando melhorar. Pois... É bom que resolvas se queres evitar problemas com segurança. De qq modo, ao nível de segurança: texto simples < addslashes() < mysql_real_escape_string() <(mas pouca diferença) mysqli_real_escape_string() < (significativo) mysqli prepared statements = PDO prepared statements. Edited March 10, 2013 at 07:16 PM by yoda "[Os jovens da actual geração]não lêem porque não envolve um telecomando que dê para mirar e atirar, não falam porque a trapalhice é rainha e o calão é rei" autor: thoga31 Life is a genetically transmitted disease, induced by sex, with death rate of 100%.
ICETuga Posted March 10, 2013 at 07:45 PM Report #498674 Posted March 10, 2013 at 07:45 PM Da minha experiência o PDO para quem está habituado ao mysql pode parecer confuso ao inicio mas depois de habituado, não quererás outra. 😉
sEnte Posted March 10, 2013 at 08:31 PM Author Report #498687 Posted March 10, 2013 at 08:31 PM Nunca usei mysqli mas pelo que vi parece ser algo idêntico ao mysql. não sei, tenho de averiguar. ICETuga o PDO parece algo confuso, mas ao mesmo tempo simples lol "If It Ain't Broke, Break it and build something Cooler!" Unknown
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now