Jump to content



Highest Reputation Content


#8885 One Mod Rewrite Rule Won'T Work

Posted by HartleySan on 28 July 2012 - 10:59 AM

If "hiv" is never followed by an e, you could change the one regex as follows:
^hiv[^e]|aids[a-z_\-\./]*$
  • 4


#6644 Just Started This Book Today!

Posted by rob on 26 March 2012 - 10:53 AM

It does affect something it affects the source code layout, which is the whole point of using it, to make source code more readable.
  • 4


#14402 Really Disturbing

Posted by margaux on 1 May 2013 - 4:56 PM

Hey xto, I'm going to try to say this in the nicest way possible -  You're in danger of trying people's patience not because you ask questions, we like questions, but because you ask questions in a way that doesn't provide the information needed to try to answer them.

 

1. please read the forum guidelines - Look for the little grey text bottom right of most pages, labelled Guidelines

2. please post only RELEVANT code and error messages within code tags. We don't need to see the entire output from your error message. It's actually distracting. Use code tags which are on the edit bar and they look like <>

3. post the relevant CODE, you keep posting the error message but not any code.

4. You should start a new thread for each new question. One reason for doing so is that other people with the same question can search and find your thread. If your question is part of another thread, it won't be found and won't help others.

5. You're asking questions that you should be able to solve 1 because the level of  experience for this book expects you know some basic debugging strategies and 2. with a little bit of online searching you would get some pointers as to where to look for the cause of your error.

 

I really shouldn't answer your question given the above but ...

 

somewhere in your code you are referencing an array value using 'sale_price' as the index, which doesn't exist. I'm going to hazard a guess that you have a line that includes $row['sale_price']. From the error dump you posted, you will see there is no index 'sale_price' but there is one named 'price'. Given what info you've provided that's all I can help with. If this doesn't help solve the problem, start a new thread and post the code that is causing the error :)


  • 4


#6039 Securing Video

Posted by Paul Swanson on 17 February 2012 - 5:40 PM

In addition to Rob's suggestion, you could use a .htaccess file in the directory housing the video to protect it from browsing. This will prevent any browser from accessing the directory (but PHP will still be able to access it):

# disable directory browsing
Options All -Indexes

# prevent folder listing
IndexIgnore *

# prevent access to any file
<FilesMatch "^.*$">
 Order Allow,Deny
 Deny from all
</FilesMatch>

  • 3


#20055 I'm Having Trouble With Sorting Query Results In Chapter 5... Plz Help!

Posted by Emilie on 30 July 2014 - 1:07 PM

Hello,

 

What is "wrong", according to you?

 

The registration date is the same for all users because you entered all of them at one go into the database, and therefore the timestamp corresponding to NOW() is the same for everyone. Because of that, ordering the results by registration_date DESC has no real meaning.

 

I hope this helps,

 

Emilie


  • 3


#15289 Use Data Type Enum For Form Drop-Down Options

Posted by margaux on 2 July 2013 - 5:02 PM

Glad I could provide a little help. When I'm struggling with some code, I use var_dump and print_r to see what is being returned. Then I know how to manipulate the data.


  • 3


#13394 Pls Help Need Urgent Help. The .Inc Extension. Chapter 11

Posted by margaux on 11 March 2013 - 4:45 AM

It's difficult to debug when the code is presented in this way. Please would you use code tags.

 

At first look, no error immediately jumps out. Which line is line 46? Look at that line and the few lines before it.

 

Probably not causing this error but it looks like you may have a typo on the tablename in the SELECT statement - users instead of usera?


  • 3


#13112 Forms In Javascript Or Php?

Posted by HartleySan on 19 February 2013 - 10:38 AM

Awesomo, to give you a concrete example, I'm going to use Jonathon's example above because I think it's a good example.
First off, you'll want to attach a JS event handler to the form so that when the form is submitted, JS intercepts the form submission and allows you to do whatever you need to before the form is actually submitted.
This can be accomplished as follows:
 
document.forms[0].onsubmit = function () {
  
  return false;
  
};
 
On any HTML page that contains at least one form, JS provides you with the forms array, which is a property of the document object. forms[0] always applies to the first form on the page. You can adjust the array index as need be.
The return false statement actually stops the form from being submitted. (Don't worry though, as we'll actually force the form to be submitted in a second, assuming everything is okay.)
 
Next, let's imagine that we have a user name text input that must be only letters and numbers, as Jonathon said. Here's a simple JS regex we can write to test for that:
 
