Home » Questions » All Answers

All Answers

1 vote
In reply to: Good PHP ORM Library?

There’s a fantastic ORM included in the QCubed framework; it’s based on code generation and scaffolding. Unlike the ActiveRecord that’s based on reflection and is generally slow, code generation makes skeleton classes for you based on the database and lets you customize them afterward. It works like a charm.

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

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

If you are looking for an ORM that implements the Data Mapper paradigm rather than Active Record specifically, then I would strongly suggest that you take a look at GacelaPHP.

Gacela features:

  • Data mapper
  • Foreign key mapping
  • Association mapping
  • Dependent mapping
  • Concrete table inheritance
  • Query object
  • Metadata mapping
  • Lazy & eager loading
  • Full Memcached support

Other ORM solutions are too bloated or have burdensome limitations when developing anything remotely complicated. Gacela resolves the limitations of the active record approach by implementing the Data Mapper Pattern while keeping bloat to a minimum by using PDO for all interactions with the database and Memcached.

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

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

Try PdoMap. Wikipedia claims that is inspired by Hibernate. Since I never used Hibernate, I cannot judge :), but I would say from my experience that is good and fast ORM that is easy to implement, with a less steep learning curve that other ORMs.

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

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

Looked at Syrius ORM. It’s a new ORM, the project was in a development stage, but in the next mouth it will be released in a 1.0 version.

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

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

A really good simple ORM is MyActiveRecord. MyActiveRecord documentation. I have been using it a lot and can say it’s very simple and well tested.

NOTE: This answer was originally posted at StackOverflow.com by Szymon Wygnański

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

Tried the ORM of Flourish library.

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

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

Try PHP ADOdb.

I can’t say it’s the best, because I haven’t used the others. But it’s fast, it supports Memcached and caching.

And it’s waaaay faster than Zend Framework’s DB/Select.

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

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

If you are looking for an ORM, like Hibernate, you should have look at PMO.

It can be easily integrated in an SOA architecture (there is only a webservice classe to develop).

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

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

Try RedBean, its requires:

  • No configuration
  • No database (it creates everything on the fly)
  • No models
  • etc.

It even does all the locking and transactions for you and monitors performance in the background. (Heck! it even does garbage collection….) Best of all… you don’t have to write a single… line of code… Jesus this, ORM layer, saved me ass!

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

  • Sherry answered 15 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
1 vote
In reply to: Good PHP ORM Library?

Another great open source PHP ORM that we use is PHPSmartDb. It is stable and makes your code more secure and clean. The database functionality within it is hands down the easiest I have ever used with PHP 5.3.

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

  • Donna answered 13 years ago
1 vote
In reply to: Good PHP ORM Library?

Look at http://code.google.com/p/lworm/ . It is a really simple, but powerful, lightweight ORM system for PHP. You can also easily extend it, if you want.

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

  • Cindy answered 13 years ago
1 vote

Everyone wants to make this more complicated than it is. The crypt() function does most of the work.

function blowfishCrypt($password,$cost)
{
    $chars='./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    $salt=sprintf('$2a$%02d$',$cost);
    //Create a 22 character salt
    for($i=0;$i<22;$i++) $salt.=$chars[rand(0,63)];
    return crypt($password,$salt);
}

Example:

$hash=blowfishCrypt('password',10); //This creates the hash
$hash=blowfishCrypt('password',12); //This creates a more secure hash
if(crypt('password',$hash)==$hash){ /*ok*/ } //This checks a password

I know it should be obvious, but please don’t use ‘password’ as your password.

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

  • Diana answered 12 years ago
  • last active 12 years ago
1 vote

You do

bcrypt is an hashing algorithm which is scalable with hardware (via a configurable number of rounds). Its slowness and multiple rounds ensures that an attacker must deploy massive funds and hardware to be able to crack your passwords. Add to that per-password salts (bcrypt REQUIRES salts) and you can be sure that an attack is virtually unfeasible without either ludicrous amount of funds or hardware.

bcrypt uses the Eksblowfish algorithm to hash passwords. While the encryption phase of Eksblowfish and Blowfish are exactly the same, the key schedule phase of Eksblowfish ensures that any subsequent state depends on both salt and key (user password), and no state can be precomputed without the knowledge of both. Because of this key difference, bcrypt is a one-way hashing algorithm. You cannot retrieve the plain text password without already knowing the salt, rounds and key (password). [Source]

You can use crypt() function to generate bcrypt hashes of input strings. This class can automatically generate salts and verify existing hashes against an input.

class Bcrypt {
  private $rounds;
  public function __construct($rounds = 12) {
    if(CRYPT_BLOWFISH != 1) {
      throw new Exception("bcrypt not supported in this installation. See http://php.net/crypt");
    }

    $this->rounds = $rounds;
  }

  public function hash($input) {
    $hash = crypt($input, $this->getSalt());

    if(strlen($hash) > 13)
      return $hash;

    return false;
  }

  public function verify($input, $existingHash) {
    $hash = crypt($input, $existingHash);

    return $hash === $existingHash;
  }

  private function getSalt() {
    $salt = sprintf('$2a$%02d$', $this->rounds);

    $bytes = $this->getRandomBytes(16);

    $salt .= $this->encodeBytes($bytes);

    return $salt;
  }

