Home ยป Shortcodes ยป [sabai-discuss-answers]

[sabai-discuss-answers]

Shortcode: [sabai-discuss-answers]

78 votes

Incrementing / Decrementing Operators

++ increment operator

-- decrement operator

Example    Name              Effect
---------------------------------------------------------------------
++$a       Pre-increment     Increments $a by one, then returns $a.
$a++       Post-increment    Returns $a, then increments $a by one.
--$a       Pre-decrement     Decrements $a by one, then returns $a.
$a--       Post-decrement    Returns $a, then decrements $a by one.

These can go before or after the variable. Putting this operator before the variable is slightly faster.

If put before the variable, the increment / decrement operation is done to the variable first then the result is returned. If put after the variable, the variable is first returned, then the increment / decrement operation is done.

For example:

$apples = 10;
for ($i = 0; $i < 10; ++$i)
{
    echo 'I have ' . $apples-- . " apples. I just ate one.\n";
}

Live example

In the case above ++$i is used, since it is faster. $i++ would have the same results.

However, you must use $apples--, since first you want to display the current number of apples, and then you want to subtract one from it.

You can also increment letters in PHP:

$i = "a";
while ($i < "c")
{
    echo $i++;
}

Once z is reached aa is next, and so on.

Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.


Stack Overflow Posts:

NOTE: This answer was originally posted at StackOverflow.com by Peter Ajtai

  • Joe answered 14 years ago
  • last active 12 years ago
78 votes

Because once ‘z’ is reached (and this is a valid result within your range, the $i++ increments it to the next value in sequence), the next value will be ‘aa’; and alphabetically, ‘aa’ is < ‘z’, so the comparison is never met

for ($i = 'a'; $i != 'aa'; $i++) 
    echo "$i\n"; 

NOTE: This answer was originally posted at StackOverflow.com by Mark Baker

  • Amy answered 14 years ago
58 votes

Others answers explain the observed behavior of the posted code. Here is one way to do what you want (and it’s cleaner code, IMO):

foreach (range('a', 'z') as $i)
    echo "$i\n";

In response to ShreevatsaR’s comment/question about the range function: Yes, it produces the “right endpoint”, i.e. the values passed to the function are in the range. To illustrate, the output I got was:

a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z

NOTE: This answer was originally posted at StackOverflow.com by GreenMatt

  • Jimmy answered 14 years ago
  • last active 14 years ago
47 votes
In reply to: PHP: self vs. $this

$this-> is used to refer to a specific instance of a class’s variables (member variables) or methods.

Example: 
$derek = new Person();

$derek is now a specific instance of Person.
Every Person has a first_name and a last_name, but $derek has a specific first_name and last_name (Derek Martin). Inside the $derek instance, we can refer to those as $this->first_name and $this->last_name

ClassName:: is used to refer to that type of class, and its static variables, static methods. If it helps, you can mentally replace the word “static” with “shared”. Because they are shared, they cannot refer to $this, which refers to a specific instance (not shared). Static Variables (i.e. static $db_connection) can be shared among all instances of a type of object. For example, all database objects share a single connection (static $connection).

Static Variables Example:
Pretend we have a database class with a single member variable: static $num_connections;
Now, put this in the constructor:

function __construct()
{
    if(!isset $num_connections || $num_connections==null)
    {
        $num_connections=0;
    }
    else
    {
        $num_connections++;
    }
}

Just as objects have constructors, they also have destructors, which are executed when the object dies or is unset:

function __destruct()
{
    $num_connections--;
}

Every time we create a new instance, it will increase our connection counter by one. Every time we destroy or stop using an instance, it will decrease the connection counter by one. In this way, we can monitor the number of instances of the database object we have in use with:

echo DB::num_connections;

Because $num_connections is static (shared), it will reflect the total number of active database objects. You may have seen this technique used to share database connections among all instances of a database class. This is done because creating the database connection takes a long time, so it’s best to create just one, and share it (this is called a Singleton Pattern).