document.forms[0].onsubmit = function () {
  
  if (/^[A-Za-z0-9]+$/.test(this.elements[0].value)) {
  
  }
  
  return false;
  
};
 
The above if statement tests that the user name text input contains only letters (either uppercase or lowercase) and numbers (and is not an empty string). I should note that I make several assumptions with this code:
The user name text input is the first input in the form. This can be seen by the this.elements[0] in the if statement. In this case, this refers to the form object we're interested in, and elements is an array attached to all JS form objects that allows you to access all the inputs items in the form. Naturally, elements[0] refers to the first element in the form. If you'd rather check the user name text input by ID (assuming the ID is "username"), you can replace this.elements[0] with document.getElementById('username'). The value property at the end will give you the actual string entered into the text input object.
 
If the above if statement evaluates to true, then we can assume that the user name does in fact only contain letters and numbers. That being the case, we should then submit the form normally.
However, if the if statement returns false, then we should change the border of the user name text input to red.
The following code will do just that:
 
document.forms[0].onsubmit = function () {
  
  if (/^[A-Za-z0-9]+$/.test(this.elements[0].value)) {
    
    this.submit();
    
  } else {
    
    this.elements[0].style.border = '#F00 solid 2px';
    
  }
  
  return false;
  
};
 
As before, this refers to the form object in question. this.submit() will actually submit the form as if JS never intercepted the form submit request in the first place.
If the if statement fails, then we use this.elements[0] (or document.getElementById('username'), if you want) to reference the user name text input object, and then change the border to a 2-pixel red border.
 
That's the basic concept to simple JS form validation built on top of standard PHP form validation.
One of the keys to this method is that you only submit the form when everything is okay.
And naturally, the concepts above can be rinsed and repeated as many times as necessary to validate all your form input.
I hope that helps.

  • 3


#11924 Very Basic: Headers Vs Cookies

Posted by HartleySan on 27 December 2012 - 8:38 PM

The order doesn't matter. In fact, you can perform any number of PHP operations before setting headers so long as you don't actually output any HTML before you set a header.
  • 3


#11574 Please Explain Routing Rules Precisely !

Posted by HartleySan on 8 December 2012 - 12:11 PM

Ziggi, sometimes when we try to help people on this forum, we don't get it right the first time.
Quite often, the reason someone is asking a question and the reason they don't understand something is not very clear to us. We don't intentionally try to not answer someone's question.
Antonio and Edward were both doing the best they could to help you. The fact that they (unintentionally) missed the mark and didn't give you the answer you wanted right away is no reason to act the way you did.

A more civil approach would have been to reanalyze your original post(s), think about why Antonio and Edward perhaps weren't able to answer your question, and then politely reprhase your question to hopefully reach a reasonable solution eventually. I guarantee that if you had been polite about it, both Antonio and Edward would have been more than happy to continue helping you until you got the answer you were looking for.

It seems like you're not a native English speaker, so perhaps the source of the arguments was all just a simple misunderstanding on both sides, but at this point, you really have no hope of ever getting any more relevant information to your question. And more than likely, you've ruined any chances you have of ever getting any help on this forum again. Both Antonio and Edward are the two most active and knowledgeable posters on the Yii forum here, so you're probably SOL.

I think you have one of two choices:

1) Apologize for your previous posts, and with time, I think tempers will cool down and we can get back to having civil discussions and everyone can get answers to questions and be happy. Please note that I am not asking you to beg on your knees, but at this point, I think a sincere apology would be nice.

2) Don't post on this forum anymore and consider this a lesson learned for future interactions on forums.

The choice is yours. I also had to swallow my pride recently and apologize for stepping over the line on this forum, and even though it didn't feel good at the time, I'm glad I did apologize and everyone was able to go back to being civil and helping out again. I'd recommend the same for you.
  • 3


#11339 Ch. 11 Using Unlink() With A Reset Button Possible?

Posted by Antonio Conte on 27 November 2012 - 10:43 PM

This can absolutely be done via GET. What you would do is using IDs as the get value. Save the filenames to an array on the form ID => "name". You then build links the same way, but with ?remove=$ID. You cast $_GET['id'] to an integer, find the filename in array by using the ID, build a full path where you add the filename, then use unlink() to delete the file.

An easy way to do this would be something like:


$handle = ""; // open file

$file_array = array(); // The file names

while ( ($file = readdir($handle)) !== false )
{
    if ($entry != "." && $entry != "..")
    {
	   $file_array[] = $file;
    } // Read files to array
}