  private $randomState;
  private function getRandomBytes($count) {
    $bytes = '';

    if(function_exists('openssl_random_pseudo_bytes') &&
        (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')) { // OpenSSL slow on Win
      $bytes = openssl_random_pseudo_bytes($count);
    }

    if($bytes === '' && is_readable('/dev/urandom') &&
       ($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE) {
      $bytes = fread($hRand, $count);
      fclose($hRand);
    }

    if(strlen($bytes) < $count) {
      $bytes = '';

      if($this->randomState === null) {
        $this->randomState = microtime();
        if(function_exists('getmypid')) {
          $this->randomState .= getmypid();
        }
      }

      for($i = 0; $i < $count; $i += 16) {
        $this->randomState = md5(microtime() . $this->randomState);

        if (PHP_VERSION >= '5') {
          $bytes .= md5($this->randomState, true);
        } else {
          $bytes .= pack('H*', md5($this->randomState));
        }
      }

      $bytes = substr($bytes, 0, $count);
    }

    return $bytes;
  }

  private function encodeBytes($input) {
    // The following is code from the PHP Password Hashing Framework
    $itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    $output = '';
    $i = 0;
    do {
      $c1 = ord($input[$i++]);
      $output .= $itoa64[$c1 >> 2];
      $c1 = ($c1 & 0x03) << 4;
      if ($i >= 16) {
        $output .= $itoa64[$c1];
        break;
      }

      $c2 = ord($input[$i++]);
      $c1 |= $c2 >> 4;
      $output .= $itoa64[$c1];
      $c1 = ($c2 & 0x0f) << 2;

      $c2 = ord($input[$i++]);
      $c1 |= $c2 >> 6;
      $output .= $itoa64[$c1];
      $output .= $itoa64[$c2 & 0x3f];
    } while (1);

    return $output;
  }
}

You may use this code as such:

$bcrypt = new Bcrypt(15);

$hash = $bcrypt->hash('password');
$isGood = $bcrypt->verify('password', $hash);

Alternatively, you may also use the Portable PHP Hashing Framework.

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

  • Judith answered 13 years ago
  • last active 12 years ago
1 vote

You can create a one-way hash with bcrypt using PHP’s crypt() function and passing in an appropriate Blowfish salt. The most important of the whole equation is that A) the algorithm hasn’t been compromised and B) you properly salt each password. Don’t use an application-wide salt; that opens up your entire application to attack from a single set of Rainbow tables.

http://php.net/manual/en/function.crypt.php

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

  • Catherine answered 13 years ago
  • last active 12 years ago
1 vote

You’ll get a lot of information here: http://chargen.matasano.com/chargen/2007/9/7/enough-with-the-rainbow-tables-what-you-need-to-know-about-s.html or http://www.openwall.com/phpass/

The goal is to hash the password with something slow so someone getting your password database will die trying to bruteforce it (a 10ms delay to check a password is nothing for you, a lot for someone trying to bruteforce it). Bcrypt is slow and can be used with a parameter to choose how slow it is.

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

  • Chris answered 13 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 vote

If you want to take advantage of cache engines like redis or memcache maybe DALMP could be a choice, it uses pure mysqli, check this: http://www.dalmp.com/PExecute

Also you can ‘prepare’ your arguments before preparing your query so that you can build dynamic queries and at the end have a full prepared statements query. http://www.dalmp.com/Prepare

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

1 vote

The right way to prevent SQL injection is by using parameterized queries. This means defining the SQL code that is to be executed with placeholders for parameter values, programmatically adding the parameter values, then executing the query. Doing this allows the server to create an execution plan for the query, which prevents any “injected” SQL from being executed. An example will help in explaining this. Let’s use the same script, but I’ll define the SQL query with parameter placeholders:

$sql = "SELECT * FROM Tbl WHERE Username = ? and Password = ?";

Now, I’ll define an array that holds the parameter values:

$params = array($_POST['Username’], $_POST['Password’]);

When I execute the query, I pass the $params array as an argument:

$stmt = sqlsrv_query($conn, $sql, $params);

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

  • Ricky answered 12 years ago
1 vote

As you can see, people suggest you to use prepared statements at the most. Its not wrong, but when your query is executed just once per process, there would be a slightly performance penalty. I was facing this issue but I think i solved it very very sophisticated way – the way hackers use to avoid using quotes. I use it to prevent all possible sql injection attacks.

My approach:

  • if you are expect input to be integer make sure its really integer. In variable-type language like is php is this very important. You can use for example very simple but powerful solution: sprintf("SELECT 1,2,3 FROM table WHERE 4 = %u", $input);
  • if you are except anything else from integer hex it. If you hex it, you will perfectly escape all input. In C/C++ there’s a function called mysql_hex_string(), in php use bin2hex(). Dont worry about that the escaped string will have 2x size of its original length because even if you use mysql_real_escape_string or bin2hex, php have to allocate same capacity ((2*input_length)+1). This hex method is often used when you transfer binary data but I see no reason why not use it to all data to prevent sql injection attacks. Note that you have to prepend 0x or use mysql function UNHEX.

So for example query:

SELECT password FROM users WHERE name = 'root'

Will become:

SELECT password FROM users WHERE name = 0x726f6f74

Perfect escape. No way to inject.

Note that this hex is often used as a sql injection attacks where integers are just like strings and escaped just with mysql_real_escape_string, then you can avoid of use of quotes. For example if you just do something like this:

"SELECT title FROM article WHERE id = " . mysql_real_escape_string($_GET["id"])

attack will very easy inject you. Consider the following injected code returned from your script:

SELECT ... WHERE id = -1 union all select table_name from information_schema.tables

SELECT ... WHERE id = -1 union all select table_name from information_schema.tables where table_name = 0x61727469636c65

But if would the coder of injectable site hex it, no injection would be possible:

SELECT ... WHERE id = 0x2d3120756e696f6e20616c6c2073656c656374207461626c655f6e616d652066726f6d20696e666f726d6174696f6e5f736368656d612e7461626c6573207768657265207461626c65203d2030783631373237343639363336633635

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

Showing 61 - 80 of 1k results