Static Methods (i.e. public static View::format_phone_number($digits)) can be used WITHOUT first instantiating one of those objects (i.e. They do not internally refer to $this).

Static Method Example:

public static function prettyName($first_name, $last_name)
{
    echo ucfirst($first_name).' '.ucfirst($last_name);
}

echo Person::prettyName($derek->first_name, $derek->last_name);

As you can see, public static function prettyName knows nothing about the object. It’s just working with the parameters you pass in, like a normal function that’s not part of an object. Why bother, then, if we could just have it not as part of the object?

  1. First, attaching functions to objects helps you keep things organized, so you know where to find them.
  2. Second, it prevents naming conflicts. In a big project, you’re likely to have two developers create getName() functions. If one creates a ClassName1::getName(), and the other creates ClassName2::getName(), it’s no problem at all. No conflict. Yay static methods!

SELF::
If you are coding outside the object that has the static method you want to refer to, you must call it using the object’s name View::format_phone_number($phone_number);
If you are coding inside the object that has the static method you want to refer to, you can either use the object’s name View::format_phone_number($pn), OR you can use the self::format_phone_number($pn) shortcut

The same goes for static variables:
Example: View::templates_path versus self::templates_path

Inside the DB class, if we were referring to a static method of some other object, we would use the object’s name:
Example: Session::getUsersOnline();

But if the DB class wanted to refer to its own static variable, it would just say self:
Example: self::connection;

Hope that helps clear things up ๐Ÿ™‚

NOTE: This answer was originally posted at StackOverflow.com by lo_fye

  • Deborah answered 16 years ago
  • last active 9 years ago
29 votes

As stated before none of the perm fixes work anymore. You need to change the perms accordingly AND put the following in your wp-config.php:

define('FS_METHOD', 'direct');

NOTE: This answer was originally posted at StackOverflow.com by Ryan Wiancko

  • Deborah answered 13 years ago
  • last active 13 years ago
27 votes
In reply to: Good PHP ORM Library?

I’ve been developing Pork.dbObject on my own. (A simple PHP ORM and Active Record implementation)
The main reason is that I find most ORMs too heavy.

The main thought of Pork.dbObejct is to be light-weight and simple to set up. No bunch of XML files, just one function call in the constructor to bind it, and an addRelation or addCustomRelation to define a relation to another dbObject.

Give it a look: Pork.dbObject

NOTE: This answer was originally posted at StackOverflow.com by SchizoDuckie

  • Tracy answered 16 years ago
  • last active 13 years ago
24 votes

You can not ethically store passwords for later plaintext retrieval. It’s as simple as that. Even Jon Skeet can not ethically store passwords for later plaintext retrieval. If your users can retrieve passwords in plain text somehow or other, then potentially so too can a hacker who finds a security vulnerability in your code. And that’s not just one user’s password being compromised, but all of them.

If your clients have a problem with that, tell them that storing passwords recoverably is against the law. Here in the UK at any rate, the Data Protection Act 1998 (in particular, Schedule 1, Part II, Paragraph 9) requires data controllers to use the appropriate technical measures to keep personal data secure, taking into account, among other things, the harm that might be caused if the data were compromised — which might be considerable for users who share passwords among sites. If they still have trouble grokking the fact that it’s a problem, point them to some real-world examples, such as this one.

The simplest way to allow users to recover a login is to e-mail them a one-time link that logs them in automatically and takes them straight to a page where they can choose a new password. Create a prototype and show it in action to them.

Here are a couple of blog posts I wrote on the subject:

NOTE: This answer was originally posted at StackOverflow.com by jammycakes

  • Stephen answered 15 years ago
  • last active 14 years ago
20 votes
In reply to: Good PHP ORM Library?

Try Doctrine2. It’s probably the most powerful ORM tool for PHP. I’m mentioning it separately from Doctrine 1, because it’s a completely different piece of software. It’s been rewritten from scratch, is still in beta phase, but it’s usable now and developed.

