Search Results

Search found 106 results on 5 pages for 'htmlspecialchars'.

Page 2/5 | < Previous Page | 1 2 3 4 5  | Next Page >

  • Form Submitting Incorrect Information to MySQL Database

    - by ThatMacLad
    I've created a form that submits data to a MySQL database but the Date, Time, Year and Month fields constantly revert to the exact same date (1st January 1970) despite the fact that when I submit the information to the database the form displays the current date, time etc to me. I've already set it so that the time and date fields automatically display the current time and date. Could someone please help me with this. Form: <html> <head> <title>Blog | New Post</title> <link rel="stylesheet" href="css/newposts.css" type="text/css" /> </head> <body> <div class="new-form"> <div class="header"> <a href="edit.php"><img src="images/edit-home-button.png"></a> </div> <div class="form-bg"> <?php if (isset($_POST['submit'])) { $month = htmlspecialchars(strip_tags($_POST['month'])); $date = htmlspecialchars(strip_tags($_POST['date'])); $year = htmlspecialchars(strip_tags($_POST['year'])); $time = htmlspecialchars(strip_tags($_POST['time'])); $title = htmlspecialchars(strip_tags($_POST['title'])); $entry = $_POST['entry']; $timestamp = strtotime($month . " " . $date . " " . $year . " " . $time); $entry = nl2br($entry); if (!get_magic_quotes_gpc()) { $title = addslashes($title); $entry = addslashes($entry); } mysql_connect ('localhost', 'root', 'root') ; mysql_select_db ('tmlblog'); $sql = "INSERT INTO php_blog (timestamp,title,entry) VALUES ('$timestamp','$title','$entry')"; $result = mysql_query($sql) or print("Can't insert into table php_blog.<br />" . $sql . "<br />" . mysql_error()); if ($result != false) { print "<p class=\"success\">Your entry has successfully been entered into the blog. </p>"; } mysql_close(); } ?> <?php $current_month = date("F"); $current_date = date("d"); $current_year = date("Y"); $current_time = date("H:i"); ?> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <input class="field" type="text" name="date" id="date" size="2" value="<?php echo $current_month; ?>" /> <input class="field" type="text" name="date" id="date" size="2" value="<?php echo $current_date; ?>" /> <input class="field" type="text" name="date" id="date" size="2" value="<?php echo $current_year; ?>" /> <input type="text" name="time" id="time" size="5"value="<?php echo $current_time; ?>" /> <input class="field2" type="text" id="title" value="Title Goes Here." name="title" size="40" /> <textarea class="textarea" cols="80" rows="20" name="entry" id="entry" class="field2"></textarea> <input class="field" type="submit" name="submit" id="submit" value="Submit"> </form> </div> </div> </div> <div class="bottom"></div> </body> </html>

    Read the article

  • jQuery: AJAX call isn't updating page

    - by Cortopasta
    Thought I had a simple AJAX call using $.POST(), but apparently my function isn't firing, and nothing is updating :-/ Here is the call: $(".answerVerse ul li").click(function(){ var rank = $(this).removeClass("star_empty star_full star_highlight").attr("class"); var verse_id = $(this).parent().parent().find(".verseId").html(); var answer_id = $(this).parent().parent().find(".answerId").html(); var place = this; $.post("rank.php", { rank: rank, verse_id: verse_id, answer_id: answer_id },function(data){ $(place).parent().removeClass().addClass(data.newVerseRank); for (i=0;i<=5;i++) { $(".answerVerse ul."+i).each(function(){ $(".answerVerse ul."+i+" li."+i).prevAll().andSelf().removeClass("star_empty").addClass("star_full"); }); } }, "json"); }); And here is the PHP (rank.php) that it calls: require_once("dbcon.php"); $user = new user(); $user->updateVerseRank($_POST['verse_id'], $_POST['rank']); $user->getVerse($_POST['verse_id']); $user->getAnswer($_POST['answer_id']; $arr = array ('newVerseRank'=>htmlspecialchars(round($user->verse[3])),'newVerseVotes'=>htmlspecialchars(round($user->verse[4])),'newAnswerRank'=>htmlspecialchars($user->answer[3])); echo json_encode($arr); Why am I not updating the page? I know it's something dumb I'm doing seeing as how this is my first attempt at AJAX and JSON :-/ Just trying to learn

    Read the article

  • Display two array's in the same table

    - by Naeem Ahmed
    $row = $query->fetchAll(PDO::FETCH_ASSOC); $num_rows = count($row); for ($i = 0; $i < $num_rows; $i++) { $title = htmlspecialchars($row[$i]['title']); $author =htmlspecialchars($row[$i]['author']); $school =htmlspecialchars($row[$i]['school']); $solution = $row[$i]['solution']; $notes = $row[$i]['notes']; $ad = array($title, $price, $author, $school, $contact, $content, $date); $inlcude = array($solutions, $notes); $field = 0; echo "<table border='1'>"; // foreach($inlcude as $in) This failled miserably foreach ($ad as $post) { if ($field < 3) //The first three values are placed in the first row { echo "<td>$post</td>"; } if ($field >= 3) { echo "<tr><td>$post</td><td>$in</td></tr>"; } $field++; } echo '</table>'; } I have two arrays and I would like to display them in different columns in my table. $ad displays perfectly fine but I'm having trouble displaying the contents in $inlcude in the second column. I've tried putting another foreach loop to iterate through contents of the second array but that really screws up my table by placing random values in different places on the table. Besides the foreach loop, I don't know of any other way to iterate through the array. Any suggestions would be appreciated.Thanks!

    Read the article

  • Increasing understanding of validating a string with PHP string functions

    - by user1554264
    I've just started attempts to validate data in PHP and I'm trying to understand this concept better. I was expecting the string passed as an argument to the $data parameter for the test_input() function to be formatted by the following PHP functions. trim() to remove white space from the end of the string stripslashes() to return a string with backslashes stripped off htmlspecialchars() to convert special characters to HTML entities The issue is that the string that I am echoing at the end of the function is not being formatted in the way I desire at all. In fact it looks exactly the same when I run this code on my server - no white space removed, the backslash is not stripped and no special characters converted to HTML entities. My question is have I gone about this in the wrong approach? Should I be creating the variable called $santised_input on 3 separate lines with each of the functions trim(), stripslashes() and htmlspecialchars()? By my understanding surely I am overwriting the value of the $santised_input variable each time I recreate it on a new line of code. Therefore the trim() and stripslashes() string functions will never be executed. What I am trying to achieve is using the "$santised_input" variable to run all of these PHP string functions when the $data argument is passed to my test_input() function. In other words can these string functions be chained together so that I only need to create $santised_input once? <?php function test_input($data) { $santised_input = trim($data); $santised_input = stripslashes($data); $santised_input = htmlspecialchars($data); echo $santised_input; } test_input("%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E\ "); //Does not output desired result "&quot;&gt;&lt;script&gt;alert('hacked')&lt;/script&gt;" ?>

    Read the article

  • Will these security functions be enough? (PHP)

    - by ggfan
    I am trying to secure my site so I don't have sql injections and xss scripting. Here's my code. //here's the from, for brevity, i just show a field for users to put firstname <form> <label for="first_name" class="styled">First Name:</label> <input type="text" id="first_name" name="first_name" value="<?php if (!empty($first_name)) echo $first_name; ?>" /><br /> //submit button etc </form> if (isset($_POST['submit'])) { //gets rid of extra whitesapce and escapes $first_name = mysqli_real_escape_string($dbc, trim($_POST['first_name'])); //check if $first_name is a string if(!is_string($first_name) { echo "not string"; } //then insert into the database. ....... } mysqli_real_espace_string: I know that this func escapes certain letters like \n \r, so when the data gets inputted into the dbc, it would have '\' next to all the escaped letters? --Will this script be enough to prevent most sql injections? just escaping and checking if the data is a string. For integers values(like users putting in prices), i just: is_numeric(). --How should I use htmlspecialchars? Should I use it only when echoing and displaying user data? Or should I also use this too when inputting data to a dbc? --When should I use strip_tags() or htmlspecialchars? SOO with all these function... if (isset($_POST['submit'])) { //gets rid of extra whitesapce and escapes $first_name = mysqli_real_escape_string($dbc, trim($_POST['first_name'])); //check if $first_name is a string if(!is_string($first_name) { echo "not string"; } //gets rid of any <,>,& htmlspecialchars($first_name); //strips any tags with the first name strip_tags($first_name) //then insert into the database. ....... } Which funcs should I use for sql injections and which ones should I use for xss?

    Read the article

  • HTML E-Mail as fileattachment

    - by johnny
    I have a Problem with Outlook 2010. I sent an E-Mail with a Contactform with this Code: $message = ' <html> <head> <title>Anfrage ('.$cfg->get('global.page.title').')</title> <style type="text/css"> body { background:#FFFFFF; color:#000000; } #tbl td { background:#F0F0F0; vertical-align:top; } #tbl2 td { background:#E0E0E0; vertical-align:top; } </style> </head> <body> <p>Mail von der Webseite '.$cfg->get('global.page.title').'</p> <table id="tbl"> <tr> <td>Absender</td> <td>'.htmlspecialchars($_POST['name']).' ('.htmlspecialchars(trim($_POST['email'])).')</td> </tr> <tr id="tbl2"> <td>Betreff:</td> <td>'.htmlspecialchars($_POST["topic"]).'</td> </tr> <tr> <td>Nachricht:</td> <td>'.nl2br(htmlspecialchars($_POST["message"])).'</td> </tr> </table> </body> </html>'; $absender = $_POST['name'].' <'.$_POST['email'].'>'; $header = "From: $absender\n"; $header .= "Reply-To: $absender\n"; $header .= "X-Mailer: PHP/" . phpversion(). "\n"; $header .= "X-Sender-IP: " . $_SERVER["REMOTE_ADDR"] . "\n"; $header .= "Content-Type: text/html; Charset=utf-8"; $send_mail = mail($cfg->get('contact.toMailAdress'), "Anfrage (".$cfg->get('global.page.title').")", $message, $header); //$send_mail = mail("[email protected]", "Anfrage (".$cfg->get('global.page.title').")", $message, $header); $_SESSION['kontakt_form_time'] = time(); $tpl->assign("mail_sent", $send_mail); When I sent the email, doesn't shows the message. it generates a File named [NAME].h. The Message is in this File. How can I fix that, that the message shows in the E-Mail. Is this a Problem about the settings in Outlook?

    Read the article

  • NuSOAP PHP Request From XML

    - by Tegan Snyder
    I'm trying to take the following XML request and convert it to a NuSOAP request and I'm having a bit of difficulty. Could anybody chime in? XML Request: <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:dto="http://dto.eai.dnbi.com" xmlns:com="http://com.dnbi.eai.service.AccountSEI"> <soapenv:Header> <dto:AuthenticationDTO> <dto:LOGIN_ID>[email protected]</dto:LOGIN_ID> <dto:LOGIN_PASSWORD>mypassword</dto:LOGIN_PASSWORD> </dto:AuthenticationDTO> </soapenv:Header> <soapenv:Body> <com:matchCompany> <com:in0> <!--Optional:--> <dto:bureauName></dto:bureauName> <!--Optional:--> <dto:businessInformation> <dto:address> <!--Optional:--> <dto:city>Bloomington</dto:city> <dto:country>US</dto:country> <dto:state>MN</dto:state> <dto:street>555 Plain ST</dto:street> <!--Optional:--> <dto:zipCode></dto:zipCode> </dto:address> <!--Optional:--> <dto:businessName>Some Company</dto:businessName> </dto:businessInformation> <!--Optional:--> <dto:entityNumber></dto:entityNumber> <!--Optional:--> <dto:entityType></dto:entityType> <!--Optional:--> <dto:listOfSimilars>true</dto:listOfSimilars> </com:in0> </com:matchCompany> </soapenv:Body> </soapenv:Envelope> And my PHP code: <?php require_once('nusoap.php'); $params = array( 'LOGIN_ID' => '[email protected]', 'LOGIN_PASSWORD' => 'mypassword', 'bureauName' => '', 'businessInformation' => array('address' => array('city' => 'Some City'), array('country' => 'US'), array('state' => 'MN'), array('street' => '555 Plain St.'), array('zipCode' => '32423')), array('businessName' => 'Some Company'), 'entityType' => '', 'listOfSimilars' => 'true', ); $wsdl="http://www.domain.com/ws/AccountManagement.wsdl"; $client = new nusoap_client($wsdl, true); $err = $client->getError(); if ($err) { echo '<h2>Constructor error</h2><pre>' . $err . '</pre>'; echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>'; exit(); } $result = $client->call('matchCompany', $params); if ($client->fault) { echo '<h2>Fault (Expect - The request contains an invalid SOAP body)</h2><pre>'; print_r($result); echo '</pre>'; } else { $err = $client->getError(); if ($err) { echo '<h2>Error</h2><pre>' . $err . '</pre>'; } else { echo '<h2>Result</h2><pre>'; print_r($result); echo '</pre>'; } } echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>'; echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>'; echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>'; ?> Am I generating the Header information correctly? I think that may be where I'm off. Thanks,

    Read the article

  • Newbie's problems with MySQL and php

    - by Mirage81
    I'm a real newbie with php and MySQL. Now I'm working on the following code which should search the database for eg. all the Lennons living in Liverpool. 1) How should I modify "get.php" to get the text "no results" to appear if there are no search results. 2) How should I modify "index.php" to get the option values (city and lastname) straight from the database instead of having to type them one by one? 3) Am I using mysql_real_escape_string the right way? 4) Any other mistakes in the code? index.php: <form action="get.php" method="post"> <p> <select name="city"> <option value="Birmingham">Birmingham</option> <option value="Liverpool">Liverpool</option> <option value="London">London</option> </select> </p> <p> <select name="lastname"> <option value="Lennon">Lennon</option> <option value="McCartney">McCartney</option> <option value="Osbourne">Osbourne</option> </select> </p> <p> <input value="Search" type="submit"> </p> </form> get.php: <?php $city = $_POST['city']; $lastname = $_POST['lastname']; $conn = mysql_connect('localhost', 'user', 'password'); mysql_select_db("database", $conn) or die("connection failed"); $query = "SELECT * FROM users WHERE city = '$city' AND lastname = '$lastname'"; $result = mysql_query($query, $conn); $city = mysql_real_escape_string($_POST['city']); $lastname = mysql_real_escape_string($_POST['lastname']); echo $rowcount; while ($row = mysql_fetch_row($result)) { if ($rowcount == '0') echo 'no results'; else { echo '<b>City: </b>'.htmlspecialchars($row[0]).'<br />'; echo '<b>Last name: </b>'.htmlspecialchars($row[1]).'<br />'; echo '<b>Information: </b>'.htmlspecialchars($row[2]); } } mysql_close($conn);

    Read the article

  • Displaying untrusted HTML using PHP

    - by esryl
    I have a read a number of excellent questions and answers today about dealing with user input. I am now using htmlspecialchars() to display user data in the create/edit forms (but accepting the raw input via prepared PDO statements into my database). The main question I know have is, what do you do when you are allowing the user to submit HTML which will then be displayed to the public. Obviously htmlspecialchars() is no longer suitable as it just encodes the tags and renders the content useless for purpose. My application is currently accepting HTML from an admin for product descriptions. This would allow a malicious admin to inject potentially unsafe data into public facing pages. How do people cope with this?

    Read the article

  • Incorrect string encodings

    - by James
    Note: I have read all of the related PHP, UTF-8, character encoding articles that are usually suggested, but my question relates to data inserted before I applied such techniques. I am wishing to retrospectively fix all character encoding problems. Now all connections are set as utf8 using PDO. PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8' Unfortunately, a large amount of data was inserted that is of questionable encoding before I had implemented correct character encoding practices. As displayed by: $sql = "SELECT name FROM data LIMIT 3"; foreach ($pdo->query($sql) as $row) { $name = $row['name']; echo $name . "\n"; echo utf8_encode($name) . "\n"; echo utf8_decode($name) . "\n"; echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . "\n"; echo htmlspecialchars(utf8_encode($name), ENT_QUOTES, 'UTF-8') . "\n"; echo htmlspecialchars(utf8_decode($name), ENT_QUOTES, 'UTF-8') . "\n"; echo '<hr/>'; } Which produces: Antonín Dvořák AntonÃÆín DvoÃâ¦Ãâ¢ÃÆák Anton??­n Dvo??????¡k Antonín Dvořák AntonÃÆín DvoÃâ¦Ãâ¢ÃÆák ---------- Ô±Ö€Õ¡Õ´ Ô½Õ¡Õ¹Õ¡Õ¿Ö€ÕµÕ¡Õ¶ ñÃâ¬Ã¡Ã´ ýáùáÿÃâ¬ÃµÃ¡Ã¶ ????? ?????????? Ô±Ö€Õ¡Õ´ Ô½Õ¡Õ¹Õ¡Õ¿Ö€ÕµÕ¡Õ¶ ñÃâ¬Ã¡Ã´ ýáùáÿÃâ¬ÃµÃ¡Ã¶ ---------- Tiësto Tiësto Tiësto Tiësto Tiësto Tiësto ---------- When removing 'SET NAMES utf8' with PDO it produces the data: Antonín DvoÅák Antonín DvoÃÂák Antonín Dvorák Antonín DvoÅák Antonín DvoÃÂák Antonín Dvorák ---------- ???? ????????? Ô±ÖÕ¡Õ´ Ô½Õ¡Õ¹Õ¡Õ¿ÖÕµÕ¡Õ¶ ???? ????????? ???? ????????? Ô±ÖÕ¡Õ´ Ô½Õ¡Õ¹Õ¡Õ¿ÖÕµÕ¡Õ¶ ???? ????????? ---------- Tiësto Tiësto Ti?sto Tiësto Tiësto ---------- And here is a dump of the database rows concerned: DROP TABLE IF EXISTS `data`; CREATE TABLE IF NOT EXISTS `data` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(80) NOT NULL, PRIMARY KEY (`id`), KEY `name` (`name`(10)), ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0; INSERT INTO `data` (`id`, `name`) VALUES (0, 'Antonín Dvořák'), (1, 'Ô±Ö€Õ¡Õ´ Ô½Õ¡Õ¹Õ¡Õ¿Ö€ÕµÕ¡Õ¶'), (2, 'Tiësto'); The 3rd and 6th lines of the 3rd row "Tiësto" are then correctly echoed. I'm just unsure what is the best way to correct encodings/detect the encodings of bad strings and correct, etc.

    Read the article

  • How should I handle the case in which a username is already in use?

    - by idealmachine
    I'm a JavaScript programmer and new to PHP and MySQL (want to get into server-side coding). Because I'm trying to learn PHP by building a simple online game (more specifically, correspondence chess), I'm starting by implementing a simple user accounts system. Of course, user registration comes first. What are the best practices for: How I should handle the (likely) possibility that when a user tries to register, the username he has chosen is already in use, particularly when it comes to function return values?($result === true is rather ugly, and I'm not sure whether checking the MySQL error code is the best way to do it either) How to cleanly handle varying page titles?($gPageTitle = '...'; require_once 'bgsheader.php'; is also rather ugly) Anything else I'm doing wrong? In some ways, PHP is rather different from JavaScript... Here is a (rather large) excerpt of the code I have written so far. Note that this is a work in progress and is missing security checks that I will add as my next step. function addUser( $username, $password ) { global $gDB, $gPasswordSalt; $stmt = $gDB->prepare( 'INSERT INTO user(user_name, user_password, user_registration) VALUES(?, ?, NOW())' ); $stmt || trigger_error( 'Failed to prepare statement: ' . htmlspecialchars( $gDB->error ) ); $hashedPassword = hash_hmac( 'sha256', $password, $gPasswordSalt, true ); $stmt->bind_param( 'ss', $username, $hashedPassword ); if( $stmt->execute() ) { return true; } elseif( $stmt->errno == 1062) { return 'exists'; } else { trigger_error( 'Failed to execute statement: ' . htmlspecialchars( $stmt->error ) ); } } $username = $_REQUEST['username']; $password = $_REQUEST['password']; $result = addUser( $username, $password ); if( $result === true ) { $gPageTitle = 'Registration successful'; require_once 'bgsheader.php'; echo '<p>You have successfully registered as ' . htmlspecialchars( $username ) . ' on this site.</p>'; } elseif( $result == 'exists' ) { $gPageTitle = 'Username already taken'; require_once 'bgsheader.php'; echo '<p>Someone is already using the username you have chosen. Please try using another one instead.'; } else { trigger_error('This should never happen'); } require_once 'bgsfooter.php';

    Read the article

  • How to select all options from a drop list in php / mysql

    - by Mirage81
    Thanks to stackoverflow.com's frienly experts I've managed to create my first php + mysql application. The code searches a mysql database for last names and cities. The choices are made through two drop lists like these: Choose city: All cities Liverpool Manchester Choose last name: All last names Lennon Gallagher The code would return eg. all the Lennons living in Liverpool. However, I haven't been able to make the options "All cities" and "All last names" to work so that the code would return eg. all the Lennons living in any city or all the people living in Liverpool. So, how can that be done? The code so far: index.php <?php $conn = mysql_connect('localhost', 'user', 'password') or die("Connection failed"); mysql_select_db("database", $conn) or die("Switch database failed"); //this gets the cities from the database to the drop list $query = "SELECT DISTINCT city FROM user".mysql_real_escape_string($city); $result = mysql_query($query, $conn); $options=""; while ($row=mysql_fetch_array($result)) { $city=$row["city"]; $options.="<OPTION VALUE=\"$city\">".$city; } //this gets the last names from the database to the drop list $query2 = "SELECT DISTINCT lastname FROM user".mysql_real_escape_string($lastname); $result2 = mysql_query($query2, $conn); $options2=""; while ($row2=mysql_fetch_array($result2)) { $lastname=$row2["lastname"]; $options2.="<OPTION VALUE=\"$lastname\">".$lastname; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"> <title>test</title> </head> <body> <form action="get.php" method="post"> <p> <select name="city"> <option value=0>Choose <option value=1>All cities <?=$options?> </select> </p> <p> <select name="lastname"> <option value=0>Choose <option value=1>All last names <?=$options2?> </select> </p> <p> <input value="Search" type="submit"> </p> </form> <br> </body> </html> get.php <?php $conn = mysql_connect('localhost', 'user', 'password') or die("Connection failed"); mysql_select_db("database", $conn) or die("Switch database failed"); $query = "SELECT * FROM user WHERE city = '".mysql_real_escape_string($_POST['city'])."' AND lastname = '".mysql_real_escape_string($_POST['lastname'])."'"; $result = mysql_query($query, $conn); echo $rowcount; $zerorows=true; while ($row = mysql_fetch_assoc($result)) { $zerorows=false; echo '<b>City: </b>'.htmlspecialchars($row[city]).'<br />'; echo '<b>Last name: </b>'.htmlspecialchars($row[lastname]).'<br />'; echo '<b>Information: </b>'.htmlspecialchars($row[information]).'<br />'.'<br />'; } if($zerorows) echo "No results"; mysql_close($conn); ?>

    Read the article

  • Help Optimizing MySQL Table (~ 500,000 records) and PHP Code.

    - by Pyrite
    I have a MySQL table that collects player data from various game servers (Urban Terror). The bot that collects the data runs 24/7, and currently the table is up to about 475,000+ records. Because of this, querying this table from PHP has become quite slow. I wonder what I can do on the database side of things to make it as optomized as possible, then I can focus on the application to query the database. The table is as follows: CREATE TABLE IF NOT EXISTS `people` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(40) NOT NULL, `ip` int(4) unsigned NOT NULL, `guid` varchar(32) NOT NULL, `server` int(4) unsigned NOT NULL, `date` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `Person` (`name`,`ip`,`guid`), KEY `server` (`server`), KEY `date` (`date`), KEY `PlayerName` (`name`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COMMENT='People that Play on Servers' AUTO_INCREMENT=475843 ; I'm storying the IPv4 (ip and server) as 4 byte integers, and using the MySQL functions NTOA(), etc to encode and decode, I heard that this way is faster, rather than varchar(15). The guid is a md5sum, 32 char hex. Date is stored as unix timestamp. I have a unique key on name, ip and guid, as to avoid duplicates of the same player. Do I have my keys setup right? Is the way I'm storing data efficient? Here is the code to query this table. You search for a name, ip, or guid, and it grabs the results of the query and cross references other records that match the name, ip, or guid from the results of the first query, and does it for each field. This is kind of hard to explain. But basically, if I search for one player by name, I'll see every other name he has used, every IP he has used and every GUID he has used. <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> Search: <input type="text" name="query" id="query" /><input type="submit" name="btnSubmit" value="Submit" /> </form> <?php if (!empty($_POST['query'])) { ?> <table cellspacing="1" id="1up_people" class="tablesorter" width="300"> <thead> <tr> <th>ID</th> <th>Player Name</th> <th>Player IP</th> <th>Player GUID</th> <th>Server</th> <th>Date</th> </tr> </thead> <tbody> <?php function super_unique($array) { $result = array_map("unserialize", array_unique(array_map("serialize", $array))); foreach ($result as $key => $value) { if ( is_array($value) ) { $result[$key] = super_unique($value); } } return $result; } if (!empty($_POST['query'])) { $query = trim($_POST['query']); $count = 0; $people = array(); $link = mysql_connect('localhost', 'mysqluser', 'yea right!'); if (!$link) { die('Could not connect: ' . mysql_error()); } mysql_select_db("1up"); $sql = "SELECT id, name, INET_NTOA(ip) AS ip, guid, INET_NTOA(server) AS server, date FROM 1up_people WHERE (name LIKE \"%$query%\" OR INET_NTOA(ip) LIKE \"%$query%\" OR guid LIKE \"%$query%\")"; $result = mysql_query($sql, $link); if (!$result) { die(mysql_error()); } // Now take the initial results and parse each column into its own array while ($row = mysql_fetch_array($result, MYSQL_NUM)) { $name = htmlspecialchars($row[1]); $people[] = array( 'id' => $row[0], 'name' => $name, 'ip' => $row[2], 'guid' => $row[3], 'server' => $row[4], 'date' => $row[5] ); } // now for each name, ip, guid in results, find additonal records $people2 = array(); foreach ($people AS $person) { $ip = $person['ip']; $sql = "SELECT id, name, INET_NTOA(ip) AS ip, guid, INET_NTOA(server) AS server, date FROM 1up_people WHERE (ip = \"$ip\")"; $result = mysql_query($sql, $link); while ($row = mysql_fetch_array($result, MYSQL_NUM)) { $name = htmlspecialchars($row[1]); $people2[] = array( 'id' => $row[0], 'name' => $name, 'ip' => $row[2], 'guid' => $row[3], 'server' => $row[4], 'date' => $row[5] ); } } $people3 = array(); foreach ($people AS $person) { $guid = $person['guid']; $sql = "SELECT id, name, INET_NTOA(ip) AS ip, guid, INET_NTOA(server) AS server, date FROM 1up_people WHERE (guid = \"$guid\")"; $result = mysql_query($sql, $link); while ($row = mysql_fetch_array($result, MYSQL_NUM)) { $name = htmlspecialchars($row[1]); $people3[] = array( 'id' => $row[0], 'name' => $name, 'ip' => $row[2], 'guid' => $row[3], 'server' => $row[4], 'date' => $row[5] ); } } $people4 = array(); foreach ($people AS $person) { $name = $person['name']; $sql = "SELECT id, name, INET_NTOA(ip) AS ip, guid, INET_NTOA(server) AS server, date FROM 1up_people WHERE (name = \"$name\")"; $result = mysql_query($sql, $link); while ($row = mysql_fetch_array($result, MYSQL_NUM)) { $name = htmlspecialchars($row[1]); $people4[] = array( 'id' => $row[0], 'name' => $name, 'ip' => $row[2], 'guid' => $row[3], 'server' => $row[4], 'date' => $row[5] ); } } // Combine people and people2 into just people $people = array_merge($people, $people2); $people = array_merge($people, $people3); $people = array_merge($people, $people4); $people = super_unique($people); foreach ($people AS $person) { $date = ($person['date']) ? date("M d, Y", $person['date']) : 'Before 8/1/10'; echo "<tr>\n"; echo "<td>".$person['id']."</td>"; echo "<td>".$person['name']."</td>"; echo "<td>".$person['ip']."</td>"; echo "<td>".$person['guid']."</td>"; echo "<td>".$person['server']."</td>"; echo "<td>".$date."</td>"; echo "</tr>\n"; $count++; } // Find Total Records //$result = mysql_query("SELECT id FROM 1up_people", $link); //$total = mysql_num_rows($result); mysql_close($link); } ?> </tbody> </table> <p> <?php echo $count." Records Found for \"".$_POST['query']."\" out of $total"; ?> </p> <?php } $time_stop = microtime(true); print("Done (ran for ".round($time_stop-$time_start)." seconds)."); ?> Any help at all is appreciated! Thank you.

    Read the article

  • Wrong logic in If Statement?

    - by Charles
    $repeat_times = mysql_real_escape_string($repeat_times); $result = mysql_query("SELECT `code`,`datetime` FROM `fc` ORDER by datetime desc LIMIT 25") or die(mysql_error()); $output .=""; $seconds = time() - strtotime($fetch_array["datetime"]); if($seconds < 60) $interval = "$seconds seconds"; else if($seconds < 3600) $interval = floor($seconds / 60) . " minutes"; else if($seconds < 86400) $interval = floor($seconds / 3600) . " hours"; else $interval = floor($seconds / 86400) . " days"; while ($fetch_array = mysql_fetch_array($result)) { $fetch_array["code"] = htmlentities($fetch_array["code"]); $output .= "<li><a href=\"http://www.***.com/code=" . htmlspecialchars(urlencode($fetch_array["code"])) . "\" target=\"_blank\">" . htmlspecialchars($fetch_array["code"]) . "</a> (" . $interval . ") ago.</li>"; } $output .=""; return $output; Why is this returning janice (14461 days) instead of janice (15 minutes ago) The datetime function table has the DATETIME type in my table so it's returning a full string for the date.

    Read the article

  • Help Optimizing MySQL Table (~ 500,000 records).

    - by Pyrite
    I have a MySQL table that collects player data from various game servers (Urban Terror). The bot that collects the data runs 24/7, and currently the table is up to about 475,000+ records. Because of this, querying this table from PHP has become quite slow. I wonder what I can do on the database side of things to make it as optomized as possible, then I can focus on the application to query the database. The table is as follows: CREATE TABLE IF NOT EXISTS `people` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(40) NOT NULL, `ip` int(4) unsigned NOT NULL, `guid` varchar(32) NOT NULL, `server` int(4) unsigned NOT NULL, `date` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `Person` (`name`,`ip`,`guid`), KEY `server` (`server`), KEY `date` (`date`), KEY `PlayerName` (`name`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COMMENT='People that Play on Servers' AUTO_INCREMENT=475843 ; I'm storying the IPv4 (ip and server) as 4 byte integers, and using the MySQL functions NTOA(), etc to encode and decode, I heard that this way is faster, rather than varchar(15). The guid is a md5sum, 32 char hex. Date is stored as unix timestamp. I have a unique key on name, ip and guid, as to avoid duplicates of the same player. Do I have my keys setup right? Is the way I'm storing data efficient? Here is the code to query this table. You search for a name, ip, or guid, and it grabs the results of the query and cross references other records that match the name, ip, or guid from the results of the first query, and does it for each field. This is kind of hard to explain. But basically, if I search for one player by name, I'll see every other name he has used, every IP he has used and every GUID he has used. <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> Search: <input type="text" name="query" id="query" /><input type="submit" name="btnSubmit" value="Submit" /> </form> <?php if (!empty($_POST['query'])) { ?> <table cellspacing="1" id="1up_people" class="tablesorter" width="300"> <thead> <tr> <th>ID</th> <th>Player Name</th> <th>Player IP</th> <th>Player GUID</th> <th>Server</th> <th>Date</th> </tr> </thead> <tbody> <?php function super_unique($array) { $result = array_map("unserialize", array_unique(array_map("serialize", $array))); foreach ($result as $key => $value) { if ( is_array($value) ) { $result[$key] = super_unique($value); } } return $result; } if (!empty($_POST['query'])) { $query = trim($_POST['query']); $count = 0; $people = array(); $link = mysql_connect('localhost', 'mysqluser', 'yea right!'); if (!$link) { die('Could not connect: ' . mysql_error()); } mysql_select_db("1up"); $sql = "SELECT id, name, INET_NTOA(ip) AS ip, guid, INET_NTOA(server) AS server, date FROM 1up_people WHERE (name LIKE \"%$query%\" OR INET_NTOA(ip) LIKE \"%$query%\" OR guid LIKE \"%$query%\")"; $result = mysql_query($sql, $link); if (!$result) { die(mysql_error()); } // Now take the initial results and parse each column into its own array while ($row = mysql_fetch_array($result, MYSQL_NUM)) { $name = htmlspecialchars($row[1]); $people[] = array( 'id' => $row[0], 'name' => $name, 'ip' => $row[2], 'guid' => $row[3], 'server' => $row[4], 'date' => $row[5] ); } // now for each name, ip, guid in results, find additonal records $people2 = array(); foreach ($people AS $person) { $ip = $person['ip']; $sql = "SELECT id, name, INET_NTOA(ip) AS ip, guid, INET_NTOA(server) AS server, date FROM 1up_people WHERE (ip = \"$ip\")"; $result = mysql_query($sql, $link); while ($row = mysql_fetch_array($result, MYSQL_NUM)) { $name = htmlspecialchars($row[1]); $people2[] = array( 'id' => $row[0], 'name' => $name, 'ip' => $row[2], 'guid' => $row[3], 'server' => $row[4], 'date' => $row[5] ); } } $people3 = array(); foreach ($people AS $person) { $guid = $person['guid']; $sql = "SELECT id, name, INET_NTOA(ip) AS ip, guid, INET_NTOA(server) AS server, date FROM 1up_people WHERE (guid = \"$guid\")"; $result = mysql_query($sql, $link); while ($row = mysql_fetch_array($result, MYSQL_NUM)) { $name = htmlspecialchars($row[1]); $people3[] = array( 'id' => $row[0], 'name' => $name, 'ip' => $row[2], 'guid' => $row[3], 'server' => $row[4], 'date' => $row[5] ); } } $people4 = array(); foreach ($people AS $person) { $name = $person['name']; $sql = "SELECT id, name, INET_NTOA(ip) AS ip, guid, INET_NTOA(server) AS server, date FROM 1up_people WHERE (name = \"$name\")"; $result = mysql_query($sql, $link); while ($row = mysql_fetch_array($result, MYSQL_NUM)) { $name = htmlspecialchars($row[1]); $people4[] = array( 'id' => $row[0], 'name' => $name, 'ip' => $row[2], 'guid' => $row[3], 'server' => $row[4], 'date' => $row[5] ); } } // Combine people and people2 into just people $people = array_merge($people, $people2); $people = array_merge($people, $people3); $people = array_merge($people, $people4); $people = super_unique($people); foreach ($people AS $person) { $date = ($person['date']) ? date("M d, Y", $person['date']) : 'Before 8/1/10'; echo "<tr>\n"; echo "<td>".$person['id']."</td>"; echo "<td>".$person['name']."</td>"; echo "<td>".$person['ip']."</td>"; echo "<td>".$person['guid']."</td>"; echo "<td>".$person['server']."</td>"; echo "<td>".$date."</td>"; echo "</tr>\n"; $count++; } // Find Total Records //$result = mysql_query("SELECT id FROM 1up_people", $link); //$total = mysql_num_rows($result); mysql_close($link); } ?> </tbody> </table> <p> <?php echo $count." Records Found for \"".$_POST['query']."\" out of $total"; ?> </p> <?php } $time_stop = microtime(true); print("Done (ran for ".round($time_stop-$time_start)." seconds)."); ?> Any help at all is appreciated! Thank you.

    Read the article

  • Sessions not sticking linux server

    - by Jacob Windsor
    I have just moved the dev site over to my linux server for production but the sessions don't seem to be sticking for very long. I am guessing it is the server settings and not the php because it does the same thing with the plesk panel. Whenever a script is executed the sessions seems to get unset. I see nothing in the error log so not sure what it is. It all worked fine on wamp. Anyway I uploaded the php.ini file which was in the wamp server as it had all the settings i needed and all was working on localhost. Not sure what the problem is and this is the final thing that I have to sort out before going into production. And just too add the sessions are being started as they last for a little bit just don't stick around long. Here is the relevent part of my login script just in case there is something wrong with the code: // if login is ok then we add a cookie if($flag == 0) { $pass = htmlspecialchars(mysql_real_escape_string($_POST['pass'])); $username = htmlspecialchars(mysql_real_escape_string($_POST['username'])); $_SESSION['username']=$username; $_SESSION['password']=$pass;

    Read the article

  • How would I know if my OS is compromised?

    - by itsols
    I had opened a php folder from a friend's web host. I run it on mine to fix some bugs. Then I tried attaching the code to be emailed and GMAIL stated that the attachment was infected by a virus. Now I'm afraid if my Apache or OS (12.04) is infected. I checked the php files and found a base64 encoded set of code being 'eval'd at the top of each and every php file. Just reversing it (echo with htmlspecialchars) showed some clue that there were sockets in use and something to do with permissions. And also there were two websites referred having .ru extensions. Now I'm afraid if my Ubuntu system is affected or compromised. Any advice please! Here's my second run of rkhunter with the options: sudo rkhunter --check --rwo Warning: The command '/usr/bin/unhide.rb' has been replaced by a script: /usr/bin/unhide.rb: Ruby script, ASCII text Warning: Hidden directory found: /dev/.udev Warning: Hidden file found: /dev/.initramfs: symbolic link to `/run/initramfs'

    Read the article

  • Calendar php problem:(

    - by Marin
    Hi everybody! Can you please help me for this problem: It shows me this error in WAMP: Notice: Undefined index: searchstring in C:\wamp\www\Reece Calendar 0.9\includes\search.php on line 180 AND THE LINE IS: <input type=\"text\" name=\"searchstring\" size='70' value='".htmlspecialchars($_POST['searchstring'])."'/> How can I modify it?Please help me!Thnx in advance=)

    Read the article

  • how to write this conditions in php

    - by Mac Taylor
    hey guys , im writing a class and im wondering how i can write a condition statement in this way : $this->referer= (!empty($_SERVER['HTTP_REFERER'])) ? htmlspecialchars((string) $_SERVER['HTTP_REFERER']) : ''; i need to find my user_id and this is the usual condtion : if(is_user($user)){ $cookie=cookiedecode($user); $user_id=intval($cookie[0]); } and i think it should be something like this : $this->user_id = (is_user($user)) ? (cookiedecode($user)) : $cookie[0]; but it didnt work

    Read the article

  • PHP URL Security Question

    - by TaG
    I want to have users store the url in my database I'm using php mysql and htmlpurifier I was wondering if the following code was good way to filter out bad data? Here is the Partial PHP code. $url = mysqli_real_escape_string($mysqli, $purifier->purify(htmlspecialchars(strip_tags($_POST['url'])));

    Read the article

  • How to Convert arrays or SimpleXML-Objects into an XML-String

    - by streetparade
    I want to create a xml from a given string, i have a function but i didn't wrote it.It seems a bit cryptical too. Can please some one review it and give me some Ideas, how it could be written clearer for everybody? /** * Converts arrays or SimpleXML-Objects into an XML-String * @params mixed Accepts an array or xml string with data to Post * @params integer DO NOT PROVIDE. Internal Usage for recursion only */ private function mixedDataToXML($data, $level = 1) { if(!$data){ return FALSE; } if(is_array($data)) { $xml = ''; if ($level==1) { $xml .= '<?xml version="1.0" encoding="ISO-8859-1"?>'."\n"; } foreach ($data as $key => $value) { $key = strtolower($key); if (is_array($value)) { $multi_tags = false; foreach($value as $key2=>$value2) { if (is_array($value2)) { $xml .= str_repeat("\t",$level)."<$key>\n"; $xml .= $this->mixedDataToXML($value2, $level+1); $xml .= str_repeat("\t",$level)."</$key>\n"; $multi_tags = true; } else { if (trim($value2)!='') { if (htmlspecialchars($value2)!=$value2) { $xml .= str_repeat("\t",$level). "<$key><![CDATA[$value2]]>". "</$key>\n"; } else { $xml .= str_repeat("\t",$level). "<$key>$value2</$key>\n"; } } $multi_tags = true; } } if (!$multi_tags and count($value)>0) { $xml .= str_repeat("\t",$level)."<$key>\n"; $xml .= $this->mixedDataToXML($value, $level+1); $xml .= str_repeat("\t",$level)."</$key>\n"; } } else { if (trim($value)!='') { if (htmlspecialchars($value)!=$value) { $xml .= str_repeat("\t",$level)."<$key>". "<![CDATA[$value]]></$key>\n"; } else { $xml .= str_repeat("\t",$level). "<$key>$value</$key>\n"; } } } } return $xml; }else{ return (string)$data; } }

    Read the article

  • Store data in DB as is, or escaped?

    - by Yegor
    Whats a better way to store textual data, such as comments, user profile fields that require them to type something in, etc? Store the escaped data right away (using htmlspecialchars in php for example), or put it thru the same function before its echoed out?

    Read the article

  • Determining when or when not to escape output

    - by Ygam
    I have a page, where I have approximately 90 items I need to output. Most of them are object properties (I am using ORM so these objects map to my database tables). But the question is, do I have to escape each of those 90 outputs by applying functions to each (in my case, the htmlspecialchars)? Wouldn't that add a bit of an overhead (calling a single function 90 times)?

    Read the article

  • PHP - not sure how to ask - regarding variables and $_POST

    - by Phil
    I have a PHP form. The form works but I'm trying to test to see if a value other than the first item has been selected. I can't figure out how to write the If statement. $products = array( '' => 1, 'Item 2' => 2, 'Item 3' => 3, 'Item 4' => 4, 'Item 5' => 5, 'Item 6' => 6 ); $html = generateSelect('products', $products); function generateSelect($name = '', $options = array()) { $html = '<select name="'.$name.'">'; foreach ($options as $option => $value) { $html .= '<option value='.$value.'>'.$option.'</option>'; } $html .= '</select>'; return $html; } In my table, the drop down box is displayed: <tr> <td style="width:{$left_col_width}; text-align:left; vertical-align:center; padding:{$cell_padding}; font-weight:bold; {$product[3]}">{$product[0]}</td> <td style="text-align:left; vertical-align:top; padding:{$cell_padding};"><select name="{$product[1]}"> <option value="1"></option> <option value="2">Item 2</option> <option value="3">Item 3</option> <option value="4">Item 4</option> <option value="5">Item 5</option> <option value="6">Item 6</option> </select></td> </tr> I use the following if statement to check to see if someone has entered a phone number. if they have not entered a phone number, then the "Phone:" text turns red. How do I do an if statement similar to this to verify that someone has selected a product option from the drop down box? if(!empty($_POST['phone'])) { $phone[2] = clean_var($_POST['phone']); if (function_exists('htmlspecialchars')) $phone[2] = htmlspecialchars($phone[2], ENT_QUOTES); } else { $error = 1; $phone[3] = 'color:#d20128;'; } it seems simple but I can't figure it out.

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >