Home » Questions » All Answers

All Answers

0 votes

You could do something basic like this:

$safe_variable = mysql_real_escape_string($_POST["user-input"]);
mysql_query("INSERT INTO table (column) VALUES ('" . $safe_variable . "')");

This won’t solve every problem, but it’s a very good stepping stone. I left out obvious items such as checking the variable’s existence, format (numbers, letters, etc.).

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

  • Laurie answered 16 years ago
  • last active 12 years ago
0 votes

You’ve got two options – escaping the special characters in your unsafe_variable, or using a parameterized query. Both would protect you from SQL injection. The parameterized query is considered the better practice, but escaping characters in your variable will require fewer changes.

We’ll do the simpler string escaping one first.

//Connect

$unsafe_variable = $_POST["user-input"]
$safe_variable = mysql_real_escape_string($unsafe_variable);

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

//Disconnect

See also, the details of the mysql_real_escape_string function.

To use the parameterized query, you need to use MySQLi rather than the MySQL functions. To rewrite your example, we would need something like the following.

<?php
    $mysqli = new mysqli("server", "username", "password", "database_name");

    // TODO - Check that connection was successful.

    $unsafe_variable = $_POST["user-input"];

    $stmt = $mysqli->prepare("INSERT INTO table (column) VALUES (?)");

    // TODO check that $stmt creation succeeded

    // "s" means the database expects a string
    $stmt->bind_param("s", $unsafe_variable);

    $stmt->execute();

    $stmt->close();

    $mysqli->close();
?>

The key function you’ll want to read up on there would be mysqli::prepare.

Also, as others have suggested, you may find it useful/easier to step up a layer of abstraction with something like PDO.

Please note that the case you asked about is a fairly simple one, and that more complex cases may require more complex approaches. In particular:

  • If you want to alter the structure of the SQL based on user input, parameterised queries are not going to help, and the escaping required is not covered by mysql_real_escape_string. In this kind of case you would be better off passing the user’s input through a whitelist to ensure only ‘safe’ values are allowed through.
  • If you use integers from user input in a condition and take the mysql_real_escape_string approach, you will suffer from the problem described by Polynomial in the comments below. This case is trickier because integers would not be surrounded by quotes, so you could deal with by validating that the user input contains only digits.
  • There are likely other cases I’m not aware of. You might find http://webappsec.org/projects/articles/091007.txt a useful resource on some of the more subtle problems you can encounter.

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

  • Anthony answered 16 years ago
  • last active 12 years ago
1 vote

Use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.

You basically have two options to achieve this:

  1. Using PDO:

    $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
    
    $stmt->execute(array(':name' => $name));
    
    foreach ($stmt as $row) {
        // do something with $row
    }
    
  2. Using mysqli:

    $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
    $stmt->bind_param('s', $name);
    
    $stmt->execute();
    
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        // do something with $row
    }
    

PDO

Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:

$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

In the above example the error mode isn’t strictly necessary, but it is advised to add it. This way the script will not stop with a Fatal Error when something goes wrong. And gives the developer the chance to catch any error(s) which are thrown as PDOExceptions.

What is mandatory however is the setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren’t parsed by PHP before sending it the the MySQL server (giving a possible attacker no chance to inject malicious SQL).

Although you can set the charset in the options of the constructor it’s important to note that ‘older’ versions of PHP (< 5.3.6) silently ignored the charset parameter in the DSN.

Explanation

What happens is that the SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute the prepared statement is combined with the parameter values you specify.

The important thing here is that the parameter values are combined with the compiled statement, not a SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters you limit the risk of ending up with something you didn’t intend. Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains 'Sarah'; DELETE * FROM employees the result would simply be a search for the string “‘Sarah’; DELETE * FROM employees”, and you will not end up with an empty table.

Another benefit with using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.

Oh, and since you asked about how to do it for an insert, here’s an example (using PDO):

$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');

$preparedStatement->execute(array(':column' => $unsafeValue));

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

  • Dorothy answered 16 years ago
  • last active 11 years ago
-1 votes

no, Wordpress is a blog. If you want a CMS, you need to look to XOOPS, Drupal, Plone, Mambo or similar.

Whilst many of these things overlap in functionality, there’s a lot more available in the CMSs that the blog-type apps wouldn’t want to provide/support.

Bottom line though – if the user is happy with the new system, who cares what it is.

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

3 votes

Good CMS. Easy to deal with. He has to take care and install new versions regulary to keep the punks away but otherwise a good choice.

You may want to tell your customer as well that just having a wordpress installed won’t increase the page rank – Content increases the page-rank and lets people come back to the site.

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

  • Joe answered 16 years ago
  • last active 14 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

