PHP - Url Router Try/catch Block
I have the code below working perfectly, but I was wondering if there is a more eloquent way to write this, specifically handling the exceptions...
This creates an object of a Router Class that parses my clean URLs into a Controller name, method name and the rest are arguments. So for example: www.domain.com/users/view/profile/bobsmith would route to the Users Controller, and find the viewUsers method and pass the arguments "profile" and "bobsmith" to it, and the method would take it from there... works great. That explains what this code does. My only question is if there is a cleaner way to handle the exceptions, so I don't have "throw new exception" written four times. Thoughts? Or is it good to go? $rawURL = getPageURL(); $router = new Router($rawURL,$rootDIR); $controller = $router->getController(); $method = $router->getMethod(); $arguments = $router->getArguments(); try { // check controller exists and set controller path // if ((isset($controller) && ($controller != ''))) { $controllerPath = APPLICATION_PATH . "controllers/" . $controller . ".class.php"; // check controller path exists // if (file_exists($controllerPath)) { // set method name and check method exists // if ((isset($method) && ($method != ''))) { $methodName = $method . ucfirst($controller); if (method_exists($controller, $methodName)) { // test it out // $test = new $controller(); $response = $test->$methodName($arguments[0]); echo $response; } else { // method_exists failed // throw new Exception("That method does not exist foo!"); } } else { // method was not found in URL // throw new Exception("No method name was given foo!"); } } else { // file_exists failed // throw new Exception("That controller does not exist foo!"); } } else { // controller was not found in URL // throw new Exception("No controller name was given foo!"); } } catch (Exception $e) { // spit it out foo // echo $e->getMessage(); } Similar TutorialsSo I'm debating whats the best method. I'm aware that catch/blocks should be used in exceptional cases but what if it saves me from having 4 nested if/else conditions? The following is code for an xbox registration site Code: [Select] try { // check code is valid $c1 = $this->input->post('code1',true); $c2 = $this->input->post('code2',true); $c3 = $this->input->post('code3',true); $gt = $this->input->post('gamertag',true); $pass = $this->input->post('password',true); if( $c1 == '' || $c2 == '' || $c3 == '') { throw new FormError("Authorization code invalid."); } // check db for code validation $q = $this->db->query("select * from `codes` where `activated` = 0 and `code` = ".$c1.$c2.$c3." limit 0,1"); if($q->num_rows() != 1) { throw new FormError("Authorization code invalid."); } $r = $q->row_array(); $email = $r["recipient_email"]; $codeGt = $r["gamertag"]; // check valid gamertag $q = $this->db->query("select * from `users` where `gamertag` = '".$gt."'"); if($q->num_rows() > 0) { throw new FormError("Gamertag already exists."); } // validate gamertag /w inputted gamertag if(strtolower($codeGt) != strtolower($gt)) { throw new FormError("Gamertag Invalid"); } $this->_createAccount($email,$pass,$gt); // show register-thanks screen $this->load->view("register-thanks",$data); $success = true; } catch (Exception $e) { $data['error'] = $e->getMessage(); } Routing issue: Cannot see a wireless router from a wired router on the same network. I have a very simple home network with a broadband connection from my ISP coming into the house with their 4-port modem/router (192.168.1.1) on it. From there I have 2 ethernet connections, one each to a wired router(192.168.1.7) and a wireless router(192.168.1.2) The wired router has one connection to my Debian Squeeze PC (usually 192.168.1.24) the wireless router has 2 or 3 connections to a PC and a tablet (usually something like 192.168.1.100 & 101... etc) The internet from my PC (192.168.1.24) is working fine through the wiired router, and the PC & tablet on the wireless router are working fine too. My problem is that I want to be able to 'see' the wireless router from my PC and I cannot connect to it or 'see' any of the connected devices. Maybe I am misunderstanding how this networking thing should work, but I think it should be possible to do this. Can anyone help me please? a) I have turned off iptables # iptables -F # iptables -L Chain INPUT (policy ACCEPT) target prot opt source destination Chain FORWARD (policy DROP) target prot opt source destination Chain OUTPUT (policy ACCEPT) target prot opt source destination Chain logdrop (0 references) target prot opt source destination b) ifconfig -a eth1 Link encap:Ethernet HWaddr fc:75:16:e1:b8:13 inet addr:192.168.1.24 Bcast:192.168.1.255 Mask:255.255.255.0 inet6 addr: fe80::fe75:16ff:fee1:b813/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:9123 errors:0 dropped:0 overruns:0 frame:0 TX packets:9696 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:1100294 (1.0 MiB) TX bytes:844749 (824.9 KiB) Interrupt:20 Base address:0xde00 lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:2740 errors:0 dropped:0 overruns:0 frame:0 TX packets:2740 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:247076 (241.2 KiB) TX bytes:247076 (241.2 KiB) b) I have added routes(I think) to the other router from my PC # route -n Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 192.168.1.1 192.168.1.7 255.255.255.255 UGH 0 0 0 eth1 192.168.1.2 192.168.1.1 255.255.255.255 UGH 0 0 0 eth1 192.168.1.0 0.0.0.0 255.255.255.0 U 0 0 0 eth1 0.0.0.0 192.168.1.7 0.0.0.0 UG 0 0 0 eth1 # arp -an ? (192.168.1.7) at 00:14:6c:0b:1d:da [ether] on eth1 ========================================== from the other end, the wireless router when I connect a wired connection to a laptop I get the following similar picture (the broadband router) # ping 192.168.1.1 PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data. From 192.168.1.107 icmp_seq=2 Destination Host Unreachable From 192.168.1.107 icmp_seq=3 Destination Host Unreachable From 192.168.1.107 icmp_seq=4 Destination Host Unreachable ^C --- 192.168.1.1 ping statistics --- 6 packets transmitted, 0 received, +3 errors, 100% packet loss, time 5009ms pipe 3 (the wireless router) # ping 192.168.1.2 PING 192.168.1.2 (192.168.1.2) 56(84) bytes of data. 64 bytes from 192.168.1.2: icmp_req=1 ttl=64 time=0.378 ms 64 bytes from 192.168.1.2: icmp_req=2 ttl=64 time=0.381 ms 64 bytes from 192.168.1.2: icmp_req=3 ttl=64 time=0.452 ms ^C --- 192.168.1.2 ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 1998ms rtt min/avg/max/mdev = 0.378/0.403/0.452/0.041 ms # arp -an ? (192.168.1.1) at <incomplete> on eth0 ? (192.168.1.2) at b0:48:7a:67:ea:7a [ether] on eth0 # route -n Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 192.168.1.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0 169.254.0.0 0.0.0.0 255.255.0.0 U 1000 0 0 eth0 0.0.0.0 192.168.1.2 0.0.0.0 UG 0 0 0 eth0 # ifconfig eth0 Link encap:Ethernet HWaddr 00:16:d3:bb:64:09 inet addr:192.168.1.107 Bcast:192.168.1.255 Mask:255.255.255.0 inet6 addr: fe80::216:d3ff:febb:6409/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:5858 errors:0 dropped:0 overruns:0 frame:0 TX packets:5491 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:7093094 (6.7 MiB) TX bytes:666534 (650.9 KiB) Interrupt:17 lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:121 errors:0 dropped:0 overruns:0 frame:0 TX packets:121 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:10032 (9.7 KiB) TX bytes:10032 (9.7 KiB) Edited by Zane, 28 December 2014 - 01:06 AM. hey guys im after a bit of advise on routing within my framework please.
now i've created a route:
account/verify/email-address/:email_address/activation-key/:activation_key
which will be then interpurated into
account/verify/email-address/destramic-at-hotmail-dot-com/activation-key/12345
now my question is having a email address in a url is good idea?
if so i can decode the :email_addres parameter in the route like so:
$router->add_route('account/verify/email-address/:email_address/activation-key/:activation_key', array('controller' => 'users', 'action' => 'activate_account', 'decode' => 'email_addres' => 'string_to_email') ));would like your thoughts on this please guys (go easy)...if not a user_id would be sufficient i suppose thanks I was trying to use one of the many PHP routers like klein, when I kept hitting an issue.
The issue was my root folder was a subdirectory of the www folder .
So instead of requesting http://localhost/index.php (as one would if the index.php was located in /var/www) I was requesting http://localhost/issues/web/index.php (index.php in /var/www/issues/web)
Naturally the router looked for a match for the whole path(issues/web/index.php) instead of just the relative path(/index.php) Which caused it not to match anything !
Questions:
1. Is this a viable solution for this problem (Got this from https://github.com/c...ry-Installation? Any possible gotchas I should be on the look out for ?
$base = dirname($_SERVER['PHP_SELF']); // Update request when we have a subdirectory if(ltrim($base, '/')){ $_SERVER['REQUEST_URI'] = substr($_SERVER['REQUEST_URI'], strlen($base)); } //initialize router code.2. This must be an extremely common situation! How do people deal with this ? OR is it simply not common for routers to be installed to subfolders and called from there ? Thanks Hi Guys, I'm a bit new to php coding, so dont really know what the best way to code this up. I want to make a router configuration page, such as it shows the link status (ip/gatewatway etc) and also have input selections such as to turn on/off wifi / dhcp etc. Ideally I would like the data stored and written to a text file as the php server is running on a linux arm embedded system. At present I have been able to read back from a text file the corresponding values for each of the status information (these are stored on a seperate line), but I'm having difficulty writing and reading the input selection boxes, such as when the dhcp is disabled I need it to write to a file that its been disabled and refresh the page to allow entry of the static ip box and then when the apply button is pressed the value is written to the file. This may be out of my depth, hopefully someone could give me some pointers. I feel that the text file might not be the best way of storing and recalling values but I don't know of another way. Many Thanks Tim Is there any way to catch warnings without defining a warning handler? Example: try { $settings = parse_ini_file( 'main.ini' ); } catch( ErrorException $e ) { throw new ErrorException('No main configuration file found for webiste', '0003'); } Only ends up throwing a warning if the file doesn't exist. I want to catch it and throw an error. i keep getting this error Fatal error: Uncaught OAuthException: Error invalidating access token: Session does not match current stored session. This may be because the user changed the password since the time the session was created or Facebook has changed the session for security reasons. thrown in /home/sites/socialnewsoffice.com/public_html/sm-login/social-media-connect/facebook/base_facebook.php on line 1050 how can i catch and display this warning to the user? Hey Guys. I am across this in a book and I am having a hard time understanding how I can try/catch this expception
The code below will throw an exception if I add an unit object into Archer or LaserCannon object.
Here is a quick example
class UnitException extends Exception{} abstract class Unit{ function AddUnit(Unit $unit){ throw new UnitException(get_class($this)."is a leaf"); } function removeUnit(Unit $unit){ throw new UnitException(get_class($this)."is a leaf"); } abstract function bombardStrength(); } class Archer extends Unit { function bombardStrength(){ return 4; } } class LaserCannonUnit extends Unit { function bombardStrength(){ return 44; } } $laser_cannon = new LaserCannonUnit(); $laser_cannon->AddUnit(New Archer()); // This is not allowedWhen I run the client code I get the following error message Fatal error: Uncaught exception 'UnitException' with message 'LaserCannonUnitis a leaf' Can any please help me understand this?? Thanks! Hello guys. Is it possible to catch a fatal error and then do something? What I need to do is to catch the error and run the script a second time, before the first execution ends. Kind regards and thanks for advance. How can i catch this exception and run the catch code , and stop the error message displaying on the webpage . Thanks <?php try{ echo $_SESSION['btn']; } catch(Exception $ex) { $_SESSION['btn'] = "Check Available"; echo $_SESSION['btn']; } ?>"/> Please help I want to use PEAR if it's installed and the regular "mail()" function if not. But to check for PEAR being installed, I can't check for the class PEAR existing because I have to include "Mail.php" first. The problem is that even though this statement works perfectly: Code: [Select] include_once "Mail.php"; This will ALWAYS be false: Code: [Select] if ( file_exists( "Mail.php" ) ) ... So how do I check for PEAR? If I just include the file, it throws a warning error that I can't seem to catch in a try..catch. I am new to the Laravel Framework, doing an internship and at the very end.. I need some assistance please with some try catch error, Its supposed to throw an error if the site name is already in the database.. If someone could help me please and thank you ..
```
public function create() { return View::make('edit.create'); } public function edit( $clientsite ) { return View::make('edit.edit', compact('clientsite')); } public function saveCreate() { $input = Input::all(); try { $clientsite = new ClientSite; $clientsite->siteName = $input['siteName']; $clientsite->description = $input['description']; $clientsite->launchDate = $input['launchDate']; $clientsite->save(); //ClientSite::whereSiteName($clientsite->siteName)->first(); ClientSite::where('siteName', $clientsite->siteName)->first(); $clientID = $clientsite['clientID'];//getting clientID for use in join query //queries for retrieving features of each group for the selected client $clientFeatures = DB::table('features')->join('clientFeatures', function($join) use($clientID) { $join->on( 'clientFeatures.featureID', '=', 'features.featureID') ->where('clientFeatures.clientID', '=', $clientID); })->get(); $groupIDs = array(); foreach ($clientFeatures as $c) { $groupIDs[] = $c->groupID; } catch(\Illuminate\Database\QueryException $e) { return View::make('profiles.clientProfiles')->with('clientsite',$clientsite) ->with('groupIDs',$groupIDs) ->with('clientFeatures',$clientFeatures) ->with('status','<strong>'.$siteName.' Site already exist!</strong>'); ; } ``` https://github.com/webdevdea/MyDyn ( i have not pushed these changes because I have an error ) I have been reading most spambots use UTC-12 timezone and PHbb has a hack to block UTC-12, but I dont have the file I am looking to get the UTC ( or GMT ) time from the referring page any ideas? how to block someone from visiting my page using ip adress ? this is the case if someone come to my site then we record the ip address and put it into database. when the visitor come again with the same IP they cannot see my page (block them) and redirect it to somewhere page. How is it that a site can forward to my site without a trace? www.2mysite.com is forwarding traffic to www.mysite.com but $page_name = $_SERVER['HTTP_REFERER']; echo $page_name; does not show www.2mysite.com as the referring site...how does one hide this? Help? It's one of those days after a long weekend and a rainy morning. Simply trying to get the correct message depending on the variable's value if($a = 'one'){ echo "POOR";} if($a = 'two'){ echo "GOOD";} if($a = 'three'){ echo "VERY GOOD";} if($a = 'four'){ echo "EXCELLENT";} Not sure if I need to use ==, extra quotes, or ELSEIF for the best result.
I draw contents from a database. Some of the texts contain a footnote, which is formatted using a div class. Following the HTML of this:
<div class=""footnotes""> <br> <hr align=""left"" noshade=""noshade"" size=""1"" width=""150"" /> <blockquote> <a href=""#f1"" name=""fn1""> <span class=""superscript""> * </span> </a>Some footnotetext</blockquote></div>Since my bibliography uses data from the database as well, the footnote now appears before the references, but I would like it at the very bottom of the page. I was thinking of using preg_replace in order to separate the textfield into two variables, one for the text itself, the other one for the footnote (it is always just one) and integrate after the bibliography is compiled. Unfortunately, it seems that the preg_replace does not work. It always displays the whole content of the textfield. Here's the PHP: $text = preg_replace('/(.*)(\div class=\"footnotes\"\>.*?\<\/div\>)/s', '$1', $result['text']);$footnote = preg_replace('/(.*)(\div class=\"footnotes\"\>.+?\<\/div\>)/s', '$2', $result['text']); echo '<div align="justify"><span style="font-family:Georgia;font-size:16px;">' . $text; ***BIBLIOGRAPHY*** ... echo $footnote;Maybe someone has an idea how to deal with that. I tried it on phpliveregex. There search string works fine. Many thanks for any help. In PHP? Let's say I'm going off of: width x height So this is 2x1 2x1 2 blocks across, 1 block height. How do I check this against other blocks in php to see if the 2x1 will overlap another set of dimensions dynamically? Am I over thinking this? Edited by Monkuar, 24 January 2015 - 12:08 PM. Hi, I want that user can only read my article but can't download it. neither with save page as or with view source, even not with selecting text. and copy and paste. is there any solution in php to do that. Please help Thanks |