Jump to content

erikla

Members
  • Posts

    41
  • Joined

  • Last visited

Posts posted by erikla

  1. Sorry, but I am still puzzled. Should I change the direct error message, implemented with an echo 'A Technical error ocurred' like above, with for example a header to direct to the error page, having a size of 512 bytes or more?. Like this:

    <?php
    
    function handle_fatal_errors() {
    	if (http_response_code() == 500) {header("Location: error_page.php");}
    }
    
    register_shutdown_function('handle_fatal_errors');	
    ini_set('display_errors', 0);
    

    Erik

  2. 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.

     

    I am unsure what you mean here? Isn't it the size of the file, where the fatal error occurs, that IE wants to be bigger than 512 B? If so it doesn't work to link to an image which size is sufficient big! Please explain.

  3. Thanks Jacques1 for the basic HTML template. I like to get it explicit like here! I will try it out.

     

    I found a nice page about the issue of character sets her: Handling UTF-8 in JavaScript, PHP, and Non-UTF8 Databases

     

     

     

    If you don't know how to transcode files your editor, you can use Notepad++.

     

     

    I guess I found out how to watch and edit the encoding in Dreamweaver: Using the keyboard shortcut Ctrl+J. 

     

     

    Seems like the issues with character sets is in website development what color management is in image processing: A mess, or at least hard to comprehend. I assume that the pain with character sets has its roots in history: That the web teams didn't choose the right approach at the very beginning, so it has been a "stop-gap solution" or kludge.

     

    Erik

  4. Thanks for the input, CroNiX and Jacques1 for the many details. I appreciate it.

     

    To be honest I know very little about the meaning of the special declarations accompanying the HTML file. I don't really know the difference between XHTML, HTML 5 and adding "transitional", etc. Until now I have just produced a webpage by opening a standard HTML file in a WYSIWYG program (Namo). I am perfectly sure, Jacques1, that you don't like that approach at all - not controlling every tiny detail. At the moment I don't have the energy and time to make a lot of changes in this regard on every page in my website, but in the future it is certainly something I should be aware of. I like your links. Would it be appropriate to change my header.html to the following (taken from one of the pages you linked to!):

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      <title>Guestbook</title>  
    
      <LINK REL=stylesheet TYPE="text/css" HREF="generel/pop_style.css">
      <LINK REL=stylesheet TYPE="text/css" HREF="generel/hoved.css">
    </HEAD>
    
    <BODY leftmargin=0 topmargin=0 marginwidth=0 marginheight=0 background="generel/univback.gif">
    
    <script type="text/javascript" language="JavaScript1.2" src="generel/pop_core.js"></script>
    <script type="text/javascript" language="JavaScript1.2" src="generel/pop_data.js"></script>
    <script type="text/javascript" language="JavaScript1.2" src="generel/pop_events.js"></script>
    
    <!--etc .......
    

    What I am worried about is that the initial HTML declaration changes might have the affect that old code doesn't display properly anymore. I should certainly learn more about these declarations in the future. I will however never be able to make any bigger changes in the javascript files controlling the dropdown menu. I have downloaded it from a webpage (Twinhelix.com) and customized it. It is simply too complicated - A very advanced dropdown menu! 

     

     

    ... and you have to convert all existing files (HTML, JavaScript, CSS) into UTF-8.

     

    This could be possible, but how do I change these files to UTF-8?

     

    Until now I have never had a problem with character sets on my web hotel, and when I upload my changes to the web server, the problems I have locally might even disappear. But for sure it is not satisfying not to know how to control it. As I mentioned in another thread my only page in English is here:

     

    http://www.matematiksider.dk/enigma_eng.html

     

    All of the rest is in my native language, which is Danish. The good thing is, that so far I have succeeded in transforming my old guestbook code to PDO and making other changes. I feel I am adapting to PHP/MySQL better and better. I will soon upload my changes to my web-hotel ...

     

     

    Erik

  5. I have had a thread here recently titled: Special Language characters doesn't display correctly. Now however, I have encountered a new problem with character sets, that I hope you can help me resolve! I find the concept of character sets quite confusing. When you are dealing with a database and want the content to be displayed on a web page, you obviously want it to be displayed correctly, and if you are not from an English speaking country, this could cause you some problems here and there due to international characters. As I have understood, one need to tell how the data (text) is stores in the database, how it is being interpreted (collation) and how it is being displayed on the web page.

     

    Here is my situation:

    One php page is displaying the content of a guestbook: show_content. This php file is divided into three parts: An include of a header.html file, a middle section displaying the content of the database and finally an include of a footer.html file to take care of the lower part of the page. Now, the header.html file does contain the script for a dropdown menu written in javascript:

     

    header.html

    <html>
    
    <head>
      <title>Guestbook</title>
      <meta http-equiv="Content-Language" content="da">
      <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    
      <LINK REL=stylesheet TYPE="text/css" HREF="generel/pop_style.css">
      <LINK REL=stylesheet TYPE="text/css" HREF="generel/hoved.css">
    </HEAD>
    
    <BODY leftmargin=0 topmargin=0 marginwidth=0 marginheight=0 background="generel/univback.gif">
    
    <script type="text/javascript" language="JavaScript1.2" src="generel/pop_core.js"></script>
    <script type="text/javascript" language="JavaScript1.2" src="generel/pop_data.js"></script>
    <script type="text/javascript" language="JavaScript1.2" src="generel/pop_events.js"></script>
    
    <!--etc .......
    

    The main page controlling this header:

     

    show_content.php

    <?php
    
    function handle_fatal_errors() {
    	if (http_response_code() == 500) {echo 'A technical error ocurred.';}
    }
    
    register_shutdown_function('handle_fatal_errors');	
    ini_set('display_errors', 0);
    
    include("header.html");
    include("settings.php");
    header('Content-Type: text/html; charset=utf-8');
    
    //etc ...
    
    

    The footer.html file doesn't really matter here, so I avoid it.

     

    Now the strange thing: When I execute the show_content.php file above, the content of the database (guestbook) display perfectly, but the International letters in the dropdown menu don't display properly. BUT if I out-comment the following line:   

    header('Content-Type: text/html; charset=utf-8');
    

    in the show-content.php file it is the opposite way around!! Then the items in the dropdown menu display properly while the content of the guestbook don't!

     

    By the way: When I connect to the database to store items, I do it with the following code:

    $db = new PDO('mysql:host='.$server.';dbname='.$database.';charset=utf8mb4', $username, $password);
    

    If somebody have an idea for an explanation of this behavior, I will be happy to hear about it! To me all these character set issues seem rather overwhelming. Maybe one setting override the other or what?

     

    NB! I also read that the people around the developement of PHP temporarily gave up on Unicode support for a PHP 6.0 version ...

     

    Erik

  6. Thanks, Jacques1! This is about the most silly thing I have ever heard. Imagine you have used a lot of time to create the most lean code and feeling really satisfied about it. Then you need to fill it up with garbage to make IE eat it properly! I assume you prefer Firefox over IE? Unfortunately we need to take into account that a majority of people still use that browser. 

     

     


    You can either create a complete HTML error page right now or ignore Internet Explorer until you have one.

     

    I don't know what you mean with a "complete HTML error page or how much work it will take?

     

    Erik

  7. Sorry I am getting back, Jacques1, but I have encountered a problem, which I hope you can resolve: I have been using your suggestion, placing the following code at the top of my php page (the page showing the content of my guestbook):

    <?php
    
    function handle_fatal_errors() {
    	if (http_response_code() == 500) {echo 'A Technical error ocurred';}
    }
    
    register_shutdown_function('handle_fatal_errors');	
    ini_set('display_errors', 0);
    

    As I told you yesterday, that if I changed the password to a wrong one and updated the page, it did correctly show the phrase "A Tecnical error ocurred", as expected. If I however in Dreamweaver start a new instant of Internet Explorer by hitting Preview in Browser > Preview in Internet Explorer, then an error page is shown named "An Internal Http 500 server error ocurred" and not a page with the desired text above. This is really strange: If creating a new page when the password is wrong, an error page is displayed, but when updating a page in which the script has been executed with the correct password previously, the correct phrase is shown. When I make previews in Firefox and Chrome, it works properly in both situations, however. Can you explain this behavior and tell me a fix to make it work in Explorer too?

     

    Erik

  8. 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.

     

     

    I completely agree with you. I have been wondering while going from one tutorial to another: I often immediately get a feeling I have somehow seen this before. Sometimes it is even the very same examples they use, maybe only shuffled around a bit. It is a pity when people offering tutorials don't think for themselves and show their own experiences, rather than mimicing others. I feel I get better information from books (also larger web solutions), although they may probably also copy other peoples bad taste from time to time. Then it is great to have a Forum like this, where things can be questioned and you can eventually read about different solutions from different developers.

     

    I see there are a few tutorials at phpfreaks.com. Unfortunately some of them dealing with MySQL are outdated, since using predecated stuff like mysql_*. Also there have been no new tutorials since 2010. With your experience and knowledge you should consider writing one with a typical database problem in PDO - if you have time and like to of course. It could be very helpful and people here could refer to it when people ask similar questions. It should not just be code snippets, but a little larger application to show the user the bigger picture. Typical examples would be a guestbook or registration in a usergroup (intermediate degree of difficulty, I guess). I myself is maintaining a couple of webpages with mathematical content. Here is a link to the only page I have written in English. The rest is in Danish, my native language. But it is a large page: http://www.matematiksider.dk/enigma_eng.html. In fact my guestbook isn't working properly here and that's why I am posing all these questions here ;)

     

    NB! My web hotel is www.one.com. I guess it has the necessary setup.

     

    Thanks,

     

    Erik

  9. You are right, Jacques1, I am a stubborn chap. Thanks to your patience you finally broke through my shell ;)

     

    I have tested your suggestions by adding your code pieces and commented out the try-catch parts. Then I changed the password to a wrong one and executed the page. It is correct that without the error handler, I received a blank page, and when I included it, I got the error message without any bad messages. I like this better far better than creating exceptions.

     

    What I don't understand is then, why these tutorials (both in print and YouTube videos) pay so much attention to these exceptions. At least when it is only error reporting, and it is in most cases, I guess, it seems obsolete ...

     

    NB! I haven't tested if my web hotel has v. 5.4+ of php, but I assume it has.

     

    Again thanks a lot!

     

    Erik

  10. I disagree with you Jacques1, when you say that this thread is heading in the wrong direction. I can say, because it was me starting this thread. This topic about error handling (the words should probably have been indicated in the thread title) is in the core of my attention. When earlier using mysql_' and mysqli_* it seemed easier to handle the situations when problems occurred in connection with the database, because you could create a function (procedure) which could connect to the database if possible and just stopped with a die() if it couldn't. To me that was logically easier. Now I realize from what people tell me here, that using exit() and die() is in fact something which you should not use. Then here comes in the new way with PDO, which besides from having several important advantages regarding security, is handling database problems with exceptions. To learn to use PDO I have only seen small snippets of code. I think this fact made me put more emphasis on this catching exceptions than is really appropriate. I guess that is what Jacques1 is trying to tell me (please tell me if I am wrong).

     

    What I am really missing is watching a longer piece of code dealing with PDO. It could be a real-World solution of a guestbook, registration at a website or the like. I have been pre-ordering a book at Amazon, but it won't be ready in half a year or so. I need to see how people really are paying attention to error-handling, database errors as well as php errors. If you know of any source I would be happy to watch it.

     

    At the moment the structure in my show_content.php file, showing the content of the guestbook, is the following:

    <?php
    
    try {
    
      //A big block of code: Interaction with the database and php to manipulate it
    
    } catch(PDOException $ex) {
    
      //echo "Could not show content in guestbook";
    
    }
    
    ?>
    

    It is maybe not the best way to do it, but it will catch any problem with the database. I mean: Any problem with the database not being able to connect or to insert or retrieve data will be handled with an exception and not with some server error messages, which I fear. I wish I could just put the try-catch block around only the code which has to do with database interaction, making it more readable, but if I do and there is a database problem, the code below the try-catch block will get executed after the exception and it will likely cause php errors. Therefore I see no other way than putting all of inside the try section. Is that "catching the exception at top level"?

     

    I am sorry that I have confused my intentions in this thread, probably due to my lack of experience and overview. My questions haven't been accurate and concise, I now see. Maybe you got the impression that I was looking for a very sophisticated kind of error-handling. I don't want to over-do things, though. On the other hand I don't want the server to write any database error messages which could be confusing and maybe reveal something about the database. I feel I can better control errors caused by the php code, because I am debugging things thoroughly locally using Xampp and it is more of a logical problem - although I can of course overlook something here too, which could eventually result in php errors. 

     

    Thank you, Jacques1, for the code to force the server to handle errors in a specific way. I now see it is also mentioned in Ullman's book. Good to know even if I won't use it now. Also thanks for the error-handling function, kicken. Finally I watched your website, mogosselin. Looks good. I will look at it later ...

     

    Erik

  11. Depending on how you have PHP setup with the server, how PHP is configured, and how the server is configured then not catching an exception could range from getting a stack trace printed to the screen to a simple 500 error message with no useful information printed. I believe what Jacques1 is suggesting is that you should make sure PHP logs the error rather than reports it, and then returns the 500 error. You could then configure the server to send back a nicer page for the 500 error by using it's error document configuration

     

    That's all fine and dandy if you have that level of control over your setup, but you may not (ie, shared hosting) so I personally dis-agree and would rather perform a generic try/catch at the top level and generate an error page manually with PHP. It's less prone to mis-configuration issues and does not add a lot of extra programming work or overhead.

     

    That's exactly what I like to hear kicken! Right, I have no control over my Web hotels configuration at the moment, so I rather prefer to have my php code make an exception in order NOT to have the web server write out a lot of garbage, which could confuse the user and maybe even reveal something which would make my database less secure. Maybe later, if I manage to get more knowledge about how to turn off error reporting at the server at my web hotel, I will think about doing it in another way. And I promise, Jacques1, to ask in another thread then, so the this thread won't turn out too 'bulky' so to say :happy-04: .

     

    Also - since both of you advice me to - I will stay with PDO and try making it work. I am currently working on displaying the content of my questbook in File 4 and hope I will succeed.

     

    One question: I am a bit puzzled about the term 'catching an exception at the top level'. At the moment when working on File 4, I have a big section of code (in fact all of it) included inside the try section. One can easily loose the overview, but I try to make comments along the way. I have been looking for ways to handle the try thing with a function/procedure  call, but have not found an obvious way to do so. Maybe it is good enough the way I do it ...

     

    Again I appreciate your replies. I feel I am getting closer to the goal!

     

    Erik

  12. Thanks, Jacques1, for pinpointing my (many) misunderstandings. I am a mathematician trying to 'dig' into PHP/MySQL without any formal education in this language. Regarding sql injection I now understand better. It can only occur if the query contains dynamic parameters. It also helped reading the Wikipedia article about the subject. Here an explicit example is being displayed in which the user can make a certain input, which unintentionally would change the query completely, typically from a limited SELECT query to a SELECT query involving all records from the database. For example a user in a usergroup would be able to retrieve not just his own data, but the data from all user! Prepared statements then solve the problem of having the user's input "glued" together with the servers part of the query to make an unfortunate query, by handling the servers part and the users input separately.   

     

    Regarding try-catch, then I am unsure if I am understanding what you mean: Should I avoid using the try-catch operation at all?  If so, I know of no way to take care of the situation in which one cannot connect to the database (Maybe the webhotel is down?) or I have accidentally delivered a wrong password or the like. Without using try-catch the user will receive an error message from the server, which is quite complicated and which could reveal something about the filenames and more ... Now I am actually considering going back using mysqli instead of PDO, because Ulmann's book is using exactly that and PDO is so new, there does not seem to be many books about it (if any) yet. I am simply missing some material (books, articles or pdf files on the Internet) containing practical code in real-World problems to be able to really getting to grips with it. The PDO Tutorial for MySQL Developers on Hashphp.org is pretty good as an overview article, but I need more examples on how to use PDO. I haven't been able to find anything useful, though. It is a pity, because I was adviced to use PDO on this site ...

     

    Erik 

  13. Thanks to both of you! I have now removed one of the try-catch blocks and added code for validating user input in the fields name, email and contribution and one more: antispam. The latter is a precaution I have used earlier to prevent spam entered into the guestbook by code - after actually having encountered it! I just ask people to write "seven" as a number in an additional field in the form. I have tried Captchas earlier but don't really like them - they can be hard to figure even for a human! It works perfectly with this easy question.

     

    Because of your comments, kicken, I avoided using the mysqli_real_escape_string(). I am however still a bit worried that although malicious code can not do any harm when entered using the PDO prepared statement, it still is entered unchanged into the database, and eventually could cause harm later, when it is handled in the database by maybe non prepared statements, or are these worries unfounded? I mean when I later want to display all contributions in the guestbook in File 4, I assume I cannot do the SELECT query as a prepared statement, since there are no parameters present?

     

    Regarding using require or require_once, I will actually need to use the database connection again later, when the content of the database is displayed - via another php page (File 4). So maybe I better use just require? Is the require_once a security measure? Why not just use require all the time?

     

    Jacques1, I understand your point that it is important that any error messages should be useful for the user, not just for the person, who wrote the script. I hope it is better now?

    <?php
    
    $ip = $_SERVER['REMOTE_ADDR'];  //Collecting users IP address 
    $name = trim($_POST['name']);  //Data from input form etc.
    $email = trim($_POST['email']);
    $contribution = $_POST['contribution'];
    $antispam = $_POST['antispam'];  //Collecting an answer to prevent spam
    
    $errors = array();  //An array to collect input errors from the form. Here it is initialised
    
    if ($antispam != 7) {$errors[] = 'Your answer in the antispam field is incorrect or missing.';}
    if (empty($name)) {$errors[] = 'You forgot to enter your name.';}
    if (empty($email)) {$errors[] = 'You forgot to enter your email address.';}
    if (empty(trim($contribution))) {$errors[] = 'You forgot to deliver a contribution.';}
    
    if (empty($errors)) {  //If no errors from the form, we proceed to the database to enter details ...
    
      try {
    	require("gb_connection_guestb.php");  
    	$stmt = $db->prepare("INSERT INTO guestbook(`time`, `ip`, `name`, `email`, `contribution`) VALUES(NOW(), ?, ?, ?, ?)");
    	$stmt->execute(array($ip, $name, $email, $contribution));  //Inserting the new contribution with details into Guestbook
    	$db = NULL;  //Closing database
    	  
    	header("Location: gb_show_content.php");  //Redirecting to the page which will show the content of the Guestbook
    	
      } catch(PDOException $ex) {
    	echo 'Could not enter your contribution in the database. We apologize for the inconvenience!'.'<br/>';
      }
      
    } else {  //If errors they are displayed and the user encouraged to use the back-button in the browser ...
      
      echo '<h1>Fejl!</h1><p>The following error(s) occurred:</p></br>';
      foreach ($errors as $msg) {echo $msg.'</br>';}
      echo '</br>'.'Use the Back button in the Browser and correct your input in the form.';
    }
    
    
    ?>
    

    Notice that I have used the trim operation to remove any white spaces before and after name and email address, also to handle errors better ...

     

     


    A big try-catch block on the top level doesn't make sense either, because most PHP errors are not exceptions, which means they aren't affected by this at all. And again: Why not just use the standard error procedure?

     

    I am not completely sure about what you mean here, Jacques1? Should I still change something?

     

    I am a little unsure how to handle eventual error messages for my own debugging purposes?

     

    Again big thanks for your advice!

     

    Erik

  14. Thanks, it helps a lot! I tried your suggestions and now it works.

     

    It is actually a guestbook. File 1 contains the connection details (connect.php), File 2 is containing a html form, which is supposed to be filled out by the user and the input is posted to File 3, which will try to insert the contribution from the user, including details, into the database table - guestbook. When this is accomplished, the php code will redirect to File 4, which will then display the content of the guestbook. Here is the php code of File 3, that you helped me write:

    <?php
    
    header('Content-Type: text/html; charset=utf-8'); //Ensuring the correct charset
    
    $ip = $_SERVER['REMOTE_ADDR'];  //Collecting users IP address 
    $name = $_POST['name'];  //Data from input form etc.
    $email = $_POST['email'];
    $contribution = $_POST['contribution'];
    $antispam = $_POST['antispam'];
    
    try {
      require("connect.php");	
      try {
        $stmt = $db->prepare("INSERT INTO guestbook(`time`, `ip`, `name`, `email`, `contribution`) VALUES(NOW(), ?, ?, ?, ?)");
        $stmt->execute(array($ip, $name, $email, $contribution));  //Inserting the new contribution with details into Guestbook
        $db = NULL;  //Closing database
        header("Location: show_content.php");  //Redirecting to the page which will show the content of the Guestbook
      } catch(PDOException $ex) {
        echo 'Could not insert into Guestbook'.'<br/>';
      }	    
    } catch(PDOException $ex) {
      echo 'Could not connect to database'.'<br/>';
    }
    
    ?>
    

    I have yet another question: As you can see, I have added a try-catch inside the first one to take into account if the connection to the database will succeed, but the insert query will not succeed. Am I right when I assume that this is a possible scenario even if you don't make any syntactical errors? I don't really know how the database behave ...

     

    I know I should write some log file to collect information for debugging purposes. Besides, my next step will be to handle the user input. I need to validate if the user input is appropriate (in the name, email and contribution fields). The user could have forgotten to fill out a field or he could have entered malicious code. Now I know PDO is not vulnerable to sql-injection, but would it be a good thing to put the contribution through a mysqli_real_escape_string() anyway?

     

    Third question: would it be better to use require_once(connect.php) instead of just require(connect.php)?

     

    I will be delighted if you could clarify my last three questions above. Then I will use some of the technique explained in Ullmans book to accomplish the validation. Again thanks a lot!

     

    Erik

  15. I have been reading in Larry Ullmans book "Visual QuickPro Guide PHP 6 and MySQL 5" and I find it well-written. Since it is from 2008, it does not contain anything about MySQL PDO, but rather does it in the mysqli_* way. Larry suggest placing the secret database password and more along with a database connection script in a connect.php file, placed above the webroot if possible. Then later, when he is creating queries and executing them in other php files, he includes the connect.php file before making the queries.

     

    Now I know it is very important to be careful with the Error handling, so the script won't output errors, which could reveal something about the database making it less secure. Therefore I am wondering how to structure things when using PDO. I need to write error-handling scripts for the following situations:

     

    a) Connection to the database doesn't succeed

    b) The execution of the queries doesn't succeed

    c) User input in HTML forms are not appropriate

     

    and probably more. The recommended way of handling errors when using PDO seems to be writing some try-catch code. But then I don't see how I can keep the connection to the database completely inside the connect.php file. Either I will need to use a die() or exit() inside this file or I will need to give up my idea to keep everything which concerns the connection to the database in the file mentioned AND write nested try-catch sentences - first make sure the connection works, then make sure the query will execute properly.

     

    I don't like either of those approaches. Firstly I have been told that using exit() is bad programming and secondly it seems to get more complicated using nested try-catch code and to let database connection take part in diverse php-files.

     

    Maybe somebody have a smart, convenient and secure way to do it?

     

    Erik

     

  16. I see your point that there are no variable values to be substituted, but maybe still it would have the advantage of being faster, since the sql statement will be compiled first. I am especially thinking about the formatted datetime. Maybe I am totally wrong here. I am not an expert. That's why I am asking.

     

    Erik

  17. You are right, Psycho, that the formatting shouldn't take place when inserting in the database, but rather when selecting from it. My mistake! Here is the output from my database (guestbook) with the following fields: id, time, ip, name, email and contribution. I had a hard time figuring the syntax when including the datetime-formatting into the select statement. I hope it looks OK now? At least it works. I have named the formatted time field 'ftime'.

     

    By the way: Is there a way to turn the select statement into a prepared statement? I guess you guys prefer these ...

    try {
      $db = new PDO('mysql:host='.$server.';dbname='.$database.';charset=utf8mb4', $username, $password);  //Connecting to database
      $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    
      $sql = "SELECT id, name, email, date_format(time, '%e/%c %Y, %H:%i') as ftime, contribution FROM guestbook order by time";
      foreach ($db->query($sql) as $row) {
    	echo "<hr>";
    	echo "Contribution number: ".$row['id']."<br/>";
    	echo "Time: ".$row['ftime']."<br/>";
    	echo "Name: ".$row['name']."<br/>";
    	echo "Email: ".$row['email']."<br/><br/>";	
    	echo nl2br($row['contribution'])."<br/>";
    	
      $db=NULL;  //Closing database	
      }
    } catch(PDOException $ex) {
    	echo "An error ocurred";
    }
    

    Sorry that my questions more and more have turned into a MySQL question. Initially I thought it would be a php question ...

     

    Erik

  18. Thanks! Your reply certainly addresses some of my concerns about using the strtotime() and data() functions. So I understand you advice me to do the formatting directly on the MySQL level, right?. What will the syntax be, if I may ask more detailed? At the moment my code for inserting into my database is (using PDO):

    $stmt = $db->prepare("INSERT INTO guestbook(`time`, `ip`, `name`, `email`, `contribution`) VALUES(NOW(), ?, ?, ?, ?)");
    $stmt->execute(array($ip, $name, $email, $contribution));
    

    Regards,

     

    Erik

  19. Interesting Thread! I have often thought about how safe database passwords really are. At my former Web Hotel they offered a directory below the root of the webpage. Here I placed the php-file (say passw.php) containing the password and linked to it from the other php files with a require(passw.php) command - better than include, I have been told. Then I changed webhotel and the new one didn't have any directories below the webroot. So I wondered if it was now less secure. After asking, I trusted their explanation that it isn't necessary. 

     

    As from what has been discussed above, I conclude that the password cannot be accessed by strangers if it is placed in a php-file, unless other files on the site, for example pages with HTML forms, are vulnerable to sql injection OR if certain settings in the web hotel allow for free downloads OR if people working at the webhotel accidentally makes any mistakes, which will exploit the site ... I hope this is correct? 

     

    I have never considered the different settings at my web hotel. I hope the default settings are so that people cannot download freely. What should I be looking for?

     

    From what I read from your last contribution, gizmola, I understand that you suggest that the file containing the database password should NOT be placed below the webroot and even in the webroot. Is that correct? Then it could be in a folder just above the root ...

     

    Thanks for a great Forum!

     

    Erik   

  20. I have selected datetime values from a MySQL database (originally stored with the NOW() method) and want to present them on a page formatted in a specific way. I succeded in making it work with the following php code:

    $time = date('d/m Y H:i', strtotime($row['time']));
    echo $time;
    

    I am however unsure if this is the best way to do it? I noticed some comments at php.net stating that this method has some limitations due to UNIX time. I am confused. There seem to be many ways of formatting date and time. Maybe somebody can clarify the situation, and tell me what will be appropriate in the current situation? I will appreciate any suggestions ...

     

    Erik 

  21. Dear people here at phpfreaks

     

    I am working on updating an old guestbook with outdated code (predecated). I will follow the suggestions I have received here on this forum already by using the new MySQL PDO technique. I am pretty rusty on PHP and MySQL, since I haven't been using it for years. So it took me a while to get Xampp running and installing Virtual hosts, so I can test my code locally. This is all working now. I have decided to start from scratch, building my guestbook up gradually in order to be able to understand each step better. I am inspired by the following tutorial:

     

    http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

     

    So far I have created four files

    1. contribution_to_guestbook.html

    2. put_in_guestbook.php

    3. show_content_of_guestbook.php

    4. mysql_functions.php

     

    The guestbook is implemented as a table with the name guestbook in the MySQL database with the name my_database. The database contains six fields, which are: id, time, ip, name, email and contribution. The user can write a contribution by filling in his name, email address and contribution in the form placed in the first file. These data for the fields name, email and contribution respectively are being sent to the second file. At the same time the datetime is automatically registered along with the IP address of the users computer in the fields time and ip. When inserted in the table in the database via the second file, the primary field id is automatically added and incremented by 1. After the insertion in the database, the user is directed to file 3, where the content of the whole guestbook is being displayed for the user to see. The 4th file is containing the connection details for the database, including the password. 

     

    NB! The IP address of the users computer is not being displayed but only collected in the case one want to block spammers from specific computers with fixed IP addresses. In order to better block for spam from computer bots, I will later place a question in the first file to only admit humans ...

     

    My questions

    1. Is the structure of my guestbook convenient? Would it be appropriate to create functions to make the code more readable and if so, how can I do it?
       
    2. I wanted to make a prepared statement in the 3. file in which I select the content on the guestbook in order to display it. Can it be done, and if so how do the code look like?
       
    3. I know I need more error handling. Also I need to test user input. For example if no contribution is being written, an error message should be shown to the user, etc. Do you have some suggestions here and how to do it?
       
    4. What about security? I hope the password for my database will not be accessible in any way?

     

    I will appreciate any comments on the four questions above and eventual something else I have overlooked! I hope my thread is not too long. Hope for some replies ...

     

    Here is my code so far (still just a framework!):

     

     

    1. contribution_to_guestbook.html

    <!doctype html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Contribution to Guestbook</title>
    <style type="text/css">
    body,td,th {font-family: Verdana, Geneva, sans-serif;}
    form1 table tr td {color: #06C;}
    h1 {color: #0000A0;}
    </style>
    </head>
    
    
    <body>
    <form method="POST" action="put_in_guestbook.php">
    
    <h1>Contribution to Guestbook</h1>
    
    <table border="0" cellspacing="5" cellpadding="5">
      <tr>
      	<td>Name</td>
        <td>
        <INPUT type="text" name="name" size=40 maxlength=100>
        </td>
      </tr>
      <tr>
      	<td>Email</td>
        <td>
        <INPUT type="text" name="email" size=40 maxlength=100>
        </td>
      </tr>
      <tr>
      	<td valign="top">Contribution</td>
        <td>
        <TEXTAREA name="contribution" cols=60 rows=10></TEXTAREA>
        </td>
      </tr>
      <tr>
        <td></td>    
        <td align="center">
        <INPUT type="submit" value="Submit contribution">
        </td>
      </tr>
    </table>
    </form>
    <p></p>
    
    
    
    </body>
    </html>
    

    2. put_in_guestbook.php

    <?php
    
    require("mysql_functions.php");
    
    $ip = $_SERVER['REMOTE_ADDR'];  //Clients IP address collected
    $name = $_POST['name'];  //Data from input form etc.
    $email = $_POST['email'];
    $contribution = $_POST['contribution'];
    
    try {
      
      $db = new PDO('mysql:host='.$server.';dbname='.$database.';charset=utf8mb4', $username, $password);  //Connecting to database
      $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
      
      $stmt = $db->prepare("INSERT INTO guestbook(`time`, `ip`, `name`, `email`, `contribution`) VALUES(NOW(), ?, ?, ?, ?)");
      $stmt->execute(array($ip, $name, $email, $contribution));  //Placing the new contribution with details in Guestbook
      
      $db = NULL;  //Closing database
      header("Location: show_content_of_guestbook.php");  //Redirecting to another page to show content of guestbook  
      
    } catch(PDOException $ex) {
    	echo "Could not insert into guestbook";
    }
    
    ?>
    
    

    3. show_content_of_guestbook.php

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf8mb4" />
    <title>Guestbook</title>
    </head>
    
    <body>
    
    <?php
    require("mysql_functions.php");
    
    header('Content-Type: text/html; charset=utf-8');
    
    try {
      $db = new PDO('mysql:host='.$server.';dbname='.$database.';charset=utf8mb4', $username, $password);  //Connecting to database
      $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
      
      foreach ($db->query('SELECT * FROM guestbook') as $row) {
    	echo "Contribution number: ".$row['id']."<br/>";
    	echo "Time: ".$row['time']."<br/>";
    	echo "Name: ".$row['name']."<br/>";
    	echo "Email: ".$row['email']."<br/>";
    	echo "Contribution: ".$row['contribution']."<br/>"."<br/>";
    	
      $db=NULL;  //Closing database	
      }
    } catch(PDOException $ex) {
    	echo "An error ocurred";
    }
    
    ?>
    
    </body>
    </html>
    

    4. mysql_functions.php

    <?php
    
    $server = 'localhost';
    $username = 'root';
    $password = 'my_password';
    $database = 'my_database';
    
    ?>
    

    Regards,

     

    Erik

  22. I tested the option of just changing the DocumentRoot in the httpd.conf file as suggested by fastsol and figured it to work right away. It is absolutely an option, because it is so simple.

     

    Regarding creating a VirtualHost, or even several Virtualhosts, it looks more elegant in the way that one doesn't need to include subdirectories in the URL when watching pages locally in the browser. Unfortunately the procedure to make the VirtualHosts work is not so simple. I tested your code thoroughly, Ch0cu3r, but it didn't work! The link to Apache.org delivered by trq didn't bring me much further to the goal. I don't like the style in Apache.org in general. Often it only states how things should be done, and not WHY. I need explanations in order to understand the logic behind the procedure. At least the explanations at Apache.org are very sparse. I find that if one doesn't understand the structure beforehand, one won't learn anything from looking into the Apache.org documentation. So I went on Googling for other explanations. I found the following pages to be helpful, delivering much better explanations:

     

    http://foundationphp.com/tutorials/apache_vhosts.php

     

    http://www.apptools.com/phptools/virtualhost.php

     

    In general different pages deliver different procedures on how to create VirtualHosts. It seems somewhat shaky in the sense that if you don't do it in the exact right way, it won't work, and it is difficult to find out what is wrong. For example one should be aware of opening the different files as administrator by rightclicking on Notepad in the Start menu. Secondly the procedure to make VirtualHosts work seems to have been changed in recent versions of Apache. That's at least what I conclude after watching several webpages delivering procedures, which don't work anymore. Anyway, after having used several hours of this subject I finally made it work. Here is how I did:

     

    I have two sites named site1 and site2 located at D:\site1 and D:\site2. I decided to name the VirtualHosts site1.local and site2.local as suggested by one of the pages above. Then I made changes to three different files. Two of them located in the Xampp directory (I have Xampp installed) and the third is a Windows system file:

     

    C:\xampp\apache\conf\httpd.conf

    C:\xampp\apache\conf\extra\httpd-vhosts.conf

    C:\Windows\System32\drivers\etc\hosts

     

    Make sure to have Windows Explorer set to show all files (also system files), or you won't see anything. Also after having opened Notepad as Administrator by rightclicking on it in the Start menu, one also needs to look for all files *.*, not just text files as the default *.txt. Again if you don't, you can't see the files. Now to the changes:

     

    In the httpd.conf file, I made sure that the comment-sign # in front of the below Include line was removed. I think it is already removed in the newer versions of Apache, but apparently wasn't in earlier versions:

    Include conf/extra/httpd-vhosts.conf
    

    In the hosts file in the Windows system, I added two lines at the end of the file: 

    127.0.0.1 site1.local
    127.0.0.1 site2.local
    

    The httpd-vhosts.conf file need the most changes. At the bottom you should place the VirtualHosts commands, in which the DocumentRoot and ServerName for each VirtualHost is listed. Notice that it is a good idea also to make a VirtualHost to the localhost. If you don't, you won't be able to use localhost, and maybe more severe: You won't be able to use your local phpMyAdmin! Higher on your page you need to write a Directory command. If you don't, you won't be able to locally access subdirectories via the browser. Finally you should remove the # sign in front of the NameVirtualHost *:80 command already in the file. 

    ...
    
    <Directory D:>
        Require all granted
    </Directory>
    
    ...
    
    # The line below is originally commented out. The #-sign should be removed to make it take action:
    NameVirtualHost *:80
    
    ...
    
    <VirtualHost *:80>
       DocumentRoot C:/xampp/htdocs
       ServerName localhost
    </VirtualHost>
    
    <VirtualHost *:80>
       DocumentRoot D:/site1
       ServerName site1.local
    </VirtualHost>
    
    <VirtualHost *:80>
       DocumentRoot D:/site2
       ServerName site2.local
    </VirtualHost>
    
    

    Finally when you have made the changes in the three files and having saved the files, it is important that you close and open the Apache server, before you can see the changes having taken action. You can close and open the Apache server in the Xampp Control Panel by hitting a button on the line with the Apache server. And then start it again by hitting it again. Now hopefully things should work for you. You can test it by writing the following URL in a browser:

     

    http://site1.local

     

    assuming you have an index.html file in the root of your site (else add the filename to the URL:  http://site1.local/somefile.php

     

    Questions: I am not sure why it is necessary and even if it is necessary to uncomment the line NameVirtualHost *:80 in the httpd-vhosts.conf file. If someone know, I would like to hear it. Secondly I am not sure if the "Require all granted" line in the Directory command is the right one to use. Some other websites deliver other commands, but it can have to do with old versions of Apache. I am not sure. I guess it has security questions also. I will appreciate any comments on that too. 

     

    At least my Virtual Hosts work now :)

     

    Regards,

     

    Erik

  23. Thanks fastsol. I will consider using it. At the moment I am however not sure which way to do it. My situation is, that I have two websites operated on the same computer, and I would like to avoid having to switch the settings in the httpd.conf file whenever I change working from one website to the other. At the moment my local mirrorpages (with subdirectories) are located side by side: D:\site1 and D:\site2.

     

    I found the webpage trq linked to directly at Apache.org difficult to follow. I found another page discussing the issue. Maybe they have a better way to do it? I will appreciate any comments on this.

     

    http://stackoverflow.com/questions/1408/make-xampp-apache-serve-file-outside-of-htdocs

     

    Regards,

     

    Erik

  24. Thanks a lot! I see one needs to make sure about characters issues on at least three levels. Now my initial problems occurred due to having manually created a database within phpMyAdmin. I wanted to upload a screenshot on how the structure of my table in phpMyAdmin is with the proper settings, but apparently users are not allowed to upload images in this Forum.

     

    I have now rewritten my bad code above now using MySQL PDO. What this page does is to connect to the database "haka" and displaying the content of the table "gaestebog". I hope my character settings are fine now - and mysql code too?

    <!DOCTYPE html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf8mb4" />
    <title>Untitled Document</title>
    </head>
    
    <body>
    
    <?php
    
    header('Content-Type: text/html; charset=utf-8');
    
    $server = 'localhost';
    $brugernavn = 'root';
    $kodeord = '***************';
    $database = 'haka';
    
    try {
      $db = new PDO('mysql:host='.$server.';dbname='.$database.';charset=utf8mb4', $brugernavn, $kodeord);
      $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    } catch(PDOException $ex) {
    	echo "Der forekom en fejl";
    }
    
    foreach ($db->query('SELECT * FROM gaestebog') as $row) {
    	echo "ID: ".$row['id']."<br/>";
    	echo "Tid: ".$row['tid']."<br/>";
    	echo "IP adresse: ".$row['ip']."<br/>";
    	echo "Navn: ".$row['navn']."<br/>";
    	echo "Email: ".$row['epost']."<br/>";
    	echo "Indlæg: ".$row['indlaeg']."<br/>"."<br/>";
    }
    
    ?>
    

    NB! I should probably place the foreach block within the try section ...

     

    Regards,

     

    Erik

×
×
  • 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.