PHP - Code Review For Custom Routing Rules
In a project that I'm working on I can specify routing rules, which is somewhat similar to mod_rewrite but in PHP. It's currently set up to use full regular expressions, but it's kind of overkill. I'm trying to convert it to use routing rules similar to some of the php frameworks I've seen. The code I've written up below is working, and while it's unlikely that I would need anything more complex, I'm wondering if anyone would like to comment, offer suggestions, or offer criticisms. This little piece of code is just a part of a bigger routing class, but this is the code that I'm concerned with. Thanks.
<?php $cfg['routes'] = [ 'cars/(:any)/(:any)/(:num).php' => 'cars/$3/$1/$2', 'default_route' => 'cars/index', 'trucks/parts?year=(:num)' => 'parts/trucks/$1', 'vans/articles(:any)' => 'articles$1' ]; $uris = [ 'cars/toyota/tercel/2014.php', # /cars/2014/toyota/tercel 'default_route', # /cars/index 'trucks/parts?year=2014', # /parts/trucks/2014 'vans/articles?p=42342' # /articles?p=42342 ]; $i = 0; foreach( $cfg['routes'] as $k => $v ) { $k = '|^' . preg_quote( $k ) . '$|uiD'; $k = str_replace( [ '\(\:any\)', '\(\:alnum\)', '\(\:num\)', '\(\:alpha\)', '\(\:segment\)' ], [ '(.+)', '([[:alnum:]]+)', '([[:digit:]]+)', '([[:alpha:]]+)', '([^/]*)' ], $k ); echo '<br />' . $uris[$i] . '<br />' . $k . '<br />'; if( @preg_match( $k, $uris[$i] ) ) { echo preg_replace( $k, $v, $uris[$i] ) . '<br /><br />'; } $i++; } Similar TutorialsThis topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=354376.0 Hey Guys, So I'm stuck on a particular line of PHP for woocommerce the code I have hear works for doing 2 levels of discount. 1 - The discount code in woocommerce coupon settings gives - 10% off for products in category named "10OFF" - Coupon settings are in the image below 2. This code here then allows the same coupon to give 15% off off products in category named "15OFF" 3. What I can't seem to work out, is how to add another layer to this, where the same coupon will give 35% off products in a category named "35OFF" I get the feeling this is something really super obvious to someone who knows more about PHP coding than myself! I've tried multiple IF statements, that breaks the whole thing. I'm confident Creating multiple Categories is the way forward. I just can't work out how to add the new categories to the code that doesn't suddenly break the whole thing again stopping all discounts being taken off each item. Any advice would be hugely appreciated! I know the Code could be a lot neater in general, but I'm really new to PHP Kind Regards to all Liam add_filter( 'woocommerce_coupon_get_discount_amount', 'alter_shop_coupon_data', 20, 5 ); function alter_shop_coupon_data( $round, $discounting_amount, $cart_item, $single, $coupon ){ //Settings// $coupon_codes = array('bigsavings'); // Product categories at 15% $product_category15 = array('15off'); // for 15% discount $second_percentage = 0.015; // 15 % // Code// if ( $coupon->is_type('percent') && in_array( $coupon->get_code(), $coupon_codes ) ) { if( has_term( $product_category15, 'product_cat', $cart_item['product_id'] ) ){ $original_coupon_amount = (float) $coupon->get_amount(); $discount = $original_coupon_amount * $second_percentage * $discounting_amount; $round = round( min( $discount, $discounting_amount ), wc_get_rounding_precision() ); } } return $round; }
Edited May 17 by liamhluk Additional info on what I've tried already i want the code for review approval platform (costumer reviews for a product )and in backend editing the code and updating it if(get_images_for_delete($username, $newid, $mysqli) !== FALSE){ // WE are dealing with images $images = get_images_for_delete($username, $newid, $mysqli); $sourceBucket = "***********"; $targetBucket = "***********"; foreach($images as $image){ // copy our object $aws = new s3; $aws = $aws->copyObject($targetBucket, $image, $sourceBucket, $image); // delete our object $aws_delete = new s3; $aws_delete = $aws_delete->deleteObject($image); // copy our (thumbnail) object $aws2 = new s3; $aws2 = $aws2->copyObject($targetBucket, "thumb_".$image, $sourceBucket, "thumb_".$image); // delete our (thumbnail) object $aws_delete2 = new s3; $aws_delete2 = $aws_delete2->deleteObject("thumb_".$image); }Is my code. Do I need to declare so many new s3 classes? All the methods are within the same class. Not sure if this is the correct way to go about it. $username = $loggedInUser->username; // This is the logged in username $time = time(); $makedir = $username.'_'.$time; $var = getcwd(); $var = str_replace('\users', '\imageuploads', $var); $dirlocation = $var."\\".test_directory($username, $mysqli); function test_directory ($username, $mysqli) { $stmt = $mysqli->prepare("SELECT Temp_Directory FROM uc_users WHERE user_name LIKE ?"); $stmt->bind_param("s", $username); $stmt->execute(); $stmt->bind_result($Tempdir); while ($stmt->fetch()){ return $Tempdir; } } if((!empty(test_directory($username, $mysqli))) && is_dir($dirlocation)){ //echo "this is it"; $thedirectory = $dirlocation; } if(empty(test_directory($username, $mysqli))){ //echo "it's not a directory"; $newdir = $var."\\".$makedir; $query = mysqli_query($mysqli, "UPDATE uc_users SET Temp_Directory='$makedir' WHERE user_name='$username'"); if(!$query){ //echo mysqli_error($mysqli); } mkdir($newdir); //security chmod($newdir, 0644); $thedirectory = $newdir; } if(!is_dir($dirlocation) && (!empty(test_directory($username, $mysqli)))){ //echo "third one"; mkdir($dirlocation); chmod($dirlocation, 0644); $thedirectory = $dirlocation; } Ok, so what I'm doing here is testing to see whether a a record exists of the user having a folder in the MySQL database. Then, if it does, make sure that a folder exists at that location. If there is no folder, we create one for the user. If there is already a folder, we leave it alone. This is for image uploads, and $thedirectory, is where we upload images later on in the script. Hope that makes sense. The code seems to work. But how can I improve it and make it more robust? Or should I just leave it alone? Should I return FALSE from the function for better reliability over empty()? I have a problem with the below code: Code: [Select] <?php $sql_ranks = ("SELECT vtp_members.id, vtp_members.name, vtp_members.teamleader, teams.team_name, count(vtp_tracking.id) surfs FROM vtp_members, vtp_tracking, teams WHERE vtp_members.team_id=".$_GET['t']." AND vtp_tracking.credit_members_id=vtp_members.id AND vtp_tracking.action_date > '$last_sunday' AND vtp_tracking.action_date < '$next_sunday' GROUP BY teams.team_name ORDER BY surfs DESC"); $rsranks = mysql_query($sql_ranks); echo "<br><table align='center' valign='top' border='0' width='300px'> <tr><td colspan='2' align='center'><font size='2px'><b>Team Rankings (Current Week)</b></font></td></tr> <tr><td><font size='2px'><b>Team</font></td><td align='right'><font size='2px'>Total Surfs</font></td></tr>"; while ($row = mysql_fetch_array($rsranks)) { echo "<tr><td><font size='2px'><b>".$row[team_name]."</font></td><td align='right'><font size='2px'>".$row[surfs]."</font></td></tr>";} echo "</table>"; ?> Problem is that the last output (".$row[surfs].") is the same for all teams. It seems it is not making a total of all id's and not per team_name. anyone can see what I am doing wrong. I need to sort by team_name and the surfs should display the total of the members with team_id is ".$_GET['t']." Hello, I'm learning how to write simple CMS and I'd like it to support page aliases. So that instead of http://www.myweb.com/?id=123 I could use http://www.myweb.com/some-page for example. I don't want to use rewrite rules in .htaccess but I'd like to do it similarly as Drupal. I understood Drupal redirects 404 page not found error to index.php and then somehow handles it. Can you advise how to do it please? Or is there any tutorial or example available? Thank you in advance! Vojta Hello I have: function MailTemplate($Type) { ob_start(); include 'mailtemplate.php'; $x=ob_get_contents(); ob_end_clean(); return $x; } Session variables are parsed; however calls to functions do not seemed to work. I'm making a call to a function that returns a value, but this value is not output in the final html. I have double checked that function is available in the template. any suggestions ? Hi I relatively new to MVC and trying to understand it all by coding my own MVC framework. I already have coded my (own variant) MVC application: a router calling controllers each creating CRUD(L)* forms (views) onto separate db tables. Now I want to create a dashboard with multiple forms each modifying a separate database table. I already have the ability for one controller to call another controller ad infinitum. However when I press "modify" on one of the forms I do not know how to route (call the router) to rebuild the dashboard restoring all the other forms (ie other controllers) to the same state they were in when my target form requested a modification. Basically I don't know how to go about routing in a hierarchical or nested MVC framework. Should I design a complex (non-linear tree-like) URL request that captures the state of my dashboard and have a very complex router that can decode it? Should each action be idempotent or should I use state in the session to make the request URL easier? *CRUD(L) a view with different forms for CRUD and L(ist) operations each invling different controller methods. I have tried searching under "HMVC" (but that seems to mean "modules") and "nested MVC" but for both terms I mostly get referred to established frameworks. Cheers GAJ Okay, so now I need help evolving my Log-In system... Up until now, the only place a user could log-in was on a given Article page if they wanted to add a comment to the Article. To accommodate that feature, I was setting the "Return To Page" only in my "article.php" script like this... Code: [Select] $_SESSION['returnToPage'] = $_SERVER['SCRIPT_NAME'] . '?title=' . $articleTitle; However, now I want to expand things. I'm growing increasingly confused about how to manage where to route people when they long-in?! 1.) Sometimes a user will Log-In and want to return where they were at (e.g. index.php, article1234.php) 2.) Sometimes a user might want to continue down a path (e.g. Checking Out, Registering for a Workshop, Sending a Message) Is there some kind of strategy to handle this? (nothing over complex, but there must be some Best Practices that work?! Debbie Hi everyone, I am a beginner web designer and a novice php user. I am a regular forum user and understand that you should always do a search and try to find the answer yourself but I have done that and didn't get any results (or I didn't understand them!). So I ask for some assistance - either you can tell me the code or link me to the correct answer. I am working on a website that I have built a enquiry form for and it has a php script for it. I have managed to get the form running properly and got the reCaptcha working correctly (with a custom error page) but I do not understand how to add custom error pages for incomplete email addresses, empty email addresses, or for a blank form? I tried using the same tactic I used for the reCaptcha error page but it didn't work - probably because I was guessing and just tried it in a bunch of different places. The error msg that displays now is just a plain white page with the msg - Email address is invalid appearing at the top left. While this is suitably functional it doesn't really look like much so I want to build a custom page for each error that could happen. So the code is below - if anyone can point a beginner in the right direction I would be super happy. :mrgreen: if you need anymore code or other details just tell me and I will post them up. The url of the form page is http://www.sunsolutionshomeimprovement.com/onlinesales.html This is the code I think you will need - I got it from a demo php script that I have modified. As I said I don't have much clue what I'm doing so I just posted it exactly how it looks - if I over did it I apologize... :oops: 68.// Validate email field. 69. 70.if(isset($_REQUEST['email']) && !empty($_REQUEST['email'])) 71.{ 72. 73.if(preg_match("/(%0A|%0D|\n+|\r+|:)/i",$_REQUEST['email'])){$errors[] = "Email address may not contain a new line or 74.a colon";} 75. 76.$_REQUEST['email'] = trim($_REQUEST['email']); 77. 78.if(substr_count($_REQUEST['email'],"@") != 1 || stristr($_REQUEST['email']," ")){$errors[] = "Email address is invalid";}else{$exploded_email = explode("@",$_REQUEST['email']);if(empty($exploded_email[0]) || strlen($exploded_email[0]) > 64 || empty($exploded_email[1])){$errors[] = "Email address is invalid";}else{if(substr_count($exploded_email[1],".") == 0){$errors[] = "Email address is invalid";}else{$exploded_domain = explode(".",$exploded_email[1]);if(in_array("",$exploded_domain)){$errors[] = "Email address is invalid";}else{foreach($exploded_domain as $value){if(strlen($value) > 63 || !preg_match('/^[a-z0-9-]+$/i',$value)){$errors[] = "Email address is invalid"; break;}}}}}} 78. 79.) 80. 81.// Check referrer is from same site. 82. 83.if(!(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST']))){$errors[] = "You must enable referrer logging to use the form";} 84. 85.// Check for a blank form. 86. 87.function recursive_array_check_blank($element_value) 88.( 89. 90.global $set; 91. 92.if(!is_array($element_value)){if(!empty($element_value)){$set = 1;}} 93.else 94. 95. 96.foreach($element_value as $value){if($set){break;} recursive_array_check_blank($value);} 97. 98.) 99. 100.) 101. 102.recursive_array_check_blank($_REQUEST); 103. 104.if(!$set){$errors[] = "You cannot send a blank form";} 105. 106.unset($set); 107. 108.// Display any errors and exit if errors exist. 109. 110.if(count($errors)){foreach($errors as $value){print "$value<br>";} exit;} 111. 112.if(!defined("PHP_EOL")){define("PHP_EOL", strtoupper(substr(PHP_OS,0,3) == "WIN") ? "\r\n" : "\n");} 113. 114.// Build message. I don't think there is anymore that is relevant? I just want to reiterate that I know nearly nothing about this stuff so if you could keep your answers simple it would help a lot - cheers! Creating a basic MVC framework. I may confuse myself while asking this, so bare with me if this is confusing for you also... As far as i understand, the URLs are in the following format: www.example.com/controller/method/args My goal here is to not show 'method' in the URL if it's not necessary. For example, www.example.com/contact instead of www.example.com/contact/view. This is OK. I can accomplish this. But problems arise when I want to pass arguments in the URL. Say I have the URL: www.example.com/users <----- this would by default, user the controller 'users' and call default method, 'view'..just list all users. But say i want to view a user.. John. www.example.com/users/john How can I make my script know that 'john' is an argument, and not a method? The only way I can think of this is if I always have a method in the url .. like www.example.com/users/view/username/john As of now, my script breaks up the URL at / and the first element in the array is is the controller. It calls the controller with the other arguments. so www.example.com/users/john. The script would do (simplified) $controller = 'users' $controller = new $controller('john') the 'Users' class would then see if 'john' is a method. If it is, call it, if not, then call the default method (view) with john as argument... but what if I have a method called 'edit' and someone's username is edit? then www.example.com/users/edit would be a problem. So my guestion to you guy is... how do you deal with this issue? If you have www.example.com/users/edit, how do you let the script know that 'edit' is someone's username and now a method to call? Do you pass the method in the url like so www.example.com/users/edit/edit ? Or if you have worked with a framework (Zend, cakePHP, Symfony, CodeIgniter, etc), how does the framework handle it? Ideally, i would like to be able to have www.example.com/users/john instead of www.example.com/users/view/id/john Hi guys, I am developing an MVC application and need some advice about how to set up url routing. Currently I can map a uri to modules/controllers and actions. I though I might leave the routing to last but it seems like that might have been a bad idea. Initially I though I might implement a Zend style routing approach and I still want to do this, but I am lost for thoughs on how I might go about this, I have looked at the zend router classes and understand the principle but cant seem to implement it in my own mvc. So far I have this, $router is an instance of a router class. mapRoute takes a route name and a route object as parameters. The name will be used for convinience. The second parameter takes a route instance which currently takes two parameters, where param1 is a route pattern and param2 is deafult values for when a uri macthes the route pattern. So if a user types http://example/user/23, the router should map to user controller, profile action. The id, which is 23, will need to be injected into a request object. Finally the router object will be added to a front controller instance, so the front controller object can gain access to all the routes. Code: [Select] $router->mapRoute("user", new Route( "user/<id>", array( "controller"=>"user", "action"=>"profile" ) ) ); If any one has any ideas please do share, im not after code, unless you want to supply some, I just need some advice to stream line the whole process or what the best way might be. Any help will be greatly appreciated. Hey all, I'm using cakephp and it asks me a question and I'm not sure what to put in, because I don't necessarily know the consequences of what I put in: Code: [Select] Would you like to create the methods for admin routing? (y/n) [y] > y You need to enable Configu :write('Routing.admin','admin') in /app/config/core.php to use admin routing. What would you like the admin route to be? Example: www.example.com/admin/controller What would you like the admin route to be? [admin] > Thanks for response I have a problem w/ a widely used password protect php code. I use a business directory program that allows custom input fields. I'm using this code to password protect a business listing page in my directory code. I created custom fields for the username & password so a listing can enter their own user/pass but when I test it it won't work when I'm calling/echoing the fields. When I hardcode it w/ a user/pass it works. Any ideas on how I should recode this?: Quote <?php // Define your username and password $username = "<?php echo $custom_74; ?>"; $password = "<?php echo $custom_16; ?>"; if ($_POST['txtUsername'] != $username || $_POST['txtPassword'] != $password) { ?> <h1>Login</h1> <form name="form" method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>"> <p><label for="txtUsername">Username:</label> <br /><input type="text" title="Enter your Username" name="txtUsername" /></p> <p><label for="txtpassword">Password:</label> <br /><input type="password" title="Enter your password" name="txtPassword" /></p> <p><input type="submit" name="Submit" value="Login" /></p> </form> <?php } else { ?> I close the code correctly. <?php echo $custom_74; ?> & <?php echo $custom_16; ?> are just incidently my custom field echo codes. I have over 150 custom fields working fine for user/listee options. The password protect code won't accept echos it seems as coded above. Thanks, Gene im tying to design and make a routing system for my mvc framework but im wondering the best way to do this if anyone could help on how the design pattern would be. im thinking i would have a route config file which would contain all the routes for each file routes.config <?php $routes = array('news' => 'news/index'); ?> then the routing class which would get the correct route depeding on the request class and get the dispatch class to load the controller and action? if anyone could help on the best way to do this that would be great...thanks This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=332538.0 I'm sure it's not much, but I'm not understanding something with custom error handlers: I've created a custom error handler, which I initially set when my page loads : set_error_handler(array ( new ErrorHandler(), 'handleError' ));
It seems to catch all internal PHP errors, such as if I: var_dump($non_existing_var); right after the set_error_handler.... Now, I have an object that throws an exception after: set_error_handler(array ( new ErrorHandler(), 'handleError' )); $locale = new \CorbeauPerdu\i18n\Locale(...); // this should throw an exception ... I thought that with an error handler set, I could 'skip' the try/catch for it, but doing so, PHP spits out in its internal log: PHP Fatal error: Uncaught CorbeauPerdu\i18n\LocaleException: ....
My error handler doesn't catch it at all before, thus my page breaks!! If I want it to go through the error handler, I have to init my Locale with a try/catch and use trigger_error() like so: set_error_handler(array ( new ErrorHandler(), 'handleError' )); try { $locale = new \CorbeauPerdu\i18n\Locale(...); // this should throw an exception } catch(Exception $e) { trigger_error($e->getMessage(), E_USER_ERROR); } ... Is this normal ? I thought one of the goals of the error_handler was to catch anything that wasn't dealt with? Thanks for your answers! why is it that when i try to submit it tells me add a picture but i did added Code: [Select] <?php //decarling some variables $msg = ""; //begin if if($_POST['submitbtn']){ $author = mysql_real_escape_string($_POST['author']); $date = mysql_real_escape_string($_POST['date']); $picture = $_FILES['picture']['name']; $ext = strtolower(substr($name,strpos($name,'.')+1)); $size = $_FILES['picture']['size']; $maxsize = 200000; $type = $_FILES['picture']['type']; $tmp = $_FILES['picture']['tmp_name']; $review = mysql_real_escape_string($_POST['review']); $move = "uploads/"; if(isset($author) && !empty($author)){ if(isset($date) && !empty($date)){ if(isset($picture) && !empty($picture)){ if($size <= $maxsize){ if($ext == 'jpg' || $ext == 'jpeg' || $ext == 'png'){ if(move_uploaded_file($tmp,$move.$name)){ if(isset($review) && !empty($review)){ $query = mysql_query(" INSERT INTO reviews ('',author,date,picture,review) VALUES ('',$author,$date,$picture,$review)"); }else $msg = "Please write a review"; }else $msg = "Error has happen try again later"; }else $msg = "Image must be a jpg, jpeg, or png"; }else $msg = "You must select a smaller image size"; }else $msg = "Select a picture"; }else $msg = "Please enter a date"; }else $msg = "Please fill in the Authors name"; } //ending the if here ?> |