Jump to content

roopurt18

Staff Alumni
  • Posts

    3,746
  • Joined

  • Last visited

    Never

Everything posted by roopurt18

  1. I'll leave that part of the discussion alone as it'll just go in circles at this point. So back on topic, and I may have missed it if it's been discussed, I can't stand it when people lose readability for non-optimizations or perform just plain silly optimizations. For example using all single quotes instead of double quotes. Or rather than using temp variables creating long chains of nested functions like: echo implode( ', ', array_reverse( array_map( 'trim', /*you get the idea */ ) ) ); Or; Put; Everything=Onto; One; Line; Or writing code that extends miles past the 80 character margin.
  2. When static content is being added to a site, developers should not be involved. You're absolutely right. Designers, not developers, should be designing how a site should look. Again we both agree. So it's up to the designer to decide how a form should be constructed. Which tags should be added and in which order. It is up to the designer to create the necessary styles and classes to make forms look nice and aligned for block elements and inline (such as city, state, zip all on one line). I'll even agree that for most sites, it is pages and content that is being added. However, I mostly develop web applications. I might have two or three pieces of static content; everything else is highly interactive user interface tied closely to a database. I'm constantly adding fields to the database, updating the fields in the UI, updating the JavaScript to do special things with the fields, adding validation logic attached to the fields, writing specialized queries to present data in a specific way, etc. There's no way a designer could keep up with me. In this environment, it would be much better for the designer to say: "Hey, I made a nice layout for your application. I gave you a template for your forms so they all look nice. As long as you adhere to my template, your application will look nice." I'm not quite sure what you were trying to say in the second part of your post.
  3. Your old index.php is probably like: <?php $company_id = $_GET['CompanyId']; // now do stuff based off $company_id ?> Your login form should now be saving CompanyId in the session, so your new pages can just use that. <?php session_start(); $CompanyID = $_SESSION['CompanyId']; // now that company ID is set, it should work just the same as before
  4. I consider this an interesting discussion so I'll keep addressing issues as I have time and people bring them up. In other words, not to be a pain in the ass and not to defend my choice. Designers are not capable of creating a proper view in the first place. The view is going to have PHP variables and data objects flying in from the controller and the designer is not going to know how to interact with them properly or they're going to have to write some sort of scripting code anyways. If the application has a "heavy" JavaScript UI the designer is not going to know how to add the extra markup classes or IDs you need to get the JavaScript to work correctly. Designers should create the layout for the site and create "copy-me-templates" that the developers use to build menus, forms, or other UI elements. In other words, the designer should create the XHTML layout and then create sample files of the markup for forms, menus, or whatever else. Then the developers should use those sample files as how to spit out the markup the designer wants. It depends on if the page has any JavaScript generated content or not. When you choose to "View source," most browsers only give you the source the page originally loaded with. With a FireFox extension, you can choose to "View Generated Source," which will give you the source as the page is right now. It will also include any extra markup inserted by plug-ins such as firebug, so it's not truly the source your PHP code is kicking out. You can expand DOM elements in firebug and choose "copy innerHTML" to see their contents, but again it will not be the exact source your PHP code kicked out.
  5. <?php session_start(); if ($_POST['Email'] && $_POST['Password']) { //db info include("admin/conf.php"); //open db include("admin/includes/db_open.php"); $_POST['Email']=trim($_POST['Email']); $_POST['Password']=trim($_POST['Password']); // I DONT KNOW WHY YOU'D WANT TO DO THIS //This is how I want to show the company, instead of using their number, I'd rather have a random number stored in the db //$randval=mt_rand(); //TODO delete me // NOT NECESSARY //store it in the db //mysql_query("UPDATE tbl_company SET sess = '$randval' WHERE Email ='". $_POST['Email'] ."' and Password='". $_POST['Password'] ."'"); //select db // TODO ESCAPE YOUR DATABASE VALUES WITH mysql_real_escape_string() $strSQL = "SELECT Company_Id, Company_Name FROM tbl_company WHERE Email = '". $_POST['Email'] ."' AND Password = '". $_POST['Password'] ."' LIMIT 0, 1"; //connect // TODO GET RID OF OR DIE(), IT'S TERRIBLE (See the tutorial on the main PHP freaks page) $dbQuery = mysql_query($strSQL,$MyDB) or die(mysql_error()); $dbResults = mysql_num_rows($dbQuery); if ($dbResults > 0) { // user is authorized while($dbx = mysql_fetch_row($dbQuery)) { $_SESSION['CompanyId'] = $dbx['Company_Id']; //changed below from 0 to 16 //$_SESSION['sess'] = $dbx['16']; //$session = $dbx['16']; //$session=$_SESSION['sess']; //$session=$_SESSION['SessID']; //added the insert //$_SESSION['SessID'] = session_id(); // TODO NOT SURE WHAT THESE ARE //$_SESSION['sess'] = $dbx['sess']; //$session=$_SESSION['sess']; // Don't see why you need this. //setcookie("Name", $dbx[1], time()+3600); } } // mysql_free_result($dbQuery); include("admin/includes/db_close.php"); } if ($dbResults > 0) { // user login success header("Location: MyAccount.php"); } else { // user login failed header("Location: index.php?error=1"); } ?> Then in MyAccount.php <?php session_start(); print_r( $_SESSION ); // You should see CompanyId, which you can use to identify // and the user is unable to change it ?>
  6. Syntax errors in PHP will result in immediate errors and the script will not run. Using the class incorrectly, for example setting an attribute that doesn't exist on a tag, will result in exceptions. Again the code will not work until the error is addressed. Having syntax errors in your markup will not stop the page from loading into the browser. If you're not careful, you may not notice the markup is incorrect. Or you may have to go out of your way to validate it (which is problematic since we tend to reload pages quite frequently). And as I said, invalid markup will cause weird behavior in CSS and JavaScript and you will just end up wasting time writing useless code.
  7. Most of my sites would be considered small and I'm not at all concerned with the extra processing power incurred by my HTML class. I'm much, much more concerned with the extra development time wasted when my markup is incorrect. If your markup is incorrect then browsers will demonstrate weird behavior with your JavaScript and CSS. This can cause you to spend time writing unnecessary JavaScript/CSS. In addition, "Is my markup correct?" is one less question I have to ask myself when weird things do happen. In my projects where I use that class, I spend little or no time inspecting the actual markup or even looking at the insides of the HTML class. I also develop with the infamous 80/20 rule in mind. As it turns out, I've never once had a situation where the extra processing done by that class has facilitated that I create markup the "traditional" way. But if that did happen, well then I might have one page in 100 where I don't use that class. And if my site became so large that I really did become concerned with speed, I'd probably be using a compiled language. This is of course after obtaining separate servers for database, static content, dynamic content and load-balancing solutions.
  8. Until you consider the benefits: 1) I don't have to jump in and out of PHP parsing mode. My files are PHP which improves readability IMO. 2) I don't have to type extra characters to set an attribute, i.e: <input type="text" name="user" value="<?php echo $somevalue; ?>" /> 3) I don't have to worry about escaping output since the HTML class does it for me. In other words, I don't have htmlentities() littered throughout my code. 4) I don't have to think about a tag being self-closing or requiring a close tag; the class does it for me. 5) All of my markup is well formed, guaranteed. I can't make mistakes like this: <input type=text" value="foo" > 6) Nor can I make mistakes like this: <input type="text" valeu="foo" /> I'll admit it was slightly awkward using the class after I first wrote it, but now I love that little guy.
  9. You can create files on remote computers with PHP, just not in the way you're thinking. The remote workstation could initiate an SSH port-forwarding connection to the server. The server could write the XML data to local port 30303 which would translate to some other port on the local machine, which could be listened on by a PHP service.
  10. I don't use single or double quotes when I write my HTML; I use a special class from my framework. <?php $html = HTML::Make( 'div' ) ->child( 'form' )->action( 'foo.php' )->method( 'post' ) ->child( 'p' )->class( 'errors hidden' ) ->_If( count( $form_errors ) > 0 ) ->child( 'ul' ) ->Iterate( $form_errors, 'iterate_helper' ) ->top() ->_EndIf() ->top() ->child( 'p' ) ->child( 'label' )->for( 'username' )->child( 'Username:' )->top() ->child( 'input' )->type( 'text' )->id( 'username' )->name( 'username' )->top() ->top() // etc... ->top(); echo $html->topMost()->__toString(); function iterate_helper( HTML $parent, $value ) { $parent->child( 'li' )->child( $value ); } ?> Would you consider my framework unreadable? <?php class UsersController extends Controller { public function AddAction() { $rq = $this->Request; if( $rq->IsPost() ) { $user = new User(); $user->username = $rq->GetParam( 'username' ); $user->password = $rq->GetParam( 'password' ); if( $user->Save() ) { $this->SetForwardMessage( 'The new user has been saved.' ); }else{ $this->SetForwardMessage( 'Unable to create new user at this time.', true ); // true denotes error } $this->Redirect(); } // If we make it this far, the view with the AddUser form automatically // is rendered. } } ?>
  11. You could create a service or scheduled task on the remote PC that attempts to download via HTTP, HTTPS, FTP, or FTPS the XML files from a secure location on the server.
  12. You should be developing locally under "ideal" conditions, where ideal represents your development box that has all of the necessary servers / services running on localhost. Under these conditions everything should be lightning fast. Then when you move to the production server you can accommodate for any short-comings of the server.
  13. Were you transferring in binary, ascii, or auto?
  14. You can encrypt data in this manner for storing within your database. Your need to base64 encode the data will depend on how well your chosen database handles binary data. I don't see any reason to decrypt user passwords and send them to your users however. Sending someone a password via e-mail in plain-text is a big security risk IMO. You'd be much better off allowing them to reset their password via a link send to their e-mail account. The reset-link would contain a unique key tied directly to that user's database record and have an expiration attached to it, so if they do not click it within X hours it can no longer be reset by that link. The only time I use two way encryption is when I'm storing a password for some sort of service (FTP, SMTP, SSH, etc.) when I know my program will need to provide the password to another program when a human will be unavailable to enter the password themselves. Or for other highly sensitive data storage, such as social security or credit card numbers.
  15. Anyone that has the raw source code to your application will have access to any sensitive information you store in your source code files, including passwords and keys. If your source code is stored in plain text on your server, then there isn't much reason to encrypt database passwords stored on disk or in source code files. The reason is any attacker can easily see your decryption scheme and decrypt your password / data the same way you do. Now if you were to go the extra step and encode your PHP source files with Nu-Coder, ZendGuard, or some other encoder program then there might be a point to this. For example, the applications I write are distributed to clients and they install my applications on their servers. When they install my application they run a setup script that will ask for their database password. The password they enter is encrypted by my program and then saved to disk. My source code files are encoded so they have no idea how I encrypt their data. And since the password to their database is encrypted, their machine is slightly more secure should an attack gain access to the machine. Note that any attacker skilled enough to: 1) Gain high enough access to a machine 2) Run a debugger Will obtain any secret keys, passwords, or even your raw source code files whether they're encoded or not.
  16. Windows: Maybe once every 3 or 6 months. Linux: Once maybe every 12 to 18 months. Stable. Yes. Still crashes though! Anyways my point is Linux is more stable so the OP should use that if it's an option.
  17. My experience is that Apache randomly crashes less in linux than it does in Windows.
  18. If Robert Jordan could have kept his thoughts organized the series would have been much better. The first few books in WoT were good. By the fourth one he had opened up so many sub-plots you couldn't keep track of them. I stopped reading after 6 or 7 books.
  19. You can use variables in MySQL. Before you run the query, you create a variable named @seq and initialize it to 0. set @seq = 0; Then you issue the query: select @seq := @seq + 1 as thecount, login from wv_user; For each row, MySQL will add 1 to the current value of @seq. It will return this value in the dataset. It also updates @seq variable to this incremented value, so the next row will increment one further. It's essentially the same as: <?php $inc = 0; $items = array( 'a', 'b', 'c', 'd' ); foreach( $items as $item ) { echo ($inc = $inc + 1) . ' ' . $item . "\n"; }
  20. You can get MySQL to number them for you: set @seq = 0; select @seq := @seq + 1 as thecount, login from wv_user;
  21. I tried to cover this in my first post: http://www.phpfreaks.com/forums/index.php/topic,284048.msg1346941.html#msg1346941 I've also attached a sample junk.zip file with the directory structure for a sample application and potential framework. [attachment deleted by admin]
  22. If you're going to set off on creating a reusable framework for yourself and you have the time, I suggest the following: Don't think so much about how you should write the framework, think more about how you want your application to interact with it. Let your application needs dictate how you write and organize the framework. Move in small chunks. Start with index.php and how you want to load the framework and kickstart everything into action. Write the application code first and go ahead and use classes and methods that don't exist yet. Then go implement those classes and methods in your framework. Get it working with a simple, sample application. Then create one or two more simple applications and get them to the same stage of completion as your first sample project. Was your framework easy to use? Is there one thing you're constantly typing in each application that you could move into the framework? Redesign your framework to accommodate any changes you want to make now. Think about how you really want everything to work. Here's an example of a design decision I made when creating the framework I use at work. The url http://domain.com/Foo/Add will map to the FooController::Add method. This is magically handled by my framework. But it's reasonable to assume that controllers will have methods not meant to be mapped to urls. I don't want someone to fiddle with a URL to try and discover methods in my controller. To accommodate this, I decided that all methods publicly mapped to URLs should have the word "Action" appended to them. Therefore my framework will actually map http://domain.com/Foo/Add to FooController::AddAction(). This allows the following: <?php class FooController extends MyController { public function __construct() { parent::__construct(); } public function AddAction() { /* publicly available via URL */ } private function add_helper() { /* method is private and name does not end in 'Action'. Therefore not available via URL */ } } ?>
  23. Ayon asked me some questions in a PM but I'm going to respond here in hopes that: 1) It will help more people 2) I can possibly receive feedback on my ideas from others what you mean with this? Do you mean that I should make classes like Database, Text, Numbers, Validate, etc? Now regarding the directories and files.. In the two sections you posted you have in the first "class Application" then in the second you've got "class My_Application extends Application" and the same with several other classes... What exactly is the difference between Application and My_Application? Only thing I can think of is that My_Application only contains something like a "loader function" for "Application".... but i'm probably wrong... Before I begin, let me just say two things: 1) Some of these are ideas for the next iteration of the framework I use at work, but not actually implemented. 2) None of this was typed or run in an IDE so excuse typos and don't expect it to work out of the box! I have one, albeit long, answer that takes care of both questions. As I said before, objects are more than collections of functions. Objects contain behavior. So let's think for a minute about how we want all of our applications to work. 1) We want our applications to have a single entry point: index.php 2) We want our applications to work equally as well from a command line and as an http request. 3) We want a standardized definition of the behavior of an application 4) We want the application to modify the behavior where it needs to Let's start with invoking our application. As a web request, we will need a mod_rewrite rule to filter everything through index.php. The url will look something like: http://domain/$CLIENT/$CONTROLLER/$ACTION/$PARAM1/$VALUE1/$PARAM2/$VALUE2?$QUERYSTRING $CLIENT: I often have to write one application that handles multiple databases. The $CLIENT portion tells my application which database, configuration, etc. to use. $CONTROLLER: The business logic handlers of the application. Examples would be logic for: Users, News, Posts, Headlines, or basically whatever your site is about. $ACTION: The action to perform on the business item. Common actions are CRUD: create, read, update, delete, but your application will likely need more. $PARAMx/$VALUEx pairs: These are named parameters the same as those in $_GET, however placing them in the URL like this is search engine friendly $QUERYSTRING: Is everything following the ? in the url, because sometimes it's just necessary. .htaccess # Turn on rewriting RewriteEngine on # Any request that is an actual file or directory should be served by Apache # and not filter through index.php. The following rules represent that. RewriteCond -f [OR] RewriteCond -d RewriteRule * - [L] # Everything else is assumed to go through index.php RewriteRule (.*) index.php [QSA,L] As a console application, we want to type something like the following to invoke our application: $ pwd /home/roopurt18/myproject $ php index.php --client fooclient --controller Import --action RunNow --force true In that example: $CLIENT is fooclient $CONTROLLER is import $ACTION is run_now $PARAM1 is force $VALUE1 is true When invoked, we want index.php to take over and run the application: index.php <?php // Note this file is part of the application, not the framework! define( 'APP_DIR_HOME', dirname( __FILE__ ) ); // Require the framework, wherever it is on the file system // bootstrap.php *IS* part of the framework and will load the essential classes // of the framework, such as: Application, Controller, Layout, View, Request, etc. require_once( '/path/to/framework/bootstrap.php' ); // Now require *YOUR* application. This is part of your application require_once( APP_DIR_HOME . '/private/classes/MyApplication.php' ); // Now run the application with top-level exception handling try { $app = new MyApplication(); $app->Run(); }catch( Exception $ex ) { MyApplication::LogFatalException( $ex ); } ?> MyApplication.php <?php // Here is the basic, non-implemented MyApplication class class MyApplication extends Application { } ?> Application.php <?php // Here is the application class, which is part of the framework. abstract class Application { final public function Run() { // Allow the specific application to run initial code $this->Startup(); // Create the request object. The request object is responsible for // determining how the application was run (www or cli) and for // providing access to the controller, action, client, parameters, etc. $rq = Request::getThisRequest(); // Allow the specific application a chance to do something pre-dispatch $this->PreRequestDispatch(); // Now dispatch the request to the controller class. The controller // class will now how to instantiate the proper controller. $output = Controller::Dispatch( $rq ); // Allow the specific application a chance to do something post-dispatch $this->PostRequestDispatch(); // Send the output echo $output; // Allow the specific application to perform special shutdown code $this->Shutdown(); } abstract protected function Startup(); abstract protected function Shutdown(); abstract protected function PreRequestDispatch(); abstract protected function PostRequestDispatch(); } ?> This isn't a perfect example by any stretch, but hopefully it'll suffice. Now since Application is abstract and MyApplication implements no functions, PHP will throw errors. My coworker has been giving me grief about abstract classes "because code should work regardless." But I like that PHP throws errors if I don't implement those functions in MyApplication. Using abstract allows me to remind myself which pieces of my framework code are required for me to implement. I can't tell you how many times I've written general, reusable code and then tried to reuse it 6 months later. I always end up forgetting to implement some piece of it, or forget some piece of configuration, etc. However, the fact that the class is abstract creates a contract and obligation on me when I go to reuse it. I must fill in those pieces or it will not work. If I fill in those pieces correctly, then the whole application should just work. So let's fill in MyApplication.php MyApplication.php <?php // Here is the basic, non-implemented MyApplication class class MyApplication extends Application { private $_start_tm = false; private $_end_tm = false; protected function Startup() { // Mark the application start up point $this->_start_tm = microtime( true ); // We'll need sessions in this application session_start(); } protected function Shutdown() { // Mark the application end time and log to database $this->_end_tm = microtime( true ); $elapsed = $this->_end_tm - $this->_start_tm; } protected function PreRequestDispatch() { /* do nothing */ } protected function PostRequestDispatch() { /* do nothing */ } } ?> Now that I've filled in MyApplication: 1) PHP will stop throwing errors (unless I've introduced some!) 2) The application receives all of the reusable functionality I've built into my framework 3) The framework allows the application to "hook" custom functionality into it at certain points of its execution Now let's look at how some controllers might work. Controller.php <?php // Controller.php -- this is part of the framework abstract class Controller { protected $_rq; // The request that generated this object protected function __construct() { } // Set the request that generated this object private function SetRequest( Request $rq ) { $this->_rq = $rq; } // Dispatches a request public static function Dispatch( Request $rq ) { // The incoming request object knows the controller name (that's its job) // But the application knows where the associated class is on disk. // So LoadClass() is abstract to the specific application can handle // loading the class. $this->LoadClass( $rq->GetControllerName() ); // If the URL is: // http://domain/theclient/Users/Add $class = $rq->GetControllerName() . 'Controller'; // I.E: Users $action = $rq->GetActionName() . 'Action'; // I.E: Add // cli requests should not be buffered, all others should // Since buffering is on, we can still make header() calls. if( $rq->IsCli() === false ) ob_start(); $instance = new $class(); // Instantiates: UsersController $instance->SetRequest( $rq ); $instance->{$action}(); // Calls $instance->AddAction() // We need the get the buffer contents if( $rq->IsCli() === false ) { $contents = ob_get_clean(); return $contents; } return true; // Cli requests will just dump to the console, but we still // want to signal that they ran, so return true (sort of arbitrary). } abstract protected function LoadClass( $name ); } ?> Now we have the concept of MyController. We have this for two reasons: 1) Controller is abstract and needs a LoadClass() method. You only want to implement this method once for all of your controllers. You don't want to write LoadClass() for your UsersController, NewsController, FoobarController, etc. 2) All of your controllers might need a special functionality. By creating a MyController you can implement this common functionality here, in one place. MyController.php <?php // This is part of your application! class MyController extends Controller { // Let's allow all of this applications controller to log their run time // to a file private $_start_tm = false; private $_end_tm = false; protected function __construct() { parent::__construct(); // calls parent $this->_start_tm = microtime( true ); // marks start time } public function __destruct() { $this->_end_tm = microtime( true ); // marks end time $fp = fopen( APP_DIR_HOME . '/private/logs/controllers.log' ); if( $fp ) { $fwrite( $fp, $this->_end_tm - $this->_start_tm . " s\n" ); } } protected function LoadClass( $name ) { // Loads: UsersController, IndexController, NewsController etc require_once( APP_DIR_HOME . '/private/controllers/' . $name . 'Controller.php' ); } } ?> Now we implement UsersController. UsersController.php <?php // This is part of your application class UsersController extends MyController { protected function __construct() { parent::__construct(); } public function AddAction() { /* add a user */ } public function DeleteAction() { /* delete a user */ } } ?> So with that model we have the following: 1) Controller is part of the framework and handles base functionality. My example doesn't do much, but a more evolved one might load the View, instantiate database objects, etc. 2) MyController allows us to use all of the behavior defined in Controller and add custom functionality to each of the application's controllers. 3) The final controllers that are instantiated (UsersController, NewsController, etc.) will all have: a) A Request object, a View object, i.e. stuff common to every application b) Time logging to a file without any extra effort per controller, they all just receive the behavior. So that's a bit long winded but I hope it helps and I'm looking forward to any feedback. I want to reiterate the code samples are merely that. They're not wonderfully designed because I'm tired and I'm demonstrating concepts, not building a public framework. Now here's the challenge: I want you to tell me how you can do all of that with a library of functions you copy and paste from project to project.
  24. Oh that's not what I'm saying at all. A library of re-usable functions is certainly better than nothing and it's a great stepping stone in your understanding of creating something like a framework. Libraries of functions do tend to grow ungainly over time though. The thought process will be something like "Does this function go in my library or the application?" Also, "hooking" your application to the library can be troublesome on occasion. However with abstract classes and interfaces you can define a base functionality and then the derived, application specific code can implement the pieces that are necessary. The best part is the code won't work until you do. On a brighter note, a framework doesn't need to be some daunting task. When I started at my current job I spent 3 or 4 days building the core of the framework that I still use today in all of my applications. I've worked there for two years now, give or take, and the entire framework is maybe 15 files. All it needs to do is expedite the most common and core needs of your application. It doesn't need to be nearly as complicated as the common PHP frameworks that exist today. (As a side note, I think almost every existing PHP framework is inconsistent in it's implementation and poorly documented in terms of best practices. I'm not encouraging you to make another one of those!) Another nice thing about a framework is the framework will dictate how an "application" works. It will do this with the base classes and then the derived application-specific classes will override methods where necessary. The nice thing about this is once your framework becomes mostly static and stable, as mine has at work, it will not change much. Each and every one of your applications you deploy, however, will all work the same. When you look at a project 6 months after it's been deployed, you won't have to ask yourself "How did I implement the XYZ in this one again?" You'll know how the framework implements XYZ because it's the same for all of them. A library of function is just that, a collection of functions. They don't define behavior, which when you support many applications and they're not always fresh in your mind is very important when it comes to support. The more consistent the behavior of your applications, the less time you spend looking_at_code_with_really_long_function_names(). Anyways, that's just my opinion and food for thought. We all start somewhere.
  25. There is no such thing. Oh sure, it may start simple but it'll bloat itself to no end as time progresses. Then you'll have a library of code that is damn near impossible to refactor due to the number of your projects that rely on it. To each their own I suppose!
×
×
  • 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.