It’s a very complex ORM, but well designed. Lot of magic from original Doctrine 1 disappeared. It provides a complete solution, and you can write your own ORM on top of Doctrine2 or use just one of its layers.

NOTE: This answer was originally posted at StackOverflow.com by tomp

  • Chris answered 14 years ago
  • last active 13 years ago
13 votes

Prettify is the code colorizer that StackOverflow uses.

NOTE: This answer was originally posted at StackOverflow.com by Zach Johnson

  • Dawn answered 15 years ago
12 votes
In reply to: Good PHP ORM Library?

I just started with Kohana, and it seems the closest to Ruby on Rails without invoking all the complexity of multiple configuration files like with Propel.

NOTE: This answer was originally posted at StackOverflow.com by Zak

  • Rebecca answered 16 years ago
  • last active 13 years ago
11 votes
In reply to: datetime vs timestamp?

Depends on application, really.

Consider setting a timestamp by a user to a server in New York, for an appointment in Sanghai. Now when the user connects in Sanghai, he accesses the same appointment timestamp from a mirrored server in Tokyo. He will see the appointment in Tokyo time, offset from the original New York time.

So for values that represent user time like an appointment or a schedule, datetime is better. It allows the user to control the exact date and time desired, regardless of the server settings. The set time is the set time, not affected by the server’s time zone, the user’s time zone, or by changes in the way daylight savings time is calculated (yes it does change).

On the other hand, for values that represent system time like payment transactions, table modifications or logging, always use timestamps. The system will not be affected by moving the server to another time zone, or when comparing between servers in different timezones.

Timestamps are also lighter on the database and indexed faster.

NOTE: This answer was originally posted at StackOverflow.com by ianaré

  • Jay answered 14 years ago
11 votes

Refinery looks really simple but I don’t have an in depth comparison to wordpress. Looks like it has a lot less features but likely easier to maintain and extend upon. It’s pretty standard to write really crappy code in the Wordpress community.

NOTE: This answer was originally posted at StackOverflow.com by Tony

  • Anne answered 14 years ago
8 votes

Type cast if possible your parameters. But it’s only working on simple types like int, bool and float.

$unsafe_variable = $_POST['user_id'];

$safe_variable = (int)$unsafe_variable ;

mysql_query("INSERT INTO table (column) VALUES ('" . $safe_variable . "')");

NOTE: This answer was originally posted at StackOverflow.com by devOp

  • Diane answered 12 years ago
8 votes

Wordpress is a specialised CMS. While you can coerce it into a more generalised role, you are probably better off choosing a more general CMS if you are doing more than blogging.

NOTE: This answer was originally posted at StackOverflow.com by Jim

8 votes

Also you can use http://tohtml.com/html/ or GeSHi

NOTE: This answer was originally posted at StackOverflow.com by voodoo555

  • Jay answered 15 years ago
8 votes

In complement to @tom answer.

Magic Quotes

Automatically parsing the whole entries and adding magic quotes is both creating bugs and useless.

  • Useless as you cannot rely on magic quotes to secure your input (multy-bytes encoding bugs for SQL injections is an example). So you need to apply a real filter before saving your data to a database
  • Creating bugs: If you need to really escape your data before a save in database you have to check that it’s not already escaped (and the simple fact this settings exists and may be enforced by the hosting environment makes that you have to check this setting was set or not).
  • Creating bugs: All the data sent by the user is not always dedicated to a database storage. Escaping it may break the content, think about a json content for example, or even file content with the dangerous magic_quote_runtime
  • Creating bugs: All database storage are not escaping quotes the same way…

So Why?, why do we see such function in a CMS?

  • see that here it’s an add_magic_quotes function, that can be used on a dedicated array, maybe not on _GET or _POST. But effectively the fact this function is just using addslashes and not a database dedicated function makes it quite bad.
  • The fact the hosting provider may enforce an automatic magic quotes is a nightmare for a CMS developper. Either you detect it and tell the user you refuse to run, or you have to manage the fact the content may or may have not be magically-addslahed… and to put everyone in the same state, you run the non-addslashed content in this function so that at least everyone is in the same (bad) state.
  • From what I can see on Wordpress, before the save a stripslahes_deep is performed in the wp_insert_post. And add_magic_quotes is usually performed on data pulled from Db before this data is send to the wp_insert_post. This may me think the problem is effectively to add slashes before removing them… maybe because sanitize filters which append before the save expect content with slashes, or maybe because no one remember why the code is running in this way ๐Ÿ™‚

