Jump to content

NotionCommotion

Members
  • Posts

    2,446
  • Joined

  • Last visited

  • Days Won

    10

Everything posted by NotionCommotion

  1. Which line do you have questions?
  2. Thanks Jacques1, Your advice makes sense. Maybe I shouldn't be using jQuery/JavaScript to create this content directly, but use some sort of template system (P.S. I love Twig!). I assume it has methods to deal with XSS and encoding URLs. Given my brief research, sounds like HandleBars might be a good start. Do you have any advice? Thanks
  3. I have some PHP which sends some user provided data to the client: <?php header('Content-type: application/json'); $data=array( array('id'=>10,'firstname'=>'John','lastname'=>'Doe'), array('id'=>14,'firstname'=>'Jane','lastname'=>'Doe'), array('id'=>19,'firstname'=>'XSS!','lastname'=>'XSS!'), ); echo(json_encode($data)); ?> The client then displays the data: $.getJSON('getJSON.php', { something: 123 }, function(list) { var string = ''; for (var i in list) { string += '<li>< a href = "index.php?id=' + list[i]['id'] + '">' + list[i]['firstname'] + '</a></li>'; } $("#MyElem").html(string); }); Does this represent any XSS risk? If so, how do I prevent it?
  4. Ah, I now see you you are creating a file with a separate class to validate and sanitize each given thing. If one wanted to add a new method, they would add a new file with a new class for the given thing, right? I was planning on creating a single class which includes core methods as well as all validation methods and sanitation methods. If one wanted to add a new method, they would just extend that class and add the method. I probably see the advantage of your approach, but please confirm you feel it is the right way to go. Below is my total implementation. The validation class is attached (tried to add to this post, but must have been too long and didn't format correctly). I realize it is a bunch of script and don't expect you to go through it all, but would appreciate any comments. Thanks Main page <!DOCTYPE html> <html> <head> <script type="text/javascript" src="jquery.js" /></script> <script type="text/javascript" src="getValidationObj.php" /></script> <script type="text/javascript"> (function() { $("#myForm").validate(validation_JSON); }); </script> </head> <body> <form id="myForm"> <input name="name" type="text" /> <input name="email" type="text" /> </form> </body> <html> getValidationObj.php Note that I know Jacques1 said not to use PHP to generate JS, however, I don't know a workaround. Yes, I could create JSON instead, however, the client would on same cases need to use eval() which is also not ideal <?php header('Content-Type: application/javascript'); $config_file='/path/to/aGivenPagesValidationFile.json'; $modify_file=array('isNameRequired'=>true); $validate=new validate($config_file,$modify_file); exit("var validation_JSON ={$validate->getJSON()};"); ?> aGivenPagesValidationFile.json { "rules": { "name": "{isNameRequired}", "email": { "required": true, "email": true } }, "messages": { "name": "Please specify your name", "email": { "required": "We need your email address to contact you", "email": "Your email address must be in the format of name@domain.com" } } "sanitizers": {} } Script to save data <?php $config_file='/path/to/aGivenPagesValidationFile.json'; $modify_file=array('isNameRequired'=>true); $validate=new validate($config_file,$modify_file); $data=$validate->sanitize($_POST); $errors=$validate->validate($data); if(empty($errors)) { //Save the data } ?> validate.php
  5. Thank you Requinix, I didn't think I was. Please let me know why you feel so. I decide to add a new method to the jQuery validition plugin which validates that the input is a given Yiddish word. Unfortunately, my PHP class doesn't have this validation function, so I will need to add it to it as well. Again, no Yiddish. Haven't dived into it yet, but I expect I don't I like Option #3, and dislike option #2 even more. Please let me give this more thought. Oh yea, I forgot. A big one is create the JavaScript object which is used by the jQuery validation plugin, but I think/hope I have that one covered. I am lost. Probably me, but please elaborate
  6. My validation class. http://forums.phpfreaks.com/topic/291358-client-and-server-side-validation-passing-data-from-server-to-client/ I've created a method which does the same thing as every jQuery validation plugin method. Those are the tasks. Validate that a value is provided, validate that it is a valid phone number, etc. The main classes are Load Configuration JSON, Validate, Sanitize, etc.
  7. Maybe it has nothing to do with namespace. Say I have the following script. I have a bunch of tasks, and I want to be able to extend the class and modify or add new tasks. It would be nice if I could add more tasks without having to worry about conflicting with one of the core methods. How would this best be handled? Thanks class myGeneralClass { //A core method which cannot be changed final public function doThis($method) { $this->$method(); } protected function task1(){} protected function task2(){} protected function task3(){} protected function task4(){} } class mySpecificClass myGeneralClass { protected function task1(){} //Overide protected function task5(){} protected function task6(){} protected function task7(){} protected function doThis(){} //Error! } $obj=new mySpecificClass(); $obj->doThis('task5');
  8. I do need to learn about interfaces. I agree the design is a bit weird, and I have since rethought things.
  9. I have a class which has two general types of methods. Those which are used by the core class, and shouldn't be overridden. Those which are "used" by the methods described above, and these can be overridden and new methods can be added. They are all private or protected, and not public. For those used by the core class, I use the "final" keyword to prevent. I am not really versed in namespace, but this seems like where it might be used. Could I get a couple of pointers where to start? Thanks
  10. Is it possible to pass a callback function to other class's method? Is what I am attempting to do a bad idea? Thanks <?php class validate { public function __construct($data,$callback) { //A bunch of script goes here, and I don't want to duplicate it if($callback) { //Use $callback function to modify $data } } } class controller { public function savePage() { //A bunch of script goes here, and I don't want to duplicate it $validate=new validate(array('hello'),$this->callback); } } class controller_page1 extends controller { public function callback() { //script which will be used to modify future $data } } ?>
  11. You do not want to store the HTML and PHP script in your database. You want to store data in your database, and then use PHP to create the HTML.
  12. Thanks all, I think I am confusing myself, and overly complicating matters.
  13. Ended up keeping it really simple. Just replace the values. Used "{ }" and '{ }' as a deliminator so it is valid JSON. It will not allow a text value to be parsed in without quotes, so maybe I will add. final public function parse($template, array $values) { //return preg_replace_callback('/\{"{\ (\w+)\ \}\"/',function ($matches) use ($values) { $re = <<<RE / "{ (\w+) }" | '{ (\w+) }' /x RE; return preg_replace_callback($re,function ($matches) use ($values) { if(isset($values[$matches[1]])){ if(is_bool($values[$matches[1]])){$new=($values[$matches[1]]?'true':'false');} elseif(is_numeric($values[$matches[1]])){$new=$values[$matches[1]];} else{$new=$values[$matches[1]];} } else{$new=$matches[0];} return $new; }, $template); }
  14. This is going to be more difficult than I thought. Suppose I wish to parse the following JSON where noInvalid is true. { "rules":{ "name":{"required":true,{{ noInvalid?'"noInvalid":true,' }}"maxlength":90,"minlength":2 } } } I am looking for the following, however, my class incorrectly splits on the colon between "noInvalid" and true. Furthermore, the text above is not valid JSON, and is hard to troubleshoot. { "rules":{ "name":{"required":true,"noInvalid":true,"maxlength":90,"minlength":2 } } } I suppose I should either go back to creating it directly from PHP, or maybe get rid of my ternary operator, and go with: { "rules":{ "name":{"required":true,"noInvalid": "{{ noInvalid }}", "maxlength":90,"minlength":2 } } } Problem is to make the original file valid JSON, I need to put quotes around my variables which might cause problems with Boolean values { "rules":{ "name":{"required":true,"noInvalid": "1", "maxlength":90,"minlength":2 } } }
  15. Thanks for your reply QuickOldCar, As for more information, the text will be parsed as described by http://forums.phpfreaks.com/topic/291400-constructive-criticism-on-parsing-text/. So, store a big array in a single file to find all the time stamps? What if there were a million elements? Would checking if a file exists be faster? I suppose I will have problems seeing if one of a million files exists as well??? Why would I need to save the hash somewhere other than as the filename? Wouldn't I just parse and save the file with name $md_filename, and then the next filename/array I get, hash it and check if the file exists? Thanks again $filename="bla bla.txt"; $array=array('a'=>123,'b'=>'Hello'); $string=$filename.serialize($array); $md_filename=md5($string); //Save file using this name
  16. I need to parse some text similar to Twig templates, but MUCH more limited and error detection is not required. My reason for not using Twig is Twig seems overkill. All it needs to do is replace variables and simple ternary operators (unlike Twig, the ternary operators use ! instead of "not"). I would welcome any constructive criticism and/or recommended changes on how I implemented it. Thanks <?php date_default_timezone_set('America/Los_Angeles'); ini_set('display_errors', 1); error_reporting(E_ALL); /* Replaces all values surrounded by {{ }} deliminators. Handles direct variable. Multiple variables can be separated by the ~ symbol. Also does (non-nested) ternary operators: x?y, !x?y, x==1?y, x?'y', x?y:z */ $template=' Test1 Hello {{ firstname }} {{ lastname }}. Call me in {{ days_int }} or {{ days_string }} days.<br> Test2 {{ flag_int?"do this2" }}<br> Test3 {{ flag_int?"do this3":"do that3" }}<br> Test4 {{ value_int==5?"do this4" }}<br> Test5 {{ value_int==5?"do this5":"do that5" }}<br> Test6 {{ value_int==4?"do this6" }}<br> Test7 {{ value_int==4?"do this7":"do that7" }}<br> Test8 {{ value_int!=5?"do this8" }}<br> Test9 {{ value_int!=5?"do this9":"do that9" }}<br> Test10 {{ value_int!=4?"do this10" }}<br> Test11 {{ value_int!=4?"do this11":"do that11" }}<br> Test12 {{ value_int!=4 bla "do this12":"do that12" }}<br> Test13 {{ value_int==5?"do this5 to "~firstname:"do that5 to "~firstname }}<br> Test14 {{ !flag_int?"do this14" }}<br> Test15 Hello {{ firstname~" "~lastname~". How are things" }}.<br> '; $values=array( 'firstname'=>'John', 'lastname'=>'Doe', 'days_int'=>5, 'days_string'=>6, 'flag_int'=>true, 'value_int'=>5 ); $parser=new parser(); echo($parser->parse($template,$values)); class parser { public function parse($template,$values) { return preg_replace_callback('/\{\{\ (.+?)\ \}\}/',function ($matches) use ($values) { $ternary = explode("?", $matches[1]); if(count($ternary)>1) { //Ternary operator. $ternary[0] is the condition and $ternary[1] is the resulting value(s) $conditions=explode("==", $ternary[0]); if(count($conditions)>1){ //Equal Condition $cond=($this->getVal($conditions[0],$values)==$this->getVal($conditions[1],$values)); } else { $conditions=explode("!=", $ternary[0]); if(count($conditions)>1){ //Not Equal Condition $cond=!($this->getVal($conditions[0],$values)==$this->getVal($conditions[1],$values)); } else { //A flag $cond=($conditions[0]== "!") ? !($this->getVal(ltrim($conditions[0],'!'),$values)) : ($this->getVal($conditions[0],$values)); } } $options=(explode(':',$ternary[1])); return $cond?$this->getValues($options[0],$values):(isset($options[1])?$this->getValues($options[1],$values):null); } else {return $this->getValues($matches[1],$values);} }, $template); } private function getVal($s,$values) { return in_array($s[0],array('\'','"'))?substr($s,1,strlen($s)-2):(isset($values[$s])?$values[$s]:$s); } private function getValues($strings, $values){ $s=null; foreach(explode('~',$strings) as $string){ $s.=$this->getVal($string,$values); }; return $s; } } ?>
  17. I have the following script. doThis() is only used for this single use. Should I use an anonymous function instead? Reasons why or why not (i.e. speed, doesn't use up a function name, etc)? How should is it be implemented? Thanks $a=array(10,20,30); for ($x=0; $x<=10; $x++) { $z.=doThis($x,$a[1],50); } function doThis($a,$b,$c) {return $a+$b+$c;}
  18. I learned every one of them the hard way
  19. I have some fairly small text files (2K) which are parsed where certain deliminated fields are replaced with values provided in an associated array. There will typically be less than 5 replaced fields, and I plan on using preg_replace_callback to find and replace them. I am contemplating caching the files after being parsed (note that they will only be accessed by PHP, and not directly by Apache). Do you think doing so will provide any significant performance improvement? If I do go this route, I would like thoughts on how to proceed. I am thinking something like the following: Append the filename along with the serialized value of the array, and hash it using md5(). Store the parsed file using name "file_".$hash Get the modification time of the newly created file using filemtime(), and store the value in a new file called "time_".$hash. bla bla bla When the next request comes in to parse a file, create the hash again. If the file exists for the given hash name, and the time file matches filemtime(), use that file, else parse the original file. Is this a good approach?
  20. I don't want three rule sets, I only want one. I've had a difficult time keeping my client side and server side rules in sync, and wanted only to define them only once and have them apply to both. Is this not a common need, or am I unique? I therefore created a PHP class which accepts a valid JSON file which describes rules, messages, and sanitizing requirements. It has one public method which will create the object required for the jQuery validation plugin (rules and messages only), and a second public method which will server-side sanitize and validate the data, and provide any error messages if applicable. It also has a bunch of private methods which mimic the jQuery validation plugins methods. When the page is displayed, the controller will use the class to get the object required by the jQuery validation plugin, and send it to the client. When the form is submitted, the controller will use the class to sanitize the data and validate it per the rules, and get any error messages. It obviously deals which the rules with callbacks differently as needed. It works as intended. In regards to using "hacks like embedding JavaScript code within strings (which you appearently do). But that's a very poor solution.", okay I can accept that I should be doing something differently. My dilemma is how should I do so?
  21. Hi again, Anyone? I am just trying to utilize server generated client script the "right" way. Really the same question asked in http://forums.phpfreaks.com/topic/291241-how-best-to-send-php-data-to-a-javascript-client/, however, that post did not give any context, and thus the recommended solutions do not work as I indicate in this post (cannot include callbacks in JSON retrieved using Ajax). Thanks
  22. No experience with MVP and Cricket, but do have some general experience, and recommend the following: Spend some time up front to truly determine your user requirements, else you will find yourself going back and changing your database schema. Mocking up your pages will both help with your HTML/CSS as well as allow you to better understand your data requirements. After you fully understand your user requirements, spend some developing your database schema or you will find your self going back and changing your application. If you really understand "normalization", read up on it. And only after you have a good database schema, start your application. I would recommend a simple MVC design pattern. Don't use someone else's, but just make your own simple one. Use a single entry point into your site (index.php) where additional data is included in the URL or Post. Consider OOP. Use prepared statements and PDO! Strongly consider a template engine. I like Twig. Have fun!
  23. I wish to create validation rules once which are used both on the client and on the server. For instance, I will start off with the following PHP object: stdClass Object ( [rules] => stdClass Object ( [email] => stdClass Object ( [required] => 1 [email] => 1 [remote] => stdClass Object ( [url] => check-email.php [type] => post [data] => stdClass Object ( [username] => function() {return $( '#username' ).val();} ) ) ) ) [messages] => stdClass Object ( [email] => stdClass Object ( [required] => an email is required ) ) ) When the edit page is downloaded to the client, I will include this object in some format suitable to the client. The client will then use the jQuery Validation plugin (http://jqueryvalidation.org/) along with the validation object, and client side validate the page. When the form passes client side validation and is uploaded, PHP will use the same validation object to serverside validate the form (I have this part working as desired). My question is how should I pass this data to the client? Originally, I would just use PHP to write some JavaScript. exit('var myObj='.json_encode($myObj)); Note that when I json_encode the object, the value of $myObj->rules->email->remote->data->username is a string with quotes around it, however, I can easily use PHP to strip these tags before sending it to the client. As Jacques1 pointed out in http://forums.phpfreaks.com/topic/291241-how-best-to-send-php-data-to-a-javascript-client/, I should never ever use PHP to generate JavaScript, and should use AJAX to download the JSON directly. I tried doing the later, but found that a callback function could not be included in the JSON. Please advise on the best way to accomplish this. Thank you
  24. Thank you Kicken, your reply was very helpful.
  25. Thanks Jacques1, I see your point. Maybe with great effort I can prevent it, but why bother and just do it right the first time. I definitely crossed outside of the scope of PHP, however, still would appreciate comments on the following scope. How do we know myObj.myProp is defined when someFastScriptWhichAccesses_myObj.myProp.js is executed? <!DOCTYPE html> <html> <head> <title>Example</title> <script type='text/javascript'> var myObj={}; $.get( "someSlowURL.php", function( data ) { myObj.myProp=data; }, "json" ); </script> <script src="someFastScriptWhichAccesses_myObj.myProp.js" type="text/javascript"></script> </head> <body></body> </html>
×
×
  • Create New...

Important Information

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