2 votes

Yes as CMS = Content Managed System which is exactly what wordpress does, allows you to manage content on multiple pages of varying types. Yes it may be specialised for blogging although as you’ve pointed out this can be easily manipulated for other means.

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

  • Paul answered 16 years ago
1 vote

WordPress is a system that allows you to manage content. That makes it a content management system. A simple one, perhaps, but one nonetheless. Plenty of people are using it in a CMS role.

For obvious reasons, its utility as a CMS for any given project depends greatly on the project involved. You wouldn’t want to run Microsoft.com or CNN.com on it, for example.

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

0 votes

Wordpress is a CMS. It did started as a blog centered software, but now includes many CMS features. It is listed in wikipedia List of content management systems and won a Packt Open Source CMS Award.

Wikipedia defines Content management system as a system which may support the following features:

  • identification of all key users and their content management roles;
  • the ability to assign roles and responsibilities to different content categories or types;
  • definition of workflow tasks for collaborative creation, often coupled with event messaging so that content managers are alerted to changes in content (For example, a content creator submits a story, which is published only after the copy editor revises it and the editor-in-chief approves it.);
  • the ability to track and manage multiple versions of a single instance of content;
  • the ability to capture content (e.g. scanning);
  • the ability to publish the content to a repository to support access to the content (Increasingly, the repository is an inherent part of the system, and incorporates enterprise search and retrieval.);
  • separation of content’s semantic layer from its layout (For example, the CMS may automatically set the color, fonts, or emphasis of text.).

While having very limited workflow, wordpress does support most of those features.

For more complex scenarios, people usually prefer a more powerful CMS such as Drupal. I tried both and usually goes with wordpress where possible.

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

  • Joe answered 16 years ago
-1 votes
In reply to: Good PHP ORM Library?

Look into Doctrine.

Doctrine 1.2 implements Active Record. Doctrine 2+ is a DataMapper ORM.

Also, check out Xyster. It’s based on the Data Mapper pattern.

Also, take a look at DataMapper vs. Active Record.

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

  • Greg answered 16 years ago
  • last active 12 years ago
1 vote
In reply to: Good PHP ORM Library?

There are only two good ones: Doctrine and Propel. We favor Doctrine, and it works well with Symfony. However if you’re looking for database support besides the main ones you’ll have to write your own code.

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

  • Jon answered 16 years ago
  • last active 13 years ago
0 votes
In reply to: Good PHP ORM Library?

Doctrine is probably your best bet. Prior to Doctrine, DB_DataObject was essentially the only other utility that was open sourced.

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

  • Sherry answered 16 years ago
  • last active 13 years ago
1 vote

In its default setting, no, WordPress is not a CMS, it is a Blogging platform.

However, like with any other popular scripts (vBulletin, phpBB, Coppermine, etc) they can be tweaked and modified to your hearts content. If you add the necessary plugins and modify the template to look like a website and not a Blog then you effectively have a CMS that’ll allow you to publish new pages as WordPress Pages or Posts.

WordPress is as much a CMS as vBulletin or phpBB, so to those who seem to disregard my opinion, please explain why WordPress is a CMS and how come we don’t just call everything that handles content a CMS?

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

  • Richard answered 16 years ago
  • last active 16 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 12 years ago
4 votes

OK, Let’s see how I get voted down by all Wordpress fans by giving a negative answer. Wordpress is probably the best solution out there for publishing content, whether it is a blog or not. However, I don’t think it is a CMS.

For me a CMS must give you the option to create a web application, not just a web site with content. By web application I mean ability to add various forms for collecting user input, have public users and profiles on the site, maybe sell some products (e-commerce module), manage the URLs of your pages/resources, have metadata about them, manage and have a workflow for media and non-text resources, have the ability to extend and customize the system to your needs. I don’t see these features in WordPress. And there are of course many more enterprise-level features that would be normal in a CMS but are missing from WordPress.

So I know how much users like Wordpress, and in fact it is a very good content publishing platform. But not a full-featured CMS.

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

2 votes

WordPress is a CMS, but it’s perhaps best used when your content is effectively like a blog. For small sites that you have to hand over to clients, it’s ideal, since the user interface is very easy to use.

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

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
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 8 years ago
3 votes

I would advise against wordpress, which is really more of a blogging engine than a CMS. I’ve had good success with Drupal and Joomla which are true CMSs

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

  • Susan answered 16 years ago
1 vote

I think WordPress is perfectly suited for a CMS.

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

  • Joe answered 16 years ago
Showing 1 - 20 of 1k results