// Simple delete
if ( ! empty($_GET) )
{
   
    $upload_dir = "uploadsDirectoryHere/"; // Upload dir
    $file_id = (int) $_GET['delete']; // File_array ID

    // Make sure file is found
    if ( array_key_exists($file_id, $file_array) )
    {
		 $delete_file = $upload_dir . $file_array[$file_id];

		 // Make sure file exists
		 if ( file_exists($delete_file) )
		 {
			  unset(file_array[$file_id]); // Remove from file array
			  unlink($delete_file); // Actually delete file here
		 }
    }

// Print out file names and links for deleting them
foreach ( $file_array as $id => $filename )
{
    echo $filename . '<a href="page.php?delete='.$id.'">Delete file</a>;
}

Not tested, but that should be the basic idea. Sorry about errors/etc. Beginning to get tired here.
  • 3


#10822 Access All Objects Of A Class

Posted by Edward on 31 October 2012 - 7:11 AM

Yes you can do this by creating a static array, then you can assign each new instance of the newly created class to that array. This method is often used when storing active database connections.
  • 3


#10649 Advanced Question - What Is Happening In This For In Loop?

Posted by HartleySan on 24 October 2012 - 2:53 AM

When you ask for more "explicit" code to accomplish the same thing, I assume that you're really asking, "What's a simple way to accomplish the same thing?"

I'm not sure if there's a simpler way, as "simpler" code might actually be more confusing for a JS guru, but for demonstration purposes, I have put together some sample code that achieves the same thing without the use of closures (at least, not in the sense that you're thinking about) and without the use of the map method.

Keep in mind that my code is super simplistic, and I wouldn't actually recommend ever doing things this way, but for demonstration purposes, I think it serves its purpose well.

<!DOCTYPE html>

<html lang="en">

  <head>

    <meta charset="UTF-8">

    <title>Chaining alternative</title>

  </head>

  <body>

    <a href="#" id="link1">Link 1</a>

    <a href="#" id="link2">Link 2</a>

    <a href="#" id="link3">Link 3</a>

    <script>

      // this in these two functions is equal to the out array in function X.

      function color(x) {

        for (var i = 0; i < this.length; i++) {

          this[i].style.color = x;

        }

        return this;

      }

      function size(x) {

        for (var i = 0; i < this.length; i++) {

          this[i].style.fontSize = x;

        }

        return this;

      }

      function X(css) {

        var out = [];

        // For this simplified example, I'm assuming that css is always a tag name, not an ID.
        var tags = document.getElementsByTagName(css);

        for (var i = 0; i < tags.length; i++) {

          out.push(tags[i]);

        }

        out['color'] = color;

        out['size'] = size;

        return out;

      }

      X('a').color('red').size('24px');

    </script>

  </body>

</html>

Does that help clarify things at all?

I know that that one guy's code on the other site is very difficult, so don't feel bad if it doesn't all click right away. He has a ton of complex code (and sometimes JS-specific idiosyncrasies) all stuck together.

To reply to your three points of interest:

1) Yes, scope in JS is very interesting. The thing about JS is that functions are lexically scoped, meaning that they contain the scope in which they're defined, not in which they are called. This is different from C, for example.

2) Yes, I agree that the way the length property is calculated in JS is interesting, but that's just the way it's defined in the ECMA specs (for better or worse). To give some more explanation, if an array contains only associative indexes, since that's akin to an object (not an array) in JS, the length will be 0. Another interesting caveat is that if, for example, you have an array with only 1 element, but the index of that element is 5, then the length will be reported as 6 (as per what I said in my previous post (i.e., 5 + 1)).

3) Closures are basically used as a tricky way to freeze a variable's state in time. For example, you may have a constantly changing global variable, but if you want to retain the value of that variable at one specific time, then you need to use a closure. Remember that every time a function is called, a closure is created (just usually not a closure in the sense that's commonly talked about). This happens because whenever a function is called, all the variables passed to that function are frozen in the state that they are in when the function was called. It's prudent to remember that this is NOT the case with function references/function definitions; only function calls. Anyway, for the m example, if you just remember that m is equal a specific instance of meths[meth] each time through the for-in loop, then you should be fine.

