PHP - Type Checking - What Is Your Take On This?
Hey
In my spare time, I am working on my PHP framework. Now, to help with development and quickly discover where I miss a type cast, I have adopted to check all parameters that are passed to a method using a function. For instance: public function __construct(&$target = null, $depth = 1){ $this->validateArguments( array(1 => 'int'), array(1 => $depth) ); And the code that triggers the exception: public function testPhpFreakType(){ $obj = 1; $p = new Xcms_DataStructures_Pointer($obj, "1"); } Code: [Select] 0: |--------------------------------------------------| 1: |--Exception: 4cfe2e86ca5970.22624423 - Full Trace | 2: | Tue, 07 Dec 2010 13:54:30 +0100 3: |-Class: 4: | Xcms_Exceptions_InvalidArgument 5: |-Message: 6: | Argument #1 of Xcms_DataStructures_Pointer:__construct() is no _null:int 7: | Stack offset: 3 8: | 9: |-Trace 10: | #0 D:\www\xcms_rev\core\exceptions\invalid.argument.helper.class.php(133): Xcms_Exceptions_InvalidArgumentHelper::factory(1, '_null:int', NULL, 2) 11: | #1 D:\www\xcms_rev\core\basic.class.php(80): Xcms_Exceptions_InvalidArgumentHelper::validateArguments(Array, Array, Array, 1) 12: | #2 D:\www\xcms_rev\core\data.structures\pointer.class.php(49): Xcms_Basic->validateArguments(Array, Array) 13: | #3 D:\www\xcms_rev\core\data.structures\pointer.test.php(73): Xcms_DataStructures_Pointer->__construct(1, '1') 14: | #4 [internal function]: Xcms_DataStructures_PointerTest->testPhpFreakType() 15: | #5 C:\xampp\php\PEAR\PHPUnit\Framework\TestCase.php(737): ReflectionMethod->invokeArgs(Object(Xcms_DataStructures_PointerTest), Array) 16: | #6 C:\xampp\php\PEAR\PHPUnit\Framework\TestCase.php(627): PHPUnit_Framework_TestCase->runTest() 17: | #7 C:\xampp\php\PEAR\PHPUnit\Framework\TestResult.php(629): PHPUnit_Framework_TestCase->runBare() 18: | #8 C:\xampp\php\PEAR\PHPUnit\Framework\TestCase.php(575): PHPUnit_Framework_TestResult->run(Object(Xcms_DataStructures_PointerTest)) 19: | #9 C:\xampp\php\PEAR\PHPUnit\Framework\TestSuite.php(766): PHPUnit_Framework_TestCase->run(Object(PHPUnit_Framework_TestResult)) 20: | #10 C:\xampp\php\PEAR\PHPUnit\Framework\TestSuite.php(742): PHPUnit_Framework_TestSuite->runTest(Object(Xcms_DataStructures_PointerTest), Object(PHPUnit_Framework_TestResult)) 21: | #11 D:\www\xcms_rev\core\testing\manager.class.php(83): PHPUnit_Framework_TestSuite->run() 22: | #12 D:\www\xcms_rev\core\testing\manager.class.php(56): Xcms_Testing_Manager->testClass(Object(ReflectionClass)) 23: | #13 D:\www\xcms_rev\cache\pkg\scripting\script_1.php(3): Xcms_Testing_Manager->run(Object(Xcms_Url_DefaultRequest)) 24: | #14 D:\www\xcms_rev\core\util.lib.php(340): include('D:\www\xcms_rev...') 25: | #15 D:\www\xcms_rev\core\packages\scripting\controllers\scripting.controller.php(66): Xcms_Util::sandboxedInclude('cache/pkg/scrip...', Array) 26: | #16 D:\www\xcms_rev\core\mvc\controllers\default.controller.php(210): Xcms_Packages_Scripting_Controllers_ScriptingController->execute(Object(Xcms_Packages_Scripting_Models_ScriptModel), Object(Xcms_Templating_Context)) 27: | #17 D:\www\xcms_rev\core\mvc\controllers\default.controller.php(170): Xcms_Mvc_Controllers_DefaultController->runScript(1, 0, Object(Xcms_Templating_Context)) 28: | #18 D:\www\xcms_rev\core\mvc\controllers\default.controller.php(132): Xcms_Mvc_Controllers_DefaultController->runScripts(0, 0, Array, Array, 1, 0) 29: | #19 D:\www\xcms_rev\index.php(15): Xcms_Mvc_Controllers_DefaultController->run() 30: | #20 {main} 31: |--------------------------------------------------| I think this speeds up my development quite a bit, because I can catch errors very early in the development process. I can give multipe possibilities of what is allowed for each parameter, not just a single possibility. Also, it is possible to register custom type/validity-checks on both global and local scope. One thing I do worry about, however, is the the performance. Of course, I could just make the funciton do nothing in production code, if it takes too much time, or I could write a script to remove all calls to that function. When I started learning python a while back, the concept to just code to interfaces instead of types seemed very intuitive and made my code much more flexible. Of course that is what I do with PHP as well, but I it's not entirely the same. So now, coming back at my PHP code and having introduced features of static languages such as type checking, I worry about whether that is the right approach. What are your thoughts on the matter? Similar Tutorialshi there, i am fairly new to OOPs in php, i get an error when i declare the argument type (as object) in a function and pass the same type (object). class eBlast { public static function getEmail(object $result) { return $result->email; } } $r = mysql_fetch_object($query); eBlast::getEmail($r); echo gettype($r); // outputs: object error is : Code: [Select] Catchable fatal error: Argument 1 passed to eBlast::getEmail() must be an instance of object, instance of stdClass given, called in C:\wamp\www\integra\client\pl_eblast\admin\send_emails.php on line 145 and defined in C:\wamp\www\integra\client\pl_eblast\app\app.eBlast.php on line 8 if i remove the type declaration in the function it works, but just would like to know why it shows error when pass the same type, also isnt mysql_fetch_object is the instance of stdclass? thanks in advance! Probably a stupid question . . .
The MIME type in my php.ini file is set to text/html:
default_mimetype = "text/html"But, because I use XHTML 1.0 Strict, the MIME type of my web pages is set to text/xml: <meta http-equiv="content-type" content="text/xml; charset=utf-8" />I should therefore change the php.ini MIME type to text/xml, right? Hello all, it's been a while! Good to be back. I am having trouble with a script I'm trying to modify to seach for domains with specific extensions. Now, I have never done any domain checking before and I'm a little bewildered. The script uses an array and checks the input against each extension using the array. Each line looks similar to: Code: [Select] '.com' => array('whois.crsnic.net','No match for'), What does the whois.crsnic.net mean? I assume it's a register/database of domains? can somebody please tel me how to make sure a field is a number? I have some error checking like if(empty($postcode)) { $errors[] = "Please enter your postcode"; } if(strlen($tel)<11) { $errors[] = "Please enter a phone number that is the correct length"; } But I dont know and cant find how to check for a number only. php5.2, mysql server5.02: if record exists,append random digit to end of information in rows column then add to database If user mike already exists and another mike is trying to create a user id I would like to keep the old mike record like it is, then add a new mike record, but add a unique digit to the end of the name mike before the record gets added to the database as a new row. Thank you kindly! Hey everyone.. I cleared the earlier doubt i have a new doubt in the same system.. <code> public function login($uname, $pass,$remember=false) { $result =$this->db->query("SELECT * FROM tbl_userauth"); $result->execute(); $resl=$result->fetchAll(PDO::FETCH_ASSOC); if ($resl[0]['username'] !=$uname || $resl[0]['password']!=$pass) { return $this->error("User not Found"); } else { $userID=$resl[0]['userid']; $_SESSION['userid']=$userID; $uname=$resl[0]['username']; $_SESSION['uname']=$uname; if(isset($_SESSION['userid'])) { header("location:dash.php"); } else { header("location:login.php"); } } </code> No this is my system actually i wanted to do session checking..Rite now when i am logging in the system i am able to log in but the same URL if i copy and paste in another browser i dont have to log in i am already logged in that's not rite Na?? I mean in another browser i should b logging in and then able to access in rite????What am i doing wrong???? PLease guide me through..Thank you.. I have written the code for email check, but how and where can I put the code to check if a username has been used twice? Thanks in advance. Code: [Select] <?php $servername = "localhost"; $username = ""; $password = ""; //validate fields if(!$_POST["username"] || !$_POST["email"] || !$_POST["password1"] || !$_POST["password2"]){ echo "<p> </p><p> </p><p> </p><br />Please fill the required fields, <p> </p><p> </p><a href='register.php'>Go to register page</a>"; //validate password }else if($_POST["password1"] != $_POST["password2"]){ echo "<p> </p><p> </p><p> </p><br />Please go back, PASSWORDS do not match! <p> </p><p> </p><a href='register.php'>Go to register page</a>"; //validate email }else if(!(eregi("^.+@.+\\..+$", $_POST['email']))){ echo "<p> </p><p> </p><p> </p><br />Please enter a valid EMAIL! <a href='register.php'><p> </p><p> </p>Go to register page</a>"; //validate captcha }else if(($_SESSION['security_code'] != $_POST['security_code']) || (empty($_SESSION['security_code'])) ){ echo "<p> </p><p> </p><p> </p><br />CAPTCHA CODE does not match! <p> </p><p> </p><a href='register.php'>Go to register page</a>"; }else{ $conn= mysql_connect($servername,$username,$password)or die(mysql_error()); mysql_select_db("genesis_members",$conn); // check if already registered $sql_check = "SELECT * FROM users WHERE email = '".$_POST[email]."'"; $result_check = mysql_query($sql_check,$conn) or die(mysql_error()); $row = mysql_fetch_assoc($result_check); if($row['id']){ echo "<p> </p><p> </p><p> </p><br />EMAIL already registered! <p> </p><p> </p><a href='register.php'>Go to register page</a>"; }else{ // insert in db $sql = "INSERT INTO users (username, email, password, company, phone, services) VALUES ('".$_POST[username]."', '".$_POST[email]."', '".$_POST[password1]."', '".$_POST[company]."', '".$_POST[phone]."', '".$_POST[services]."')"; $result = mysql_query($sql,$conn) or die(mysql_error()); echo "<p> </p><p> </p><p> </p><br /><h1>You Have Successfully Registered</h1>"; echo "<p> </p><p> </p><br /><a href='main_login.php'>go to login page</a>"; } } ?> Can someone help me to get this code working... Code: [Select] public function getBowlContents(){ if is_null($this->contents) { return "The bowl is empty!"; } else { return "The bowl contains " . $this->contents . " soup!"; } TomTees I coded small funny script I tested it in three hosting ww.rufaa.net dallawat.com/new ibuj.org but I don't know why in the first link, my script seem slow not like the other second and third links So basically I have a site, and on that site, I have a page that submits a form and updates a database. I have it set up so that someone can enter in Multiple values into a textarea, one on each line, and it will submit each of those values as a new row in the database, but for the life of me, I cannot figure out how to check those values against the actual users. It is basically a point system, where the staff can award points users of the site. But at the moment, a Staff member could enter in Jibberish, and it would insert that into the database, but I want it to check my users table to make sure the user exists before it inserts it into the database. here is my code: <?php include 'global.php'; echo $headersidebar; if ($_COOKIE['access'] == $accessstaff) { if(count($_POST)) { $array = preg_split('/(\r?\n)+/', $_POST['studentname']); foreach($array as $students) { $statusmsg = '<center><span style="background: #A6FF9E;">You have successfully submitted points to the database.</span></center>'; mysql_query("INSERT INTO points (giver, receiver, points, category, reason, date, status) VALUES ('{$_COOKIE['username']}', '{$students}', '{$_POST['pointamt']}', '{$_POST['pointcat']}', '{$_POST['pointreason']}', '{$date}', 'Validating')"); } } $addpointspage = $statusmsg . ' <form action="submit_points.php" method="post"> <table class="table" > <tr> <td colspan="10"> <h1><strong><center>Submit Points</center></strong></h1> </td> </tr> <tr> <td colspan="10" rowspan="100"> <center>Please remember to follow the house point limits when submitting house points.</center> </td> </tr> </table> <table class="table"> <tr> <td style="width: 15%;" valign="top"> Student Name:<br> <span style="font-size: 60%;">(List as many as you want; One per Line)</span> </td> <td colspan="10"> <center><textarea name="studentname" cols="60" rows="10"></textarea></center> </td> </tr> <tr> <td style="width: 15%;" valign="top"> Amount of Points: </td> <td> <input style="position: relative; left: 16px;" type="text" size="15" name="pointamt" /> </td> <td> Do not put anything that is not a number into this box. </td> </tr> <tr> <td style="width: 15%;" valign="top"> Point Category: </td> <td colspan="10"> <select name="pointcat" style="position: relative; left: 16px;"> <option SELECTED value="">-------</option> <option>Class Work</option> <option>Class Exam</option> <option>Extra Work</option> <option>Contests</option> <option>Teacher\'s Assistant</option> <option>Negative Points</option> </select> </td> </tr> <tr> <td style="width: 15%;" valign="top"> Reason: </td> <td colspan="10"> <input style="position: relative; left: 16px;" name="pointreason" type="text" size="80" /> </td> </tr> <tr> <td> </td> <td colspan="10"> <input style="position: relative; left: 16px;" type="submit" value="Submit Points" /> </td> </tr> </table </form> '; } elseif (1==1) { $addpointspage = $accessdenied; } echo ' <!-- start content --> <div id="content"> <div class="post"> <div class="entry"> <p><strong>' . $addpointspage . '</p> <p class="links">' . $addpointslink . '</p> </div> </div> </div> <!-- end content --> <div style="clear: both;"> </div> </div> <!-- end page --> </div>'; echo $footer; ?> I am fairly new to PHP, so I would appreciate any help someone could give me; I am not too good with arrays and such, so this one has got me stumped. I have textfield for signature in my form, I m checking if the signature was sent ( if(!empty($_POST['signature'])) and if it's not empty I m putting it into the db. The problem is that, I have noticed a greek user has entered something in greek letters, and function could not deal with it and saved it as it is.( DB field supports greek charset ) I just want to allow english and german chars with special chars ( ",',< etc. ) , no other charset like greek. How can I do that? any function for this purpose ? I don't know precisely how to put it so i will give an example: suppose you have a search form with input fields for: -an age range, -a data range, -for the sex, -postal code as soon as the user would fill in one of these input fields, a query should be generated including a condition doing something with the inputted value. For example, the user fills in maxAge, the the query should say: SELECT * FROM table WHERE age >= maxAge; Filling more than one criterion then would do .= " AND criteria (condition) inputvalue " etc... My question comes to the part about: how to check if there is already a WHERE in the clause and how to put WHERE or AND for every criterion. Since doing like above, i won't be able to search for another criterion if i don't select maxAge first because then there would be no WHERE in the sql clause. Hopefully i've put it clear thanks in advance $characterIDs = explode(',', $_POST['characterIDList']); After the explode I want to take all those values and do a select statement in a database table for any of the values that match any of the values inside that variable variable. Not sure how to do this since there is no limit to how may there could be. Hi friends I have following code Code: [Select] function UseOfSSL($domain_name) { $site = ($domain_name); $port = 443; $fp = fsockopen($site,$port,$errno,$errstr,10); if(!$fp) { echo "Not Installed"; } else{ echo "Yes, it is installed"; fclose($fp); } } If domain name from $domain_name has installed SSL, it will show it is installed else not installed. Problem is that I tried this with both types of sites, those who are using SSL and those who are not and always, it says Yes, it is installed. 443 is used because https uses port 443 What is the cause ? I have two arrays of keywords that I'm pulling from the database. I'm wanting to compare those two arrays and see if ANY of the contents are the same, if they are push that result into another array for later use. while($row_rsCWGetupsell = $cartweaver->db->db_fetch_assoc($rsCWGetupsell)) { $b = array_unique(array_filter(explode(",", preg_replace( '/\s*/m', '', $row_rsCWGetupsell["product_keywords"])), "strlen")); $a = array_unique(array_filter(explode(",", preg_replace( '/\s*/m', '', $row_rsCWGetProduct["product_keywords"])), "strlen")); if($a IN $b) // <--- this is where the comparison should be! $list[] = $row_rsCWGetupsell; } Hello! Does anyone know an effective way to track inactive idlers in daily basis? So that it will count the amount of days no data has been posted to the table. E.g. User posts latest data and inserts timestamp 1282228120 which reads Thursday, August 19th 2010, 14:28:40 (GMT) The days for inactivity should output as 8 days because no data has been posted from 20th August to today - 28th August. Anyway I can achieve this? Any information is appreciated, thanks. Scenario: each row contains an ID, title, description, price, and up to 5 images. There are not always 5 images stored in each row. The images are stored as a file path which is then pulled out of the DB and used to display an image via HTML. I need to do some sort of loop/check that looks at the contents of a particular row (actually all rows in this particular table) and then decide how many times to loop through the images to display them all correctly on the webpage. I could statically set a variable for each column but then it would have a space for an image but nothing would show. I really want this to be able to only load the images that are stored in the DB. Any help on how I can go about this? thanks -beemer Okay I need some help. I want to check a MySQL DB and then if it says 0 then don't do anything if it says anything else echo out what's there. I have tried for about a hour now. Hi, I'm creating an upload section that limits users to upload the following file types: .zip .rar .doc .jpeg .gif When getting the type for .pdf files, it comes up as: application/force-download and for .rar files it comes up as: application/x-download If I do a check that says: if ($type=="application/force-download" || $type=="application/x-download") then will users only be able to upload .PDF and .RAR files? I'm assuming these two types will allow other formats as well. If this is the case, how can I check the extension of the file before the user is able to upload it. I was thinking of somehow capturing the last 3 letters of the filename, and then doing the check that way, except I'm not sure how to go about this. Any insight appreciated! |