register_globals

Seems that this is the way to implement a Registry pattern in wordpress… They wanted to make the code simple to understand, and to allow a simple way to access importants objects like the query or the post. And an object oriented Registry class was not in the simple PHP way, where the $_GLOBALS array is already an existing registry.

Having a Registry is a perfectly valid thing in an application. a register_global thing is dangerous only if you allow some user input to override your valid secure input. And of course only if this secure input is taken from $_GLOBALS elsewhere (or with global keyword).

The dangerous part in the function here is the part of the function you have extracted, the loop on $query->query_vars. You will have to track the calls to see if user injected keys could run throught wp_parse_args and finish in that function. But the next part of this function is fixing $_GLOBALS content for several objects:

$GLOBALS['query_string'] = $this->query_string;
$GLOBALS['posts'] = & $wp_query->posts;
$GLOBALS['post'] = (isset($wp_query->post)) ? $wp_query->post : null;
$GLOBALS['request'] = $wp_query->request;

So at least theses globals cannot be overwritten by user input and are safe.

So, theses functions are bad. But you can use them if you understand what they do and what you need to do to prevent the bad effects. And when you want to implements a simple framework for developpers, available on a very wide environment you sometimes have to use them.

But for sure it’s a bad practice, you can certainly find bad wordpress plugins using *$_GLOBALS* in the wrong way or misusing the add_magic_quotes to data pulled from db wordpress concept. But there will be years before a Zend Framework CMS gained such a big number of contributions.

NOTE: This answer was originally posted at StackOverflow.com by regilero

  • Paula answered 13 years ago
  • last active 13 years ago
7 votes

You may want to look at SyntaxHighligher. It uses JavaScript so it’s not using your own server’s resources and supports a bunch of color schemes. http://alexgorbatchev.com/wiki/SyntaxHighlighter

The problem with putting your code in a generator on another website is that if you change it somewhere you have to put it back in, which can become tedious.

NOTE: This answer was originally posted at StackOverflow.com by aelx

6 votes

In my opinion, the best way to generally prevent SQL injection in your PHP app (or any web app, for that matter) is to think about your application’s architecture. If the only way to protect against SQL injection is to remember to use a special method or function that does The Right Thing every time you talk to the database, you are doing it wrong. That way, it’s just a matter of time until you forget to correctly format your query at some point in your code.

Adopting the MVC pattern and a framework like CakePHP or CodeIgniter is probably the right way to go: Common tasks like creating secure database queries have been solved and centrally implemented in such frameworks. They help you to organize your web app in a sensible way and make you think more about loading and saving objects than about securely constructing single SQL queries.

NOTE: This answer was originally posted at StackOverflow.com by Johannes Fahrenkrug

6 votes
  1. In wp-config.php add define(‘FS_METHOD’, ‘direct’);
  2. Make server writable the directories wp-content/, wp-content/plugins/
  3. Install the plugin.

Worked on version 3.2.1

NOTE: This answer was originally posted at StackOverflow.com by Lamy

  • Rita answered 13 years ago
  • last active 12 years ago
6 votes

It’s a subjective question for sure. From experience I’ve notice WP takes way, way more server resources than other systems or my custom code. I’ve had to move WP sites off my servers as a consequence. So my experience suggests there are some memory use issues.

As an exercise try going through the code, tracing the logic from the start of a request to a page, and look at how many objects are loaded, how many methods are called before any HTML is output.

NOTE: This answer was originally posted at StackOverflow.com by Devin Ceartas

Showing 1 - 20 of 1k results