-
Posts
4,207 -
Joined
-
Last visited
-
Days Won
209
Everything posted by Jacques1
-
No offense, KubeR, but this is bollocks. You don't seem to understand what session actually are and how they work. Standard PHP sessions consist of two parts: A session cookie which holds the session ID and the session file on the server. Since the actual session data is on the server, users don't have access to it. They can of course change their ID in the cookie, but that alone doesn't get them anywhere. There are two security risks for standard sessions: If the session ID can be intercepted or predicted, an attacker can take over the session (session hijacking). If you adopt user-provided IDs (which is the default), an attacker can try to make the victim use a known ID and then take over the session after the victim has logged in (session fixation). The first problem can be solved by using sufficiently random session IDs (see session.entropy_file and session.entropy_length) and only transmitting them over HTTPS. The second problem can be solved by generating a fresh ID in the log-in procedure. So if used correctly, PHP sessions are secure. I'll happily discuss this in another thread. Your statements about cookies are also wrong. Yes, the values are editable. But that simply means we need to check the integrity and authenticity of the data. This is typically done with a message authentication code. However, I don't recommend this approach, because it's very hard to get right compared to simply storing the session data on the server. There are some alternatives to session-based authentication, most notably HTTP authentication and TLS client certificates. But they have problems as well and make little sense for an average website.
-
This is not a problem of conflicting declarations, because the meta element is overriden by the HTTP header (of course it's still wrong). The problem is that the text in your dropdown menu actually is stored as Windows-1252 or similar, whereas the rest of your application uses UTF-8. This is an issue of your editor. You need to make it use UTF-8, and you have to convert all existing files (HTML, JavaScript, CSS) into UTF-8. Having the database use a certain encoding is one thing, but of course your source files need to use the same encoding as well. There are several other issues: First of all, the HTML markup is hopelessly outdated. I'd say this was written before the year 2000. JavaScript 1.2? That was back in 1997 when people used Netscape Navigator and Internet Explorer 4. Quite a lot has changed since then. We no longer use HTML for styling. All style attributes like leftmargin, background were removed a long time ago in favor of CSS. The language attribute is no longer used. Depending on which flavor of HTML you use, you need the type attribute or nothing at all (HTML5 uses JavaScript by default). And of couse the era of JavaScript 1.2 is long gone. You're missing the DOCTYPE declaration. This makes the document invalid and triggers the compatibility mode of the browser. As a result, your users may see strange layout errors. The meta element for the character encoding should be at the very top of the head element. Otherwise you risk that the browser doesn't find it at all. It might be a good idea to switch to HTML5. For example, the meta element for the encoding now has a short form: <meta charset="utf-8">. Anyway, the bottom line is: You need a better resource for HTML. The Mozilla Developer Network has excellent, up-to-date information. It's also strongly recommended that you run your HTML through the W3C validator to see if it's even correct. The small snippet above already gives me 5 errors. The PHP 6 project failed, and the whole Unicode discussion is somewhat misleading. PHP is already perfectly capable of handling Unicode data (as you can see). What the PHP 6 people tried to do is improve and extend the support. For example, we currently need the Mbstring extension if we want to do string operations with Unicode strings (getting the n-th character, getting the length, getting a substring etc.). It would have been nice to have this in the PHP core. But, well, we won't.
-
I'm talking about a graphical error page with formatted text, images etc. Something like the Wikipedia error page. I mean, that single line of plaintext above was just for testing. In reality, it should be a proper page with a bit of visual appeal. Internet Explorer is indeed a pain in the ass. This has improved over the years, but occasionally you still encounter the special IE brainfarts.
-
The Google recommendations are not “wrong”. They are micro-optimization techniques which can help in certain setups in certain situations. For example, if you've already maxed out your hardware and need the last bit of performance to satisfy your thousands of impatient users, it may indeed make sense to fine-tune the traffic characteristics. As I've already traid to explain, proper optimization requires a concrete goal, analysis and judgement. If you've gone through that and found out that getting rid of redirects will lead to a major performance boost for your particular site, by all means, do it. I'm all for it. But what doesn't help is tell everybody that redirects are evil and that people should throw away their good code for the sake of some alleged performance benefit. I mean, this is like tuning a car: If you need the last bit of performance for your Porsche, go ahead. But that doesn't mean your neighbours are supposed to fill nitrous oxide into the family van. It's not gonna help them drive the kids to school, and it's actually a rather bad idea.
-
Date, between date column and date column -3 days
Jacques1 replied to lasha's topic in PHP Coding Help
The blue underlined text in my reply is a link. You need to click it and read the text. I'm not sure where you've searched, but the very first function in the link above is already the one you need. -
Sorry, but this is just blind nano-optimization voodoo bullshit. Do you know paddy_fields's server setup? Do you have usage statistics? Benchmarks? Profiles? No? Then on what basis do you tell him to avoid redirects? As far as I'm concerned, his website may very well run on the cheapest shared host with the slowest possible Apache/CGI configuration and 10 users per day. And you're worried about redirects? You first write proper code, then check the performance, then analyze the problem (if there's any) and finally choose the right technique to solve this particular problem (if there's any). Running around applying random “optimizations” in the hopes that they'll do something doesn't get you anywhere. In fact, this is downright harmful, because optimizations usually come at a price. Let's summarize: Removing redirects will lead to irritating error messages in case the user tries to reload the page or go back lead to duplicate submissions if the user clicks the wrong button – unless you make the script twice as complex by implementing nonces What you might get is a theoretical nano-optimization by saving a single roundtrip. Is it even measurable? Perceptible? Do the users even care in this particular case? We have no idea, it's all just speculation. In other words, you've replaced a minor virtual problem with a major real problem. Congratulations.
-
Date, between date column and date column -3 days
Jacques1 replied to lasha's topic in PHP Coding Help
I have no idea what that is supposed to mean. But there's no reason for this PHPMySQL mixture, anyway. MySQL is perfectly capable of doing date calculations. -
Doing a redirect after a successful POST request is absolutely correct. Don't let anybody talk you out of it. This is the PRG pattern, and we all use it. Not only does it prevent strange error messages. It also prevents people from accidentally submitting the same data again, which can be a serious problem depending on the context. I have no idea what davidannis is talking about. A redirect makes you “pay a high price in performance”? What century are you living in?
-
This is one of those silly quirks of Internet Explorer: The size of the error page must exceed a certain limit, or else the browser will ignore it and instead display some default error message. The numbers from the article are still true, so you need at least 513 bytes of content. You can either create a complete HTML error page right now or ignore Internet Explorer until you have one.
-
Having problem with moving uploaded files
Jacques1 replied to MaryamJamil's topic in PHP Coding Help
Wherever you got this terrible code from, you need to take it offline immediately. This allows anybody to upload and potentially execute malicious code on your server. Or to put it in other words: Once this runs, you'll be “hacked” in no time. File uploads are very critical, and you absolutely must understand the risks and how to deal with them. Turn on your brain, do a Google search and then carefully write your own code. Do not copy and paste stuff you found somewhere on the Internet. To name just a few things you need to take care of: You have to choose the filename (including extension), not the user! Do not store the file under the user-provided filename, because this allows an attacker to place malicious scripts on your server, overwrite existing files or block your entire service by using up all common filenames. The filename must be unique. No, you cannot use file_exists(). This doesn't work with simultaneous uploads, and it will quickly make your upload feature unusable due to name collisions. If I upload a file name “vacation.jpg”, does that mean nobody will ever be able to use that name? That's hardly acceptable. To achieve unique filenames, you must either use an AUTO_INCREMENT column from the database or generate a purely random name. You need to restrict the file types. Is this an image uploader? Then only accept image types. If possible, serve the uploaded files from a different domain so that JavaScript attacks will be less harmful. ... Sorry for being a bit harsh, but you were about to commit virtual suicide.- 2 replies
-
- upload files
- php
-
(and 1 more)
Tagged with:
-
Cool. It's a sad fact that many people who write PHP tutorials have absolutely no idea what they're doing. You'd think they're experts you can learn from, but in reality, they're often just parotting the same nonsense that has been around for years. PHP is somewhat infamous for bad tutorials. One of the core developers once described it as “the blind leading the blind”, and this is very true. So while tutorials may give you some ideas and inspiration, you should be very critical and question everything. Just because thousands of PHP programmers use a certain practice doesn't mean that it makes sense. Error handling in particular seems to be extremely difficult for many people. Hell, even the PHP manual can't get it right: In their example code for establishing a PDO connection, they immediately catch the exception, print the raw error message on the screen and then continue script execution. That's ... not intelligent. One might try to explain this away as a kind of demonstration, but the PHP developers should know that the exact code will be copied and pasted around for the next 30 years. So you should indeed question everything, even example code from the PHP manual. Of course you cannot possibly take care of every little detail while you're still learning the language. But whenever you have the chance for doing research and thinking about a problem, do it. If not, it's just a few lines of extra code. But then you definitely need a new hoster.
-
Hi... does the first P really stand for PHP?
Jacques1 replied to kathmeejee's topic in Introductions
That's a very romantical explanation. But I fear it was just a bunch of drunken guys doing wordplay. -
Do not, I repeat, do not echo PHP values into a JavaScript context. This is almost guaranteed to cause a cross-site scripting vulnerability or at least a severe bug. For example, if $data happens to contain a single quote, then the whole script will blow up with a syntax error. And if $data includes user-provided data, then an attacker can purposely break out of the JavaScript string and inject arbitrary code into your page (aka cross-site scripting). First of all: What is $data, and why do you need to pass it from your page to the target script? Can't you retrieve it in the target script itself?
-
<?php function html_escape($input, $encoding) { return htmlspecialchars($input, ENT_QUOTES, $encoding); } ?> <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="utf-8"> <title>Escaping test</title> </head> <body> <?php if ($_SERVER['REQUEST_METHOD'] == 'POST'): ?> <h1>The escaped output</h1> <p> <?= html_escape($_POST['markup'], 'UTF-8'); ?> </p> <?php else: ?> <h1>The input</h1> <form method="post"> <label for="some_text">Enter some HTML markup:</label> <textarea id="markup" name="markup"></textarea> <input type="submit"> </form> <?php endif; ?> </body> </html>
-
Erik, the problem is that you happily adopt any nonsense which matches your expectations, but you have a very hard time giving up a wrong expectation for the sake of a good solution. Do you think you can put aside all the expectations for a minute and just be open-minded? Forget about exceptions for now. In PHP, we're dealing with errors. Exceptions are just a subset of errors, and they're useful when you start to program object-oriented. But at this point, they're completely irrelevant. Forget about the try-catch statement. Strike it from your memory. OK, now we're talking about errors. There are many different types of them (15, to be exact), and if your PHP setup is misconfigured, they'll all be printed on the screen. You don't want this, so you need to suppress the error messages. This is done with ini_set('display_errors', 0). Now your users will see a blank screen instead of an error. This better but not perfect. You actually want an error page instead of a blank screen, so you need PHP to execute a custom function in case of an error. The obvious solution would be an error handler, but this doesn't work, because error handlers cannot catch fatal errors (which are the most important ones). What you need is a shutdown function. And while you were busy catching exceptions, I already wrote down a solution. You must have missed it. If you just cannot give up your old ideas and try something new, I'm OK with that. At this point, it doesn't matter, because it's all just for fun. Your users probably won't mind too much if they're bombarded with PHP errors. But in the long run (especially if you plan to do this professionally), you need to reconsider your approach. Making a mistake is OK. Making the same mistake over and over again even if you know that it's wrong is a problem.
-
It's still not clear what you want. What does JavaScript insertion have to do with database queries? If you want to somehow magically “clean” the user input before you store it in the database, this is neither possible nor sensible. Cross-site scripting is an output problem, not an input problem. You leave the input as is when you store it in the database. But when you output the data, you escape it for the specific context. As a concrete example: Let's say you have a form on your site where people can enter an arbitrary comment. When you store the comment, you don't do anything with it. No escaping, no “sanitizing” (whatever that means). You just store the raw text. But when you put this comment into your HTML page, you escape it for the specific target context. For example, if the comment is supposed to go into a simple HTML element like div or p, you need htmlspecialchars(). It's very important to understand that escaping is done when you use the data, not when you receive or store it. You should avoid terms like “sanitizing”, because they carry the idea that you could just take the input, apply some magical cleaning function and then safely use the result in any context. This is wrong.
-
Does interfaces include default definitions?
Jacques1 replied to johnmerlino1's topic in PHP Coding Help
Why are you so obsessed with silly comparisons of programming languages, John? You seem to spend your entire time picking random features from random languages and trying to find an equivalent in PHP. Of course you're free to to that (we all have some strange hobby), but I fail to see the relevance or usefulness. You can philosophize all day long about why PHP's strpos() returns false when C's strpos() returns -1, or why PHP doesn't have the latest fancy features of Java. But I fear you won't learn PHP one bit from doing that. PHP is neither Java or C. It's PHP. The question is: What do you want to do? Then we can tell you how it's done in PHP. -
C, Java. What language comes next? I suggest Brainfuck.
-
php supports function overloading or not?
Jacques1 replied to johnmerlino1's topic in PHP Coding Help
The quote is bollocks, and it worries me that obvious nonsense like this is accepted into a book. Interestingly, chapter 5 says the exact opposite (the truth): You cannot have multiple functions/methods with the same name but different parameters. PHP doesn't even have type declarations of parameters (there's type hinting, but it's limited to classes and arrays). However, the PHP core developers themselves are hopelessly confused about the term “overloading”: On the one hand, they've redefined it to describe magical methods like __set() and __get(). Then it's used with yet another definition in the mbstring extension where it simply means that the default string functions are replaced with mbstring functions. So now we have three different definitions: The “official” one as used everywhere outside of PHP, and two different definitions used in the PHP world. How helpful. -
Error handlers cannot catch fatal errors, but that's exactly the type we want to catch. In fact, catching anything other than fatal errors is a bad idea, because you're likely to run into a partially rendered page. In addition to that, you now have this strange double error handling: You first catch some errors to turn them into exceptions, and then you catch all exceptions to do the actual error handling. In fact, you need a third stage (rethrowing the exception) if you don't want to do the error logging manually. And let's not forget that the try-catch must be repeated for every single script which is accessed directly. Why spend five times as much effort on an approach which only works halfway? Only to keep the beloved try-catch statement? On the other hand, the shutdown handler above catches all relevant errors with a single function. This is actually an emulation of what a properly configured setup would do: PHP automatically triggers a 500 response code in case of a fatal error, and the webserver (or in our case PHP) displays an error page.
-
No, it doesn't. It escapes “<”, “>”, “&”, single and double quotes and a whole lot of harmless characters. If you need anything else, you're doing it wrong. Are you trying to insert user input into an existing script element? This is simply wrong and mustn't be done at all.
-
I think this thread is turning into a very, very wrong direction. I'm not sure why kicken even came up with this try-catch stuff, because this is objectively wrong, and he should definitely know that. Exceptions are only a small fraction of possible errors. In fact, they're a fairly recent addition to the PHP core and are only used in the “new”, object-oriented parts of PHP (PDO being one of them). All other functions use classical errors (notices, warnings, fatal errors etc.). So this big try-catch block catches maybe 5% of the errors and lets the other 95% through. This is nonsense. It's actually downright harmful if your error messages are indeed printed on the screen, because that means your users will see all the notices, warnings, fatal errors etc. You want a quick-and-dirty solution? OK, let's assume the administrator of your system is an evil bastard who has activated display_errors on your live server (which no sane admin would ever do) and prevents you from turning it off (which no sane admin would ever do). What you would do then is turn this setting off at runtime and register a shutdown function to display an error page: <?php /* * This is *not* a correct solution. It's a workaround for dealing with a * hypothetical evil admin who has misconfigured PHP and now won't let you * touch the configuration. */ // overwrite error settings at runtime ini_set('display_errors', 0); ini_set('log_errors', 1); ini_set('error_log', '/path/to/logfile'); function handle_fatal_errors() { if (http_response_code() == 500) { echo 'Sorry, there was a technical problem.'; } } register_shutdown_function('handle_fatal_errors'); The script only works in PHP 5.4 and above. If your hoster doesn't even offer that, this is getting silly.
-
Again: Only a small part of PHP errors are exceptions, so your global try-catch doesn't get you anywhere. If at all, you'd use an error handler to catch all errors, not just exceptions. However, if your hoster gives you absolutely no control over the configuration, the solution is to switch to one that does rather than try to come up with strange workarounds. In fact, global error handling at runtime doesn't even work, because it obviously only covers errors which happen after the initialization. What about the others? Error handling needs to be done by the webserver outside of the script. This can partially be emulated with the auto_prepend_file directive. But before we do all kinds of speculation, let's hear about the OP's setup.
-
Definitely stick to PDO. You already know all the important parts, and switching to MySQLi would be a huge step backwards. Also, the current issues have nothing to do with PDO in particular. I understand now why you're struggling with exceptions. You think that every uncaught exception will dump the internal error message on the screen. This is not the case. How PHP deals with errors (which includes exceptions) depends on the configuration. During development, it makes a lot of sense to display the error messages on the screen, so you turn display_errors on. In a live environment, you want to log the errors instead of displaying them, so you turn display_errors off and log_errors on. The only thing left to do is set up a user-friendly error page in the webserver. How this works depends on your webserver and the architecture you're using (CGI? FastCGI?). If you need help with this, you should create a new thread.
-
Several things. First of all, prepared statements are only immune against SQL injections if you've set the PDO::ATTR_EMULATE_PREPARE attribute to false and use a constant query string without any dynamic values. You cannot use mysqli_real_escape_string() at all. Like the name already says, this is a MySQLi function. PDO and MySQLi are two entirely different extensions which have nothing to do with each other. If you want to do manual escaping in PDO, you need to use PDO::quote(). However, there seems to be a general misunderstanding about how escaping works. You do not store “pre-escaped” strings. The database is supposed to hold the actual unaltered data. If a person has the lastname “O’Sullivan”, you store that as “O’Sullivan”, not “O\’Sullivan”, “O'Sullivan” or whatever. Storing escaped data is an awful idea. What if you need to use it in a different context? For example, what if you want to display your SQL-escaped string in your HTML document? Then you first need to revert the SQL-escaping, retrieve the original value and finally apply HTML-escaping. Hell, you couldn't even query the database for names of a certain length, because the escaping characters are in the way. But what's even worse: Using “pre-escaped” strings means that you blindly trust your database content. What if one of the values is not escaped? Maybe there's a bug, maybe an admin has manually inserted the data. In any case, you now have an SQL injection vulnerability or at least a bug. Escaping is always done ad hoc, never in advance. There seems to be a misunderstanding. Once the database logic is loaded, you can use it anywhere in the current script context (including sub-scripts) and as often as you want. Using require would make absolutely no sense, because you'd constantly reconnect to the database while overwriting the current connection. The database part is supposed to be executed only once per script execution. You don't understand. My point is that it's nonsensical to have an error-handling procedure for every single error. In general, you always want to do the same two things: Log the internal error message. Have the webserver display a generic error page. Those are standard features of PHP and your webserver. If you just let the software do its job, you probably don't have to write a single line of code. What is the point of telling the user about your database issues? They cannot fix them, can they? All they need to know is that the application failed. So in general, you do not catch exceptions. Just let PHP handle this. The only time when you catch an exception is when you actually want to solve the problem or do something special with the error. OK, let's say it's absolutely crucial to tell the user that their data hasn't been inserted (as opposed to some other problem). Then you still wouldn't stop the whole error procedure. You'd add your information and then rethrow the exception. But again: In general, you do not catch exceptions. They work just fine without human intervention.