PHP - Filter_var Adds Crap To My String
function Clean_String($string)
{ return strtolower(trim(filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW))); } Ive tracked my issue back to filter_var here. For some reason it is adding stuff to the beginning and end of the string im looking for. It did this on 1 string that I noticed and doesnt do it on any others, which was strange because that string was typical like all others. Just a few sentences and numbers and line breaks. I cant find a reason why this is happening Similar TutorialsI have to make a code that takes X amount of teams and and pairs them each up a given amount of time. No match ups can repeat themselves and they have to be matched up Y amount of times. I've been working on this code since 8:00 last not and I still haven't been able to get it completely working. Now, its stuck in an endless loop in which the match up is being endlessly inserted into the database. Why is this resulting in an endless loop? $started = "false"; $id=$_GET['id']; $gid = $id; //Identify game $sql = "select * from `games` where `id`='$id'"; $result = mysql_query($sql) or die(mysql_error()); while ($row = mysql_fetch_array($result)){ $game = $row['title']; } //$games = $_POST['games']; //START Grab Game //Find Team $a=0; $sql5 = "select * from `leagues` where `game`='$game'"; $result5 = mysql_query($sql5) or die(mysql_error()); while ($row5 = mysql_fetch_array($result5)){ $division = $row5['name']; $sql6 = "select * from `conferences` where `game`='$game' and `division`='$division'"; $result6 = mysql_query($sql6) or die(mysql_error()); while ($row6 = mysql_fetch_array($result6)){ $conference = $row6['title']; $sql = "select * from `teams` where `game`='$game' and `league`='$division' and `conference`='$conference'"; $result = mysql_query($sql) or die(mysql_error()); while ($row = mysql_fetch_array($result)){ $a += 1; $teamId = $row['id']; $team = $row['name']; $teamsIndex["$a"] = $team; $division = $row['league']; $conference = $row['conference']; } //Each Team is stored in an index $b = 0; while ($b<$a){ $b+=1; $teams["$b"]=$b; } $cWeek = 1; $weeks = $_POST['weeks']; //So we have 15 teams. Cycle each team and make matchups while($cWeek<=$weeks){ echo "<br><br><b>Week $cWeek</b><hr>"; $b = 1; $rows = -1; echo "<br>Rows redeclared"; while ($b<=$a){ $bold = $b; echo "<br>DEBUG: $b/$a"; $end = "false"; $stopper = 0; while ($end!="true"){ echo "<br><i>End: $end</i>"; $team1 = $b; $redo="false"; $reverse = "false"; ///lets match up a random $against = $team1; while ($against==$team1){ $against = rand(1,$a); } echo "<br>Row: $rows"; //We have rows set, so lets check each row. $rowcheck = 0; $cancont = 0; echo "<br><i>$team1 vs $against</i>"; $stop = "false"; if ($rows==-1){ $stop = "true"; echo "<br><u>FIRST ROW</u>"; } while ($rowcheck<=$rows){ $reverse = "false"; $redo = "false"; $cancont = 1; echo "<br><i>RC: $rowcheck/$rows</i>"; $t1 = $games[$rowcheck]["Team1"]; $t2 = $games[$rowcheck]["Team2"]; echo "<br><i>t1 = $t1; t2 = $t2</i>"; if($t2==$against){ $cancont = 0; $redo="true"; echo "<br> Team 2 already has a match"; } if($team1==$t2){ if($against==$t1){ //The match is already set, just in the reverse order $stop="true"; echo "<br> Team 1 already has a match against team 2"; } } if ($cancont==0){ $rowcheck=$rows+10; $redo="true"; }else{ $rowcheck +=1; } //Check if already matched up in a previous week. $teamA = $teamsIndex["$b"]; $teamB = $teamsIndex["$against"]; //WAIT how many weeks are listed? $prev = "false"; $sql9 = "select * from `matches` where `game`='$game' and `division`='$division' and `team1`='$teamA' and `team2`='$teamB'"; $result9 = mysql_query($sql9) or die(mysql_error()); while ($row9 = mysql_fetch_array($result9)){ $stop = "false"; $rowcheck = $rows+1; $prev = "true"; echo "<br>Match Already Made"; } $sql9 = "select * from `matches` where `game`='$game' and `division`='$division' and `team1`='$teamB' and `team2`='$teamA'"; $result9 = mysql_query($sql9) or die(mysql_error()); while ($row9 = mysql_fetch_array($result9)){ $stop = "false"; $rowcheck = $rows+1; $prev = "true"; echo "<br>Match Already Made"; } if($prev=="false"){ if ($team1!=$t1){ if ($against!=$t2){ if ($team1!=$t2){ if ($against!=$t1){ $stop="true"; echo "<br>AVALIBLIE"; }else{ $stop="false"; echo "<br>Team Two = t1"; $rowcheck = $rows+1; } }else{ echo "<br>Team1 = t2"; //HOLD ON. If this happens, it should not record, but still print it! $stop = "true"; $reverse = "true"; $against = $t1; $rowcheck = $rows+1; } }else{ $stop="false"; echo "<br>Team2 = t2"; $rowcheck = $rows+1; } }else{ $stop="false"; echo"<br>Team1 =t1"; $rowcheck = $rows+1; } } } //Can we record the match? if ($redo=="true"){ $end = "false"; }else{ //No issues where found $end = "true"; } //Record match //if it wasn't stopped! if($stop=="true"){ if ($rows==-1){ $end = "true"; $games = array( array( "Team1" => "$team1", "Team2" => "$against" ) ); echo "<br><i>First</i>"; $rows +=1; echo "<Center><br><b>$team1 vs $against</b> ($rows)<br><br></center>"; //Convert Indexes $team1 = $teamsIndex["$b"]; $against = $teamsIndex["$against"]; $sql = "insert into `matches` (`team1`,`team2`,`game`,`division`,`week`) values ('$team1','$against','$game','$division','$cWeek')"; mysql_query($sql) or die(mysql_error()); $sql3 = "select * from `bb_forums`"; $mcids=1; $result3 = mysql_query($sql3) or die(mysql_error()); while($row3 = mysql_fetch_array($result3)){ $mcids+=1; } $sql3 = "insert into `bb_forums` (`cid`,`name`,`islocked`) values ('7','Match Chat #$mcids','false')"; mysql_query($sql3) or die(mysql_error()); $sql3 = "select * from `bb_forums` where `name`='Match Chat #$mcids'"; $result3 = mysql_query($sql3) or die(mysql_error()); while($row3 = mysql_fetch_array($result3)){ $id = $row3['id']; } $url = "<a href='forum.php?page=tlist&id=$id'>Match Forum</a>"; $url = mysql_real_escape_string($url); $sql3 = "insert into `matchcom` (`team`,`url`,`team2`,`week`) values ('$against','$url','$team1','$cWeek')"; mysql_query($sql3) or die(mysql_error()); $sql3 = "select * from `matchcom` where `url`='$url'"; $result3 = mysql_query($sql3) or die(mysql_error()); while ($row3 = mysql_fetch_array($result3)){ $mcid = $row3['id']; } $sql3 = "insert into `matchcom_data` (`mcid`,`game`,`division`) values ('$mcid','$game','$division')"; mysql_query($sql3) or die(mysql_error()); $end = "true"; }else{ if($reverse!="true"){ $rows +=1; echo "<br>$rows"; $games[$rows]["Team1"]="$team1"; $games[$rows]["Team2"]="$against"; //array_push($games,Team1 => "$team1", Team2 => "$against"); /*$games .= array( array( Team1 => "$team1", Team2 => "$team2" ) ); */ echo "<centeR><br><b>$team1 vs $against</b> ($rows) <br><br></center>"; //Convert Indexes //$team1 = $b; echo "<br>$b"; $team1 = $teamsIndex["$b"]; $against = $teamsIndex["$against"]; //Insert into Matches $sql = "insert into `matches` (`team1`,`team2`,`game`,`division`,`week`) values ('$team1','$against','$game','$division','$cWeek')"; mysql_query($sql) or die(mysql_error()); //Insert into Match Com $sql3 = "select * from `bb_forums`"; $mcids=1; $result3 = mysql_query($sql3) or die(mysql_error()); while($row3 = mysql_fetch_array($result3)){ $mcids+=1; } $sql3 = "insert into `bb_forums` (`cid`,`name`,`islocked`) values ('7','Match Chat #$mcids','false')"; mysql_query($sql3) or die(mysql_error()); $sql3 = "select * from `bb_forums` where `name`='Match Chat #$mcids'"; $result3 = mysql_query($sql3) or die(mysql_error()); while($row3 = mysql_fetch_array($result3)){ $id = $row3['id']; } $url = "<a href='forum.php?page=tlist&id=$id'>Match Forum</a>"; $url = mysql_real_escape_string($url); $sql3 = "insert into `matchcom` (`team`,`url`,`team2`,`week`) values ('$against','$url','$team1','$cWeek')"; mysql_query($sql3) or die(mysql_error()); $sql3 = "select * from `matchcom` where `url`='$url'"; $result3 = mysql_query($sql3) or die(mysql_error()); while ($row3 = mysql_fetch_array($result3)){ $mcid = $row3['id']; } $sql3 = "insert into `matchcom_data` (`mcid`,`game`,`division`) values ('$mcid','$game','$division')"; mysql_query($sql3) or die(mysql_error()); }else{ echo "<centeR><br><b>$team1 vs $against</b> ($rows) <br><br></center>"; } $end = "true"; } $end="true";
What version of PHP does the function filter_var() come with?? How do I know if I have it installed on my web server? Thanks, Debbie I wrote
<?php Hello Guys ... i am new here and i am also new in php i selfstudy html css and js and bootstrap for front-end and for back-back php & mysql & PDO & OOP and i will soon start mvc then laravel and i am trying to secure my input field and i do not want any attacks or sql injects and i see people user filter_var and htmlentities and htmlspecialchars and each one has diffrent opinion can some one help me and tell me what is the best for securing input which all values will store in database thanks <3
This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=349365.0 I tried parsing through first https://www.jadaliyya.com/Details/28167/The-Empire-of-Sexuality-An-Interview-with-Joseph-Massad then even tried www.google.com and on both I get the following returned
post_url equals: www.google.compost_title equals: testpost_Threadybody equals: Enter your posts... URL equals: www.google.com www.google.com is not a valid URL Web page redirects after 2 seconds. And here is the if statement that handles my filter for URLs if(isset($_POST["submit"]) && !empty($_POST["url"]) && !empty($_POST["Title"])){ $URL = $conn -> real_escape_string($_POST["url"]) ; $BodyText = $conn -> real_escape_string(nl2br($_POST["ThreadBody"])) ; echo "<P>URL equals: " ; echo $URL ; echo "<P>" ; //Change to embed for youtube. if (filter_var($URL, FILTER_VALIDATE_URL)) { echo("$URL is a valid URL"); //Check if url is a youtube url if (strpos($URL,'youtube') !== false) { echo 'Youtube exists.'; $URL = preg_replace("/\s*[a-zA-Z\/\/:\.]*youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i","<iframe width=\"420\" height=\"315\" src=\"//www.youtube.com/embed/$1\" frameborder=\"0\" allowfullscreen></iframe>",$URL); } else { echo 'Youtube is not included .'; $URL = "<ahref ='" . $URL . "</a>" ; } $Title = $conn -> real_escape_string($_POST["Title"]) ; $User = $_SESSION['username']; $sql = "INSERT INTO Threads (Title, Users, ThreadBody, url) VALUES ('$Title', '$User','$BodyText','$URL')"; if (mysqli_query($conn, $sql)) { echo "New record has been added successfully !"; } else { echo "Error: " . $sql . ":-" . mysqli_error($conn); } } else { echo("$URL is not a valid URL"); }
Hi,
Is there any way to use the inbuilt filter functions in PHP to filter for integer values greater than 256? All examples that I saw had a max_range of 256. Kindly suggest. Thanks.
This topic has been moved to Other. http://www.phpfreaks.com/forums/index.php?topic=347753.0 I'm having a lot of trouble validating things using custom regex. I'm trying to validate usernames without spaces using numbers and/or letters with optional underscores. This is my code but it isn't validating anything, nothing is ever validated. Whatever I write it says the username isn't valid. if(isset($_POST['submit'])){ if(filter_var($_POST['value1'], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[\w.-]{{3},{28}}$/")))){ echo "Value is a valid username."; } else { echo "Value is NOT a valid username."; } } ?> Any help regarding this issue will be greatly appreciated. Thanks! Im working with php 5.1.6. With xampp 1.5.14.
Im also working on a stock application. If I want to say add stock product (add_stock.php) this error is generated on screen. It seems to refer to a function in ump.class.php
Here we go,
ump.class.php
<?php /** * GUMP - A fast, extensible PHP input validation class * * @author Sean Nieuwoudt (http://twitter.com/SeanNieuwoudt) * @copyright Copyright (c) 2011 Wixel.net * @link http://github.com/Wixel/GUMP * @version 1.0 */ class GUMP { // Validation rules for execution protected $validation_rules = array(); // Filter rules for execution protected $filter_rules = array(); // Instance attribute containing errors from last run protected $errors = array(); // ** ------------------------- Validation Data ------------------------------- ** // public static $basic_tags = "<br><p><a><strong><b><i><em><img><blockquote><code><dd><dl><hr><h1><h2><h3><h4><h5><h6><label><ul><li><span><sub><sup>"; public static $en_noise_words = "about,after,all,also,an,and,another,any,are,as,at,be,because,been,before, being,between,both,but,by,came,can,come,could,did,do,each,for,from,get, got,has,had,he,have,her,here,him,himself,his,how,if,in,into,is,it,its,it's,like, make,many,me,might,more,most,much,must,my,never,now,of,on,only,or,other, our,out,over,said,same,see,should,since,some,still,such,take,than,that, the,their,them,then,there,these,they,this,those,through,to,too,under,up, very,was,way,we,well,were,what,where,which,while,who,with,would,you,your,a, b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,$,1,2,3,4,5,6,7,8,9,0,_"; // ** ------------------------- Validation Helpers ---------------------------- ** // /** * Shorthand method for inline validation * * @param array $data The data to be validated * @param array $validators The GUMP validators * @return mixed True(boolean) or the array of error messages */ public static function is_valid(array $data, array $validators) { $gump = new Gump(); $gump->validation_rules($validators); if($gump->run($data) === false) { return $gump->get_readable_errors(false); } else { return true; } } /** * Magic method to generate the validation error messages * * @return string */ public function __toString() { return $this->get_readable_errors(true); } /** * Perform XSS clean to prevent cross site scripting * * @static * @access public * @param array $data * @return array */ public static function xss_clean(array $data) { foreach($data as $k => $v) { $data[$k] = filter_var($v, FILTER_SANITIZE_STRING); } return $data; } /** * Getter/Setter for the validation rules * * @param array $rules * @return array */ public function validation_rules(array $rules = array()) { if(!empty($rules)) { $this->validation_rules = $rules; } else { return $this->validation_rules; } } /** * Getter/Setter for the filter rules * * @param array $rules * @return array */ public function filter_rules(array $rules = array()) { if(!empty($rules)) { $this->filter_rules = $rules; } else { return $this->filter_rules; } } /** * Run the filtering and validation after each other * * @param array $data * @return array * @return boolean */ public function run(array $data) { $data = $this->filter($data, $this->filter_rules()); $validated = $this->validate( $data, $this->validation_rules() ); if($validated !== true) { return false; } else { return $data; } } /** * Sanitize the input data * * @access public * @param array $data * @return array */ public function sanitize(array $input, $fields = NULL, $utf8_encode = true) { $magic_quotes = (bool)get_magic_quotes_gpc(); if(is_null($fields)) { $fields = array_keys($input); } foreach($fields as $field) { if(!isset($input[$field])) { continue; } else { $value = $input[$field]; if(is_string($value)) { if($magic_quotes === TRUE) { $value = stripslashes($value); } if(strpos($value, "\r") !== FALSE) { $value = trim($value); } if(function_exists('iconv') && function_exists('mb_detect_encoding') && $utf8_encode) { $current_encoding = mb_detect_encoding($value); if($current_encoding != 'UTF-8' && $current_encoding != 'UTF-16') { $value = iconv($current_encoding, 'UTF-8', $value); } } $value = filter_var($value, FILTER_SANITIZE_STRING); } $input[$field] = $value; } } return $input; } /** * Return the error array from the last validation run * * @return array */ public function errors() { return $this->errors; } /** * Perform data validation against the provided ruleset * * @access public * @param mixed $input * @param array $ruleset * @return mixed */ public function validate(array $input, array $ruleset) { $this->errors = array(); foreach($ruleset as $field => $rules) { #if(!array_key_exists($field, $input)) #{ # continue; #} $rules = explode('|', $rules); foreach($rules as $rule) { $method = NULL; $param = NULL; if(strstr($rule, ',') !== FALSE) // has params { $rule = explode(',', $rule); $method = 'validate_'.$rule[0]; $param = $rule[1]; } else { $method = 'validate_'.$rule; } if(is_callable(array($this, $method))) { $result = $this->$method($field, $input, $param); if(is_array($result)) // Validation Failed { $this->errors[] = $result; } } else { throw new Exception("Validator method '$method' does not exist."); } } } return (count($this->errors) > 0)? $this->errors : TRUE; } /** * Process the validation errors and return human readable error messages * * @param bool $convert_to_string = false * @param string $field_class * @param string $error_class * @return array * @return string */ public function get_readable_errors($convert_to_string = false, $field_class="field", $error_class="error-message") { if(empty($this->errors)) { return ($convert_to_string)? null : array(); } $resp = array(); foreach($this->errors as $e) { $field = ucwords(str_replace(array('_','-'), chr(32), $e['field'])); $param = $e['param']; switch($e['rule']) { case 'validate_required': $resp[] = "The <span class=\"$field_class\">$field</span> field is required"; break; case 'validate_valid_email': $resp[] = "The <span class=\"$field_class\">$field</span> field is required to be a valid email address"; break; case 'validate_max_len': if($param == 1) { $resp[] = "The <span class=\"$field_class\">$field</span> field needs to be shorter than $param character"; } else { $resp[] = "The <span class=\"$field_class\">$field</span> field needs to be shorter than $param characters"; } break; case 'validate_min_len': if($param == 1) { $resp[] = "The <span class=\"$field_class\">$field</span> field needs to be longer than $param character"; } else { $resp[] = "The <span class=\"$field_class\">$field</span> field needs to be longer than $param characters"; } break; case 'validate_exact_len': if($param == 1) { $resp[] = "The <span class=\"$field_class\">$field</span> field needs to be exactly $param character in length"; } else { $resp[] = "The <span class=\"$field_class\">$field</span> field needs to be exactly $param characters in length"; } break; case 'validate_alpha': $resp[] = "The <span class=\"$field_class\">$field</span> field may only contain alpha characters(a-z)"; break; case 'validate_alpha_numeric': $resp[] = "The <span class=\"$field_class\">$field</span> field may only contain alpha-numeric characters"; break; case 'validate_alpha_dash': $resp[] = "The <span class=\"$field_class\">$field</span> field may only contain alpha characters & dashes"; break; case 'validate_numeric': $resp[] = "The <span class=\"$field_class\">$field</span> field may only contain numeric characters"; break; case 'validate_integer': $resp[] = "The <span class=\"$field_class\">$field</span> field may only contain a numeric value"; break; case 'validate_boolean': $resp[] = "The <span class=\"$field_class\">$field</span> field may only contain a true or false value"; break; case 'validate_float': $resp[] = "The <span class=\"$field_class\">$field</span> field may only contain a float value"; break; case 'validate_valid_url': $resp[] = "The <span class=\"$field_class\">$field</span> field is required to be a valid URL"; break; case 'validate_url_exists': $resp[] = "The <span class=\"$field_class\">$field</span> URL does not exist"; break; case 'validate_valid_ip': $resp[] = "The <span class=\"$field_class\">$field</span> field needs to contain a valid IP address"; break; case 'validate_valid_cc': $resp[] = "The <span class=\"$field_class\">$field</span> field needs to contain a valid credit card number"; break; case 'validate_valid_name': $resp[] = "The <span class=\"$field_class\">$field</span> field needs to contain a valid human name"; break; case 'validate_contains': $resp[] = "The <span class=\"$field_class\">$field</span> field needs contain one of these values: ".implode(', ', $param); break; case 'validate_street_address': $resp[] = "The <span class=\"$field_class\">$field</span> field needs to be a valid street address"; break; } } if(!$convert_to_string) { return $resp; } else { $buffer = ''; foreach($resp as $s) { $buffer .= "<span class=\"$error_class\">$s</span>"; } return $buffer; } } /** * Filter the input data according to the specified filter set * * @access public * @param mixed $input * @param array $filterset * @return mixed */ public function filter(array $input, array $filterset) { foreach($filterset as $field => $filters) { if(!array_key_exists($field, $input)) { continue; } $filters = explode('|', $filters); foreach($filters as $filter) { $params = NULL; if(strstr($filter, ',') !== FALSE) { $filter = explode(',', $filter); $params = array_slice($filter, 1, count($filter) - 1); $filter = $filter[0]; } if(is_callable(array($this, 'filter_'.$filter))) { $method = 'filter_'.$filter; $input[$field] = $this->$method($input[$field], $params); } else if(function_exists($filter)) { $input[$field] = $filter($input[$field]); } else { throw new Exception("Filter method '$filter' does not exist."); } } } return $input; } // ** ------------------------- Filters --------------------------------------- ** // /** * Replace noise words in a string (http://tax.cchgroup.com/help/Avoiding_noise_words_in_your_search.htm) * * Usage: '<index>' => 'noise_words' * * @access protected * @param string $value * @param array $params * @return string */ protected function filter_noise_words($value, $params = NULL) { $value = preg_replace('/\s\s+/u', chr(32),$value); $value = " $value "; $words = explode(',', self::$en_noise_words); foreach($words as $word) { $word = trim($word); $word = " $word "; // Normalize if(stripos($value, $word) !== FALSE) { $value = str_ireplace($word, chr(32), $value); } } return trim($value); } /** * Remove all known punctuation from a string * * Usage: '<index>' => 'rmpunctuataion' * * @access protected * @param string $value * @param array $params * @return string */ protected function filter_rmpunctuation($value, $params = NULL) { return preg_replace("/(?![.=$'€%-])\p{P}/u", '', $value); } /** * Translate an input string to a desired language [DEPRECIATED] * * Any ISO 639-1 2 character language code may be used * * See: http://www.science.co.il/language/Codes.asp?s=code2 * * @access protected * @param string $value * @param array $params * @return string */ /* protected function filter_translate($value, $params = NULL) { $input_lang = 'en'; $output_lang = 'en'; if(is_null($params)) { return $value; } switch(count($params)) { case 1: $input_lang = $params[0]; break; case 2: $input_lang = $params[0]; $output_lang = $params[1]; break; } $text = urlencode($value); $translation = file_get_contents( "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q={$text}&langpair={$input_lang}|{$output_lang}" ); $json = json_decode($translation, true); if($json['responseStatus'] != 200) { return $value; } else { return $json['responseData']['translatedText']; } } */ /** * Sanitize the string by removing any script tags * * Usage: '<index>' => 'sanitize_string' * * @access protected * @param string $value * @param array $params * @return string */ protected function filter_sanitize_string($value, $params = NULL) { return filter_var($value, FILTER_SANITIZE_STRING); } /** * Sanitize the string by urlencoding characters * * Usage: '<index>' => 'urlencode' * * @access protected * @param string $value * @param array $params * @return string */ protected function filter_urlencode($value, $params = NULL) { return filter_var($value, FILTER_SANITIZE_ENCODED); } /** * Sanitize the string by converting HTML characters to their HTML entities * * Usage: '<index>' => 'htmlencode' * * @access protected * @param string $value * @param array $params * @return string */ protected function filter_htmlencode($value, $params = NULL) { return filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS); } /** * Sanitize the string by removing illegal characters from emails * * Usage: '<index>' => 'sanitize_email' * * @access protected * @param string $value * @param array $params * @return string */ protected function filter_sanitize_email($value, $params = NULL) { return filter_var($value, FILTER_SANITIZE_EMAIL); } /** * Sanitize the string by removing illegal characters from numbers * * @access protected * @param string $value * @param array $params * @return string */ protected function filter_sanitize_numbers($value, $params = NULL) { return filter_var($value, FILTER_SANITIZE_NUMBER_INT); } /** * Filter out all HTML tags except the defined basic tags * * @access protected * @param string $value * @param array $params * @return string */ protected function filter_basic_tags($value, $params = NULL) { return strip_tags($value, self::$basic_tags); } /** * Filter out all SQL Valnurablities * * @access protected * @param string $value * @param array $params * @return string */ protected function filter_mysql_escape($value, $params = NULL) { return mysql_real_escape_string($value); } // ** ------------------------- Validators ------------------------------------ ** // /** * Verify that a value is contained within the pre-defined value set * * Usage: '<index>' => 'contains,value value value' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_contains($field, $input, $param = NULL) { $param = trim(strtolower($param)); $value = trim(strtolower($input[$field])); if (preg_match_all('#\'(.+?)\'#', $param, $matches, PREG_PATTERN_ORDER)) { $param = $matches[1]; } else { $param = explode(chr(32), $param); } if(in_array($value, $param)) { // valid, return nothing return; } else { return array( 'field' => $field, 'value' => $value, 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Check if the specified key is present and not empty * * Usage: '<index>' => 'required' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_required($field, $input, $param = NULL) { if(isset($input[$field]) && trim($input[$field]) != '') { return; } else { return array( 'field' => $field, 'value' => NULL, 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided email is valid * * Usage: '<index>' => 'valid_email' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_valid_email($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!filter_var($input[$field], FILTER_VALIDATE_EMAIL)) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided value length is less or equal to a specific value * * Usage: '<index>' => 'max_len,240' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_max_len($field, $input, $param = NULL) { if(!isset($input[$field])) { return; } if(function_exists('mb_strlen')) { if(mb_strlen($input[$field]) <= (int)$param) { return; } } else { if(strlen($input[$field]) <= (int)$param) { return; } } return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } /** * Determine if the provided value length is more or equal to a specific value * * Usage: '<index>' => 'min_len,4' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_min_len($field, $input, $param = NULL) { if(!isset($input[$field])) { return; } if(function_exists('mb_strlen')) { if(mb_strlen($input[$field]) >= (int)$param) { return; } } else { if(strlen($input[$field]) >= (int)$param) { return; } } return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } /** * Determine if the provided value length matches a specific value * * Usage: '<index>' => 'exact_len,5' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_exact_len($field, $input, $param = NULL) { if(!isset($input[$field])) { return; } if(function_exists('mb_strlen')) { if(mb_strlen($input[$field]) == (int)$param) { return; } } else { if(strlen($input[$field]) == (int)$param) { return; } } return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } /** * Determine if the provided value contains only alpha characters * * Usage: '<index>' => 'alpha' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_alpha($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!preg_match("/^([a-zÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ])+$/i", $input[$field]) !== FALSE) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided value contains only alpha-numeric characters * * Usage: '<index>' => 'alpha_numeric' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_alpha_numeric($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!preg_match("/^([a-z0-9ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ])+$/i", $input[$field]) !== FALSE) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided value contains only alpha characters with dashed and underscores * * Usage: '<index>' => 'alpha_dash' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_alpha_dash($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!preg_match("/^([a-z0-9ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ_-])+$/i", $input[$field]) !== FALSE) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided value is a valid number or numeric string * * Usage: '<index>' => 'numeric' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_numeric($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!is_numeric($input[$field])) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided value is a valid integer * * Usage: '<index>' => 'integer' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_integer($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!filter_var($input[$field], FILTER_VALIDATE_INT)) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided value is a PHP accepted boolean * * Usage: '<index>' => 'boolean' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_boolean($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } $bool = filter_var($input[$field], FILTER_VALIDATE_BOOLEAN); if(!is_bool($bool)) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided value is a valid float * * Usage: '<index>' => 'float' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_float($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!filter_var($input[$field], FILTER_VALIDATE_FLOAT)) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided value is a valid URL * * Usage: '<index>' => 'valid_url' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_valid_url($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!filter_var($input[$field], FILTER_VALIDATE_URL)) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if a URL exists & is accessible * * Usage: '<index>' => 'url_exists' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_url_exists($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } $url = str_replace( array('http://', 'https://', 'ftp://'), '', strtolower($input[$field]) ); if(function_exists('checkdnsrr')) { if(!checkdnsrr($url)) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } else { if(gethostbyname($url) == $url) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } } /** * Determine if the provided value is a valid IP address * * Usage: '<index>' => 'valid_ip' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_valid_ip($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!filter_var($input[$field], FILTER_VALIDATE_IP) !== FALSE) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided value is a valid IPv4 address * * Usage: '<index>' => 'valid_ipv4' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_valid_ipv4($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!filter_var($input[$field], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== FALSE) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided value is a valid IPv6 address * * Usage: '<index>' => 'valid_ipv6' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_valid_ipv6($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!filter_var($input[$field], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== FALSE) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the input is a valid credit card number * * See: http://stackoverflow.com/questions/174730/what-is-the-best-way-to-validate-a-credit-card-in-php * Usage: '<index>' => 'valid_cc' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_valid_cc($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } $number = preg_replace('/\D/', '', $input[$field]); if(function_exists('mb_strlen')) { $number_length = mb_strlen($input[$field]); } else { $number_length = strlen($input[$field]); } $parity = $number_length % 2; $total = 0; for($i = 0; $i < $number_length; $i++) { $digit = $number[$i]; if ($i % 2 == $parity) { $digit *= 2; if ($digit > 9) { $digit -= 9; } } $total += $digit; } if($total % 10 == 0) { return; // Valid } else { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the input is a valid human name [Credits to http://github.com/ben-s] * * See: https://github.com/Wixel/GUMP/issues/5 * Usage: '<index>' => 'valid_name' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_valid_name($field, $input, $param = NULL) { if(!isset($input[$field])|| empty($input[$field])) { return; } if(!preg_match("/^([a-zÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïñðòóôõöùúûüýÿ '-])+$/i", $input[$field]) !== FALSE) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided input is likely to be a street address using weak detection * * Usage: '<index>' => 'street_address' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_street_address($field, $input, $param = NULL) { if(!isset($input[$field])|| empty($input[$field])) { return; } // Theory: 1 number, 1 or more spaces, 1 or more words $hasLetter = preg_match('/[a-zA-Z]/', $input[$field]); $hasDigit = preg_match('/\d/' , $input[$field]); $hasSpace = preg_match('/\s/' , $input[$field]); $passes = $hasLetter && $hasDigit && $hasSpace; if(!$passes) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } } // EOCHere is add_stock.php <?php include_once("init.php"); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>POSNIC - Add Stock Category</title> <!-- Stylesheets --> <link href='http://fonts.googleapis.com/css?family=Droid+Sans:400,700' rel='stylesheet'> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="js/date_pic/date_input.css"> <link rel="stylesheet" href="lib/auto/css/jquery.autocomplete.css"> <!-- Optimize for mobile devices --> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <!-- jQuery & JS files --> <?php include_once("tpl/common_js.php"); ?> <script src="js/script.js"></script> <script src="js/date_pic/jquery.date_input.js"></script> <script src="lib/auto/js/jquery.autocomplete.js "></script> <script> /*$.validator.setDefaults({ submitHandler: function() { alert("submitted!"); } });*/ $(document).ready(function() { $("#supplier").autocomplete("supplier1.php", { width: 160, autoFill: true, selectFirst: true }); $("#category").autocomplete("category.php", { width: 160, autoFill: true, selectFirst: true }); // validate signup form on keyup and submit $("#form1").validate({ rules: { name: { required: true, minlength: 3, maxlength: 200 }, stockid: { required: true, minlength: 3, maxlength: 200 }, cost: { required: true, }, sell: { required: true, } }, messages: { name: { required: "Please Enter Stock Name", minlength: "Category Name must consist of at least 3 characters" }, stockid: { required: "Please Enter Stock ID", minlength: "Category Name must consist of at least 3 characters" }, sell: { required: "Please Enter Selling Price", minlength: "Category Name must consist of at least 3 characters" }, cost: { required: "Please Enter Cost Price", minlength: "Category Name must consist of at least 3 characters" } } }); }); function numbersonly(e){ var unicode=e.charCode? e.charCode : e.keyCode if (unicode!=8 && unicode!=46 && unicode!=37 && unicode!=38 && unicode!=39 && unicode!=40 && unicode!=9){ //if the key isn't the backspace key (which we should allow) if (unicode<48||unicode>57) return false } } </script> </script> </head> <body> <!-- TOP BAR --> <?php include_once("tpl/top_bar.php"); ?> <!-- end top-bar --> <!-- HEADER --> <div id="header-with-tabs"> <div class="page-full-width cf"> <ul id="tabs" class="fl"> <li><a href="dashboard.php" class="dashboard-tab">Dashboard</a></li> <li><a href="view_sales.php" class="sales-tab">Sales</a></li> <li><a href="view_customers.php" class=" customers-tab">Customers</a></li> <li><a href="view_purchase.php" class="purchase-tab">Purchase</a></li> <li><a href="view_supplier.php" class=" supplier-tab">Supplier</a></li> <li><a href="view_product.php" class="active-tab stock-tab">Stocks / Products</a></li> <li><a href="view_payments.php" class="payment-tab">Payments / Outstandings</a></li> <li><a href="view_report.php" class="report-tab">Reports</a></li> </ul> <!-- end tabs --> <!-- Change this image to your own company's logo --> <!-- The logo will automatically be resized to 30px height. --> <a href="#" id="company-branding-small" class="fr"><img src="<?php if(isset($_SESSION['logo'])) { echo "upload/".$_SESSION['logo'];}else{ echo "upload/posnic.png"; } ?>" alt="Point of Sale" /></a> </div> <!-- end full-width --> </div> <!-- end header --> <!-- MAIN CONTENT --> <div id="content"> <div class="page-full-width cf"> <div class="side-menu fl"> <h3>Stock Management</h3> <ul> <li><a href="add_stock.php">Add Stock/Product</a></li> <li><a href="view_product.php">View Stock/Product</a></li> <li><a href="add_category.php">Add Stock Category</a></li> <li><a href="view_category.php">view Stock Category</a></li> <li><a href="view_stock_availability.php">view Stock Available</a></li> </ul> </div> <!-- end side-menu --> <div class="side-content fr"> <div class="content-module"> <div class="content-module-heading cf"> <h3 class="fl">Add Stock </h3> <span class="fr expand-collapse-text">Click to collapse</span> <div style="margin-top: 15px;margin-left: 150px"></div> <span class="fr expand-collapse-text initial-expand">Click to expand</span> </div> <!-- end content-module-heading --> <div class="content-module-main cf"> <?php //Gump is libarary for Validatoin if(isset($_POST['name'])){ $_POST = $gump->sanitize($_POST); $gump->validation_rules(array( 'name' => 'required|max_len,100|min_len,3', 'stockid' => 'required|max_len,200', 'sell' => 'required|max_len,200', 'cost' => 'required|max_len,200', 'supplier' => 'max_len,200', 'category' => 'max_len,200' )); $gump->filter_rules(array( 'name' => 'trim|sanitize_string|mysql_escape', 'stockid' => 'trim|sanitize_string|mysql_escape', 'sell' => 'trim|sanitize_string|mysql_escape', 'cost' => 'trim|sanitize_string|mysql_escape', 'category' => 'trim|sanitize_string|mysql_escape', 'supplier' => 'trim|sanitize_string|mysql_escape' )); $validated_data = $gump->run($_POST); $name = ""; $stockid = ""; $sell = ""; $cost = ""; $supplier = ""; $category = ""; if($validated_data === false) { echo $gump->get_readable_errors(true); } else { $name=mysql_real_escape_string($_POST['name']); $stockid=mysql_real_escape_string($_POST['stockid']); $sell=mysql_real_escape_string($_POST['sell']); $cost=mysql_real_escape_string($_POST['cost']); $supplier=mysql_real_escape_string($_POST['supplier']); $category=mysql_real_escape_string($_POST['category']); $count = $db->countOf("stock_details", "stock_name ='$name'"); if($count>1) { $data='Dublicat Entry. Please Verify'; $msg='<p style=color:red;font-family:gfont-family:Georgia, Times New Roman, Times, serif>'.$data.'</p>';// ?> <script src="dist/js/jquery.ui.draggable.js"></script> <script src="dist/js/jquery.alerts.js"></script> <script src="dist/js/jquery.js"></script> <link rel="stylesheet" href="dist/js/jquery.alerts.css" > <script type="text/javascript"> jAlert('<?php echo $msg; ?>', 'POSNIC'); </script> <?php } else { if($db->query("insert into stock_details(stock_id,stock_name,stock_quatity,supplier_id,company_price,selling_price,category) values('$stockid','$name',0,'$supplier',$cost,$sell,'$category')")) { $db->query("insert into stock_avail(name,quantity) values('$name',0)"); $msg=" $name Stock Details Added" ; header("Location: add_stock.php?msg=$msg"); }else echo "<br><font color=red size=+1 >Problem in Adding !</font>" ; } } } if(isset($_GET['msg'])){ $data=$_GET['msg']; $msg='<p style=color:#153450;font-family:gfont-family:Georgia, Times New Roman, Times, serif>'.$data.'</p>';// ?> <script src="dist/js/jquery.ui.draggable.js"></script> <script src="dist/js/jquery.alerts.js"></script> <script src="dist/js/jquery.js"></script> <link rel="stylesheet" href="dist/js/jquery.alerts.css" > <script type="text/javascript"> jAlert('<?php echo $msg; ?>', 'POSNIC'); </script> <?php } ?> <form name="form1" method="post" id="form1" action=""> <table class="form" border="0" cellspacing="0" cellpadding="0"> <tr> <?php $max = $db->maxOfAll("id", "stock_details"); $max=$max+1; $autoid="SD".$max.""; ?> <td><span class="man">*</span>Stock ID:</td> <td><input name="stockid" type="text" id="stockid" readonly maxlength="200" class="round default-width-input" value="<?php echo $autoid; ?>" /></td> <td><span class="man">*</span>Name:</td> <td><input name="name"placeholder="ENTER CATEGORY NAME" type="text" id="name" maxlength="200" class="round default-width-input" value="<?php echo $name; ?>" /></td> </tr> <tr> <td><span class="man">*</span>Cost:</td> <td><input name="cost" placeholder="ENTER COST PRICE" type="text" id="cost" maxlength="200" class="round default-width-input" onkeypress="return numbersonly(event)" value="<?php echo $cost; ?>" /></td> <td><span class="man">*</span>Sell:</td> <td><input name="sell" placeholder="ENTER SELLING PRICE" type="text" id="sell" maxlength="200" class="round default-width-input" onkeypress="return numbersonly(event)" value="<?php echo $sell; ?>" /></td> </tr> <tr> <td>Supplier:</td> <td><input name="supplier" placeholder="ENTER SUPPLIER NAME" type="text" id="supplier" maxlength="200" class="round default-width-input" value="<?php echo $supplier; ?>" /></td> <td>Category:</td> <td><input name="category" placeholder="ENTER CATEGORY NAME" type="text" id="category" maxlength="200" class="round default-width-input" value="<?php echo $category; ?>" /></td> </tr> <tr> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> <input class="button round blue image-right ic-add text-upper" type="submit" name="Submit" value="Add"> (Control + S) <td align="right"><input class="button round red text-upper" type="reset" name="Reset" value="Reset"> </td> </tr> </table> </form> </div> <!-- end content-module-main --> </div> <!-- end content-module --> </div> <!-- end full-width --> </div> <!-- end content --> <!-- FOOTER --> <div id="footer"> <p>Any Queries email to <a href="mailto:sridhar.posnic@gmail.com?subject=Stock%20Management%20System">sridhar.posnic@gmail.com</a>.</p> </div> <!-- end footer --> </body> </html>now who can tell me what is wrong with the function filter_var() method on line 186 in ump.class.php? I'm trying to automatically change a math equation so that the solution is an even number: It is at first complicated but I'm progressing. This is my first attempt at accomplishing what I'm trying to accomplish. if (($sol != round($sol)) && ($x1 < $x2)) { /***********************************************************/ function round_up ($sol, $x1, $op, $x2) { for ($x1 = $x1; $sol < round($sol); $x1++) { switch ($op) { case '+' : $sol = $x1 + $x2; break; case '-' : $sol = $x1 - $x2; break; case '*' : $sol = $x1 * $x2; break; case '/' : $sol = $x1 / $x2; break; } } return (array ($sol, $x1, $op, $x2)); } /**********************************************************/ $round_array = round_up($sol, $x1, $op, $x2); echo "after for loop: $round_array[1] $round_array[2] $round_array[3] = and sol: $round_array[0] <br /><br />"; } If the solution of the equation is not a round number, and if the first number is smaller than the other, than increase the first number until the solution is a round number. It is a very primitive solution, but I'm learning as I go and I'll try to make it more intelligent. But to my problem, the above script outputs following values: Code: [Select] first calc: 3 / 5 = ? first sol: 0.6 after for loop: 6 / 5 = and sol: 1 The script will increase the first number about 1 digit more, and that is exactly my problem, since that way the equation makes no sense. The condition of the for loop is, increase $x1 till $sol is SHORTLY before the next rounded number, when it is has reached the next rounded number STOP. Thus $x1 should be 5 in the above example, because 5/5 = 1. IT seems that after $sol has reached the next round number, the for loop will go one more time over the variables, and THEN it will stop. How can I solve this problem? >subject. Why does it do this and how can I fix it? Example: I write <?php echo"hello world!"; ?> other stuff/html here After I submit I see this: <?php echo"hello world!"; ?> other stuff/html here 1 I'm using Geshi w/ highlight_string This also happens if I use htmlspecialchars + highlight_string Can anyone tell me what's making this code put an extra entry in the database?Whatever the number of looped students being added, it adds another row with nothing but the registrationid entered. Code: [Select] <?php // connect to database include("databaseconn.php"); // store all posted intemnos and descriptions in local arrays $fname = $_POST['fname']; $lname = $_POST['lname']; $phone = $_POST['phone']; $email = $_POST['email']; $bdate = $_POST['bdate']; $bdate2 = $_POST['bdate2']; $bdate3 = $_POST['bdate3']; $wid = $_POST['wid']; $rid = $_POST['reg_id']; $reg_alone = $_POST['reg_alone']; $_SESSION['workshops']=$wid; ?> <? if(sizeof($_POST['fname'])) { // loop through array $number = count($fname); for ($i=0; $i<=$number; $i++) { // store a single item number and description in local variables $fnames = $fname[$i]; $lnames = $lname[$i]; $phones = $phone[$i]; $emails = $email[$i]; $bdates = $bdate[$i]; $bdates2 = $bdate2[$i]; $bdates3 = $bdate3[$i]; $wids = $wid[$i]; $rids = $rid[$i]; echo "echod ".$bdates2."and<br>"; print_r($bdates2); $query_insertItemWorkshop = "INSERT INTO tbl_attendees (attendee_fname, attendee_lname, attendee_registrationid, workshop_id, attendee_email, attendee_telephone, attendee_bday, attendee_bmonth, attendee_byear) VALUES ('$fnames', '$lnames', '$reg_alone', '$wids', '$emails', '$phones', '$bdates', '$bdates2', '$bdates3')"; echo "query: ".$query_insertItemWorkshop; $dberror = ""; $ret = mysql_query($query_insertItemWorkshop); } } ?> Hey Guys, I've got a small script that displays latest news. It is supposed to show just the title of the news item in a list, however it shows the content at the bottom of the code... This is my page <ul> <?php $args= array( 'news_items' => 500, 'title' => TRUE, 'content' => FALSE, 'before_title' => '<li>', 'after_title' => '</li>' ); jep_latest_news_loop($args); echo '</ul>'; ?> <br>TEST<br> But this is the output Quote * February 2011 Newsletter * January 2011 Newsletter * December 2010 Newsletter * November 2010 Newsletter * October 2010 Newsletter * New Website Launched TEST February 2011 Newsletter January 2011 Newsletter December 2010 Newsletter November 2010 Newsletter October 2010 Newsletter XXX XXXXX are pleased to announce the launch their new website today. We hope you find it easy to use and informative. Please feel free to contact us with any queries. This is the code generator page <?php add_action('init', 'jep_latest_news_init'); function jep_latest_news_init() { // Create new Latest-News custom post type $labels = array( 'name' => _x('Latest News', 'post type general name'), 'singular_name' => _x('Latest News', 'post type singular name'), 'add_new' => _x('Add New', 'Latest News'), 'add_new_item' => __('Add New Latest News'), 'edit_item' => __('Edit Latest News'), 'new_item' => __('New Latest News'), 'view_item' => __('View Latest News'), 'search_items' => __('Search Latest News'), 'not_found' => __('No Latest News found'), 'not_found_in_trash' => __('No Latest News found in Trash'), '_builtin' => false, 'parent_item_colon' => '' ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'exclude_from_search' => false, 'show_ui' => true, 'query_var' => true, 'rewrite' => true, 'capability_type' => 'post', 'hierarchical' => false, 'menu_position' => 20, 'supports' => array('title','editor','author','thumbnail','excerpt','comments'), 'taxonomies' => array('category', 'post_tag') ); register_post_type('latest-news',$args); } /* Template function to output the latest news stories */ function jep_latest_news_loop($args = null) { $defaults = array( 'news_items' => 500, 'title' => TRUE, 'content' => FALSE, 'before_title' => '<li class="h3">', 'after_title' => '</li>', ); global $paged; $r = wp_parse_args( $args, $defaults ); $qargs=array( 'post_type'=>'latest-news', //'posts_per_page' => $r[news_items], //'paged' => $paged ); query_posts($qargs); while ( have_posts() ) : the_post(); ?> <?php echo($r[before_title]);?> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <?php echo($r[after_title]);?> <?php endwhile; } ?> Any ideas what is dumping the extra code? Hello, Experts! Need you advice. Here is the code: <?php if ($var == "") { echo "text"; } if ($var == "*") { echo "text"; } else if ($var != "") { $query = "SELECT * FROM bd WHERE ....."; $data = mysql_query($query) or die(mysql_error()); $anymatches=mysql_num_rows($data); if ($anymatches != 0) { echo "text"; while($row = mysql_fetch_array($data)) { echo "text"; } } if ($anymatches == 0) { $query2 = "SELECT * FROM bd WHERE....."; $data2 = mysql_query($query2) or die(mysql_error()); $anymatches2=mysql_num_rows($data2); if ($anymatches2 != 0) { echo "text" else { mysql_query("INSERT INTO notfound (notfound) VALUES ('$var')") or die(mysql_error()); } } } ?> The last line adds two identical lines to my table. Do I run it twice? Thanks in advance! Hi Guys, i got the PHP and MYSQL for dummies (4th addition) and i am typing up the code examples myself just to gain the experience. Im at the end of the book nearly where it is talking about log in applications that add info to the url but for some reason the code doesn't work. Im using Xampp as a localhost server. Attached are the two scripts for the program, and below is the include file. I open up the login_url form first: form_log.inc: <?php /* Program name: form_log.inc * Description: Displays a login form */ if( isset ( $message ) ) { echo $message; } echo "<form action='$_SERVER[PHP_SELF]' method='POST' style='margin: .5in'>\n <p><label for='username' style='font-weight: bold; padding-bottom: 1em'>User ID: </label> <input type='text' name='user_name' id='user_name' value='$user_name' />\n</p> <p><label for='password' style='font-weight: bold'>Password: </label> <input type='password' name='password' id='password' value='$password' />\n</p> <p><input type='submit' value='Log In'>\n</p> <input type='hidden' name='sent' value='yes' /> </form>\n"; ?> Here are the errors i get: Warning: include(dbstuff.inc) [function.include]: failed to open stream: No such file or directory in /Applications/XAMPP/xamppfiles/htdocs/test_php/login_url.php on line 31 Warning: include() [function.include]: Failed opening 'dbstuff.inc' for inclusion (include_path='.:/Applications/XAMPP/xamppfiles/lib/php:/Applications/XAMPP/xamppfiles/lib/php/pear') in /Applications/XAMPP/xamppfiles/htdocs/test_php/login_url.php on line 31 Couldn't execute query. Any help would be appreciated thankyou Enlighten Hi All, I have a script that i bought and a part of it has a share icon with an email icon so if the user clicks the email icon then it opens up your email client and adds the details of the deal to the email. The problem is that it seems to break each word up by placing a + between them. So for example you get this... Come+and+check+out+Welcome+to+theSocialDeal,+they+have+this+great+local+deal,+if+we+all+buy+it+then+we+get+it+cheaper! Today's+Deal:+4+hours+of+extreme+MTB+action+at+John+Doe+Extreme+Trail+Centre+for+the+price+of+1+hour Click+this+link+to+check+it+out:+ which should be this... Come and check out Welcome to theSocialDeal, they have this great local deal, if we all buy it then we get it cheaper! Today's Deal: 4 hours of extreme MTB action at John Doe Extreme Trail Centre for the price of 1 hour Click this link to check it out: Here is the php function, does anyone know what this could be and how i can stop it? function share_mail($team) { global $login_user_id; global $INI; if (!$team) { $team = array( 'title' => $INI['system']['sitename'] . '(' . $INI['system']['wwwprefix'] . ')', ); } $pre[] = "Come and check out {$INI['system']['sitename']}, they have this great local deal, if we all buy it then we get it cheaper!"; if ( $team['id'] ) { $pre[] = "Today's Deal: {$team['title']}"; $pre[] = "Click this link to check it out: "; $pre[] = $INI['system']['wwwprefix'] . "/team.php?id={$team['id']}&r={$login_user_id}"; $pre = mb_convert_encoding(join("\n\n", $pre), 'UTF-8', 'UTF-8'); $sub = "The Deal: {$team['title']}"; } else { $sub = $pre[] = $team['title']; } $sub = mb_convert_encoding($sub, 'UTF-8', 'UTF-8'); $query = array( 'subject' => $sub, 'body' => $pre, ); $query = http_build_query($query); return 'mailto:?'.$query; } I'm having a problem with some php code that allows you to edit a text file. No matter what file it loads, it always adds four horizontal tabs and two spaces to the end of the text. I've attached the code to this post. If anyone can help me with this, it would be greatly appreciated. Cindy Hi, I am trying to make some adjustments to uploadify.php which comes with the latest version of uploadify (3.0 beta), so that it works with a session variable that stores the login username and adds it to the path for uploads. Here is uploadify.php as it currently looks: Code: [Select] <?php session_name("MyLogin"); session_start(); $targetFolder = '/songs/' . $_SESSION['name']; // Relative to the root if (!empty($_FILES)) { $tempFile = $_FILES['Filedata']['tmp_name']; $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder; $targetFile = rtrim($targetPath,'/') .'/'. $_FILES['Filedata']['name']; // Validate the file type $fileTypes = array('m4a','mp3','flac','ogg'); // File extensions $fileParts = pathinfo($_FILES['Filedata']['name']); if (in_array($fileParts['extension'],$fileTypes)) { move_uploaded_file($tempFile,$targetFile); echo '1'; } else { echo 'Invalid file type.'; } } echo $targetFolder; ?> I added Code: [Select] echo $targetFolder; at the bottom so that I could make sure that the string returned was correct, and it is, i.e. '/songs/nick'. For some reason though, uploads are not going to the correct folder, i.e. the username folder, but instead are going to the parent folder 'songs'. The folder for username exists, with correct permissions, and when I manually enter Code: [Select] $targetFolder = '/songs/nick';all works fine. Which strikes me as rather strange. I have limited experience of using php, but wonder how if the correct string is returned by the session variable, the upload works differently than with the manually entered string. Any help would be much appreciated. It's the last issue with a website that was due to go live 2 days ago! Thanks, Nick |