Hope that helps (and by all means, fire back another comment if it doesn't).
  • 3


#10475 Benefits And Applications Of Ajax?

Posted by HartleySan on 16 October 2012 - 1:40 AM

Probably the most important thing to understand is that Ajax is not a replacement for PHP; it's a technology that combines JS with a server-side language (e.g., PHP) to do things that can only be done on the server side, but without the need to reload the page. That's really the whole point of it; to create a more seamless, desktop application-like experience for the user. Also, it's important to understand that JS and Ajax are not one and the same.

To more specifically answer your questions:
1) Because JS is client side, you can use JS to perform some basic form checking before submitting the form to the server and your PHP script. By doing this, the user will get an instantaneous response to any mistakes they may have made in filling out the form. This generally equates to a better, more-responsive user experience.

Some important things to note with JS validation though are that because anyone can view your JS code, you don't want to validate with only JS, as people might try to study your code to find ways around your validation for the sake of hacking your site/DB. Also, PHP has much more robust functions for performing validation and preventing DB attacks, so PHP validation should always be used and the final line of defense, regardless of whether or not you are also using JS for validation.

Some good examples of when to perform JS validation would be to check that an entered password meets the site requirements, zip codes are entered in the proper format, etc., etc. This will help prevent a majority of the honest mistakes that users might make in filling out a form.

The more you can entrust to the client side, the faster and better the user experience and the less of a strain you put on the server. Just remember to never sacrifice safety for speed.

2) Again, Ajax is not a replacement for PHP, and honestly, Ajax is never required for a site, but it makes the whole experience on the site a lot smoother and easier to use. The purpose of Ajax has always been to create a more desktop application-like experience for web pages.

To give a couple of examples of how to effectively use Ajax:
- You could use Ajax to poll (i.e., check) a DB every so many seconds, and then update content on the site whenever there is a change to the DB. By doing this, you can constantly update a site's content without the user having to refresh the page. This is good for things like stock tickers, updating the scores of sporting events, etc., etc.

- You can use Ajax to update only part of a page. For example, with most websites, when you click on a link, the new page that is loaded will likely have a lot of the same content as the old page. However, with Ajax, when a link is clicked, you can choose to change only a small part of the page while leaving everything else untouched. This ultimately puts less of a strain on the server (because less info needs to be processed/downloaded) and it'll make the new "page" load faster for the user, and without the need to actually reload the page.

With all that said, please note that there are two big downsides to Ajax:
- It "breaks" the back button in your browser in that because there are no page transitions (at least, not according to the browser), the back button will take you to the page you were on before you loaded the site, and not the previous page you were on on the site.
- Similar to the above, you cannot bookmark pages because there are no page transitions.

Over the years, people have come up with ways to circumvent these two problems, but they're all half-ass workarounds that can be tricky to implement and don't really solve the problem.

The silver lining to all this is that there is a new API in HTML5 called the History API, which allows you to properly create proper URLs for Ajax-driven sites, and thus the back button and bookmarking problems can be resolved for Ajax sites. Unfortunately, the History API is still new and does not have universal support, especially among IE browsers.

Also, in what is quickly becoming a new replacement for Ajax in some situations, there is also the HTML5 WebSocket API, which allows for true, asynchronous communication between two endpoints. This allows you to do things via a browser that before were impossible and/or very inefficient using only Ajax.
For example, you could use the WebSocket API to create a chess application that detects when your opponent makes a move and instantly updates the board on your end. You could also use the WebSocket API for things like chat applications, etc.
Gmail and Facebook already very actively use this technology for their chat applications.

Well, hopes that is somewhat the answer you were looking for.
  • 3


#13111 Losing $_Get Values After Pressing Reload Button

Posted by HartleySan on 19 February 2013 - 9:54 AM

Hello, Roy. Welcome to the forums. I hope you find them helpful.

I think you have a few options:

 

1) Store the $ordernbr value in a hidden input in the form on the second page, and then grab that value from the $_POST superglobal when you post the form with the "Reload" button.

 

2) Save the $ordernbr into a cookie or session.

 

3) Use JavaScript and Ajax to change part of the form dynamically without actually reloading the page. (This is rather advanced and not really recommended. I more am just presenting it here because it is a possibility.)

 

Of the three options, I probably wouldn't attempt #3 unless you want a serious challenge.

#2 is a very viable option, but I'm not sure if Larry talks about cookies/sessions in the book, so I'd check that first.

So that leaves us with option #1.

 

Basically, when you are using PHP to write the HTML for the form on the second page, add am extra hidden input element (I think Larry talks about these in the book) with a value equal to the $ordernbr variable. That way, when you post the second form by clicking the "Reload" button, that $ordernbr value will be posted and accessible in the $_POST superglobal under the name set for the hidden input.

Does that make sense?


  • 3