Rectangle 27 2

You don't have to use php to achieve that. You can do it with pure SQL syntax using the ON DUPLICATE KEY:

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL performs an UPDATE of the old row. For example, if column a is declared as UNIQUE and contains the value 1, the following two statements have similar effect:

INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE    
name="A", age=19

php - Database : if exists 'update' if not exists insert - Stack Overf...

php mysql
Rectangle 27 2

You don't have to use php to achieve that. You can do it with pure SQL syntax using the ON DUPLICATE KEY:

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL performs an UPDATE of the old row. For example, if column a is declared as UNIQUE and contains the value 1, the following two statements have similar effect:

INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE    
name="A", age=19

php - Database : if exists 'update' if not exists insert - Stack Overf...

php mysql
Rectangle 27 3

As mentioned, prepared statements are one of the best ways to prevent SQL injections. i.e., you shouldn't add your parameters as part of the final query string. You should use parameter placeholders, and add the parameters via a key/value array.

If you're using PDO, have a look at this page, which describes prepared statements in greater detail:

A quite thorough explanation of PHP's input filters (and a good article on sanitization) can be found here:

You are probably interested in the filter_var and filter_input functions:

php - How to prevent against XSS and SQL injection - Stack Overflow

php xss sql-injection
Rectangle 27 3

As mentioned, prepared statements are one of the best ways to prevent SQL injections. i.e., you shouldn't add your parameters as part of the final query string. You should use parameter placeholders, and add the parameters via a key/value array.

If you're using PDO, have a look at this page, which describes prepared statements in greater detail:

A quite thorough explanation of PHP's input filters (and a good article on sanitization) can be found here:

You are probably interested in the filter_var and filter_input functions:

php - How to prevent against XSS and SQL injection - Stack Overflow

php xss sql-injection
Rectangle 27 3

As mentioned, prepared statements are one of the best ways to prevent SQL injections. i.e., you shouldn't add your parameters as part of the final query string. You should use parameter placeholders, and add the parameters via a key/value array.

If you're using PDO, have a look at this page, which describes prepared statements in greater detail:

A quite thorough explanation of PHP's input filters (and a good article on sanitization) can be found here:

You are probably interested in the filter_var and filter_input functions:

php - How to prevent against XSS and SQL injection - Stack Overflow

php xss sql-injection
Rectangle 27 3

As mentioned, prepared statements are one of the best ways to prevent SQL injections. i.e., you shouldn't add your parameters as part of the final query string. You should use parameter placeholders, and add the parameters via a key/value array.

If you're using PDO, have a look at this page, which describes prepared statements in greater detail:

A quite thorough explanation of PHP's input filters (and a good article on sanitization) can be found here:

You are probably interested in the filter_var and filter_input functions:

php - How to prevent against XSS and SQL injection - Stack Overflow

php xss sql-injection
Rectangle 27 3

<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];


    public static function insertUpdate(array $attributes = [])
    {
        $model = new static($attributes);

        $model->fill($attributes);

        if ($model->usesTimestamps()) {
            $model->updateTimestamps();
        }

        $attributes = $model->getAttributes();

        $query = $model->newBaseQueryBuilder();
        $processor = $query->getProcessor();
        $grammar = $query->getGrammar();

        $table = $grammar->wrapTable($model->getTable());
        $keyName = $model->getKeyName();
        $columns = $grammar->columnize(array_keys($attributes));
        $insertValues = $grammar->parameterize($attributes);

        $updateValues = [];

        if ($model->primaryKey !== null) {
            $updateValues[] = "{$grammar->wrap($keyName)} = LAST_INSERT_ID({$keyName})";
        }

        foreach ($attributes as $k => $v) {
            $updateValues[] = sprintf("%s = '%s'", $grammar->wrap($k), $v);
        }

        $updateValues = join(',', $updateValues);

        $sql = "insert into {$table} ({$columns}) values ({$insertValues}) on duplicate key update {$updateValues}";

        $id = $processor->processInsertGetId($query, $sql, array_values($attributes));

        $model->setAttribute($keyName, $id);

        return $model;
    }
}
App\User::insertUpdate([
    'name' => 'Marco Pedraza',
    'email' => 'mpdrza@gmail.com'
]);
insert into `users` (`name`, `email`, `updated_at`, `created_at`) values (?, ?, ?, ?) on duplicate key update `id` = LAST_INSERT_ID(id),`name` = 'Marco Pedraza',`email` = 'mpdrza@gmail.com',`updated_at` = '2016-11-02 01:30:05',`created_at` = '2016-11-02 01:30:05'

The method automatically add/remove the Eloquent timestamps if you have enabled or disabled.

Hi, welcome to SO. Please don't just dump code, explain your train of thought so people can better understand your answer. Thanks.

Useful function that seems to be working, unlike the updateOrCreate function this one also updates the timestamps. However why does it update both? It should only update the updated_at, currently it also updates the created_at. And is there any way to use this function with bulk inserts? That's why I came looking for this otherwise the updateOrCreate function seemed to work ok aside from the fact it didn't automatically update the timestamps.

Laravel 5.1 Create or Update on Duplicate - Stack Overflow

laravel laravel-5 eloquent query-builder
Rectangle 27 35

Here is simple example. A contact has one to many associated phone numbers. When a contact is deleted, I want all its associated phone numbers to also be deleted, so I use ON DELETE CASCADE. The one-to-many/many-to-one relationship is implemented with by the foreign key in the phone_numbers.

CREATE TABLE contacts
 (contact_id BIGINT AUTO_INCREMENT NOT NULL,
 name VARCHAR(75) NOT NULL,
 PRIMARY KEY(contact_id)) ENGINE = InnoDB;

CREATE TABLE phone_numbers
 (phone_id BIGINT AUTO_INCREMENT NOT NULL,
  phone_number CHAR(10) NOT NULL,
 contact_id BIGINT NOT NULL,
 PRIMARY KEY(phone_id),
 UNIQUE(phone_number)) ENGINE = InnoDB;

ALTER TABLE phone_numbers ADD FOREIGN KEY (contact_id) REFERENCES \
contacts(contact_id) ) ON DELETE CASCADE;

By adding "ON DELETE CASCADE" to the foreign key constraint, phone_numbers will automatically be deleted when their associated contact is deleted.

INSERT INTO table contacts(name) VALUES('Robert Smith');
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8963333333', 1);
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8964444444', 1);

Now when a row in the contacts table is deleted, all its associated phone_numbers rows will automatically be deleted.

DELETE TABLE contacts as c WHERE c.id=1; /* delete cascades to phone_numbers */

To achieve the same thing in Doctrine, to get the same DB-level "ON DELETE CASCADE" behavoir, you configure the @JoinColumn with the onDelete="CASCADE" option.

<?php
namespace Entities;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * @Entity
 * @Table(name="contacts")
 */
class Contact 
{

    /**
     *  @Id
     *  @Column(type="integer", name="contact_id") 
     *  @GeneratedValue
     */
    protected $id;  

    /** 
     * @Column(type="string", length="75", unique="true") 
     */ 
    protected $name; 

    /** 
     * @OneToMany(targetEntity="Phonenumber", mappedBy="contact")
     */ 
    protected $phonenumbers; 

    public function __construct($name=null)
    {
        $this->phonenumbers = new ArrayCollection();

        if (!is_null($name)) {

            $this->name = $name;
        }
    }

    public function getId()
    {
        return $this->id;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function addPhonenumber(Phonenumber $p)
    {
        if (!$this->phonenumbers->contains($p)) {

            $this->phonenumbers[] = $p;
            $p->setContact($this);
        }
    }

    public function removePhonenumber(Phonenumber $p)
    {
        $this->phonenumbers->remove($p);
    }
}

<?php
namespace Entities;

/**
 * @Entity
 * @Table(name="phonenumbers")
 */
class Phonenumber 
{

    /**
    * @Id
    * @Column(type="integer", name="phone_id") 
    * @GeneratedValue
    */
    protected $id; 

    /**
     * @Column(type="string", length="10", unique="true") 
     */  
    protected $number;

    /** 
     * @ManyToOne(targetEntity="Contact", inversedBy="phonenumbers")
     * @JoinColumn(name="contact_id", referencedColumnName="contact_id", onDelete="CASCADE")
     */ 
    protected $contact; 

    public function __construct($number=null)
    {
        if (!is_null($number)) {

            $this->number = $number;
        }
    }

    public function setPhonenumber($number)
    {
        $this->number = $number;
    }

    public function setContact(Contact $c)
    {
        $this->contact = $c;
    }
} 
?>

<?php

$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);

$contact = new Contact("John Doe"); 

$phone1 = new Phonenumber("8173333333");
$phone2 = new Phonenumber("8174444444");
$em->persist($phone1);
$em->persist($phone2);
$contact->addPhonenumber($phone1); 
$contact->addPhonenumber($phone2); 

$em->persist($contact);
try {

    $em->flush();
} catch(Exception $e) {

    $m = $e->getMessage();
    echo $m . "<br />\n";
}
# doctrine orm:schema-tool:create --dump-sql

you will see that the same SQL will be generated as in the first, raw-SQL example

@przemo_li It is correct placement. The contact doesn't know phone numbers exist, because the phone numbers have a reference to the contact, and a contact doesn't have a reference to the phone numbers. So if a contact gets deleted, a phone number has a reference to a non-existing contact. In this case, we want something to happen: triggering the ON DELETE action. We decided to cascade the deletion, so to delete the phone numbers as well.

@przemi_li the onDelete="cascade" is placed correctly in the entity (on the child) because that is SQL cascading, which is placed on the child. Only the Doctrine cascading (cascade=["remove"], which is not used here) is placed on the parent.

php - On delete cascade with doctrine2 - Stack Overflow

php doctrine2 symfony cascading-deletes
Rectangle 27 1

Addition to @MarkR answer - one thing to note would be that many PHP frameworks with ORMs would not recognize or use advanced DB setup (foreign keys, cascading delete, unique constraints), and this may result in unexpected behaviour.

For example if you delete a record using ORM, and your DELETE CASCADE will delete records in related tables, ORM's attempt to delete these related records (often automatic) will result in error.

That would bea reason to not use that particular ORM. Any tool that is that poor at database support is not trustworthy. Foreign keys and cascading deletes or updates are db basics not advanced concepts and no realtional database should ever be designed without foreign key constraints!

mysql - Foreign key constraints: When to use ON UPDATE and ON DELETE -...

mysql sql database foreign-keys
Rectangle 27 3

The key is must-revalidate: This means, that the client is asking the server if the file has changed. If you dont handle this case, the browser will fetch a new copy.

$_SERVER['HTTP_IF_NONE_MATCH']
$_SERVER['HTTP_IF_MODIFIED_SINCE']

So what your saying is, it is possible to cache "images, CSS, scripts, etc." using this method without having to modify server configs?

Yes, static files are handled by the server. Executable files (PHP, SSI, CGI) have to do this on their own, because the server cannot know, what content they produce.

This answer is wrong - the header provided will force caching of the content if implemented properly.

php - how to use control-cache headers? - Stack Overflow

php caching header
Rectangle 27 90

While the answers here are definately working, they are using a GET request, which exposes your private key (even though https is used). On Google Developers the specified method is POST.

function isValid() 
{
    try {

        $url = 'https://www.google.com/recaptcha/api/siteverify';
        $data = ['secret'   => '[YOUR SECRET KEY]',
                 'response' => $_POST['g-recaptcha-response'],
                 'remoteip' => $_SERVER['REMOTE_ADDR']];

        $options = [
            'http' => [
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($data) 
            ]
        ];

        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return json_decode($result)->success;
    }
    catch (Exception $e) {
        return null;
    }
}

Array Syntax: I use the "new" array syntax ( [ and ] instead of array(..) ). If your php version does not support this yet, you will have to edit those 3 array definitions accordingly (see comment).

Return Values: This function returns true if the user is valid, false if not, and null if an error occured. You can use it for example simply by writing if (isValid()) { ... }

$data = ...
$options = ...
$data = array('secret'   => '[YOUR SECRET KEY]',                  'response' => $_POST['g-recaptcha-response'],                  'remoteip' => $_SERVER['REMOTE_ADDR']);          $options = array(             'http' => array(                 'header'  => "Content-type: application/x-www-form-urlencoded\r\n",                 'method'  => 'POST',                 'content' => http_build_query($data)              )         );
if (empty($_POST['g-recaptcha-response'])) {   return false; }

https urls are actually encrypted, so the private key is not exposed even when using a GET request, see: stackoverflow.com/questions/499591/are-https-urls-encrypted

Please note, for debugging purposes, you can only call isValid() once. If called a second time, it will return false. Found this out the hard way with an echo statement...

Something like this should be in the official docs...

new google recaptcha with checkbox server side php - Stack Overflow

php recaptcha
Rectangle 27 90

While the answers here are definately working, they are using a GET request, which exposes your private key (even though https is used). On Google Developers the specified method is POST.

function isValid() 
{
    try {

        $url = 'https://www.google.com/recaptcha/api/siteverify';
        $data = ['secret'   => '[YOUR SECRET KEY]',
                 'response' => $_POST['g-recaptcha-response'],
                 'remoteip' => $_SERVER['REMOTE_ADDR']];

        $options = [
            'http' => [
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($data) 
            ]
        ];

        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return json_decode($result)->success;
    }
    catch (Exception $e) {
        return null;
    }
}

Array Syntax: I use the "new" array syntax ( [ and ] instead of array(..) ). If your php version does not support this yet, you will have to edit those 3 array definitions accordingly (see comment).

Return Values: This function returns true if the user is valid, false if not, and null if an error occured. You can use it for example simply by writing if (isValid()) { ... }

$data = ...
$options = ...
$data = array('secret'   => '[YOUR SECRET KEY]',                  'response' => $_POST['g-recaptcha-response'],                  'remoteip' => $_SERVER['REMOTE_ADDR']);          $options = array(             'http' => array(                 'header'  => "Content-type: application/x-www-form-urlencoded\r\n",                 'method'  => 'POST',                 'content' => http_build_query($data)              )         );
if (empty($_POST['g-recaptcha-response'])) {   return false; }

https urls are actually encrypted, so the private key is not exposed even when using a GET request, see: stackoverflow.com/questions/499591/are-https-urls-encrypted

Please note, for debugging purposes, you can only call isValid() once. If called a second time, it will return false. Found this out the hard way with an echo statement...

Something like this should be in the official docs...

new google recaptcha with checkbox server side php - Stack Overflow

php recaptcha
Rectangle 27 254

The new PHP password API (5.5.0+)

The easiest way to get your password storage scheme secure is by using a standard library.

Because security tends to be a lot more complicated and with more invisible screw up possibilities than most programmers could tackle alone, using a standard library is almost always easiest and most secure (if not the only) available option.

If you are using PHP version 5.5.0 or newer, you can use the new simplified password hashing API

Example of code using PHP's password API:

<?php
// $hash is what you would store in your database
$hash = password_hash($_POST['password'], PASSWORD_DEFAULT, ['cost' => 12]);

// $hash would be the $hash (above) stored in your database for this user
$checked = password_verify($_POST['password'], $hash);
if ($checked) {
    echo 'password correct';
} else {
    echo 'wrong credentials';
}

(In case you are still using legacy 5.3.7 or newer you can install ircmaxell/password_compat to have access to the build-in functions)

If you want extra security, the security folks now (2017) recommend adding a 'pepper' to the (automatically) salted password hashes.

There is a simple, drop in class that securely implements this pattern, I recommend: Netsilik/PepperedPasswords (github). It comes with a MIT License, so you can use it however you want, even in proprietary projects.

Netsilik/PepperedPasswords
<?php
use Netsilik/Lib/PepperedPasswords;

// Some long, random, binary string, encoded as hexadecimal; stored in your configuration (NOT in your Database, as that would defeat the entire purpose of the pepper).
$config['pepper'] = hex2bin('012345679ABCDEF012345679ABCDEF012345679ABCDEF012345679ABCDEF');

$hasher = new PepperedPasswords($config['pepper']);

// $hash is what you would store in your database
$hash = $hasher->hash($_POST['password']);

// $hash would be the $hash (above) stored in your database for this user
$checked = $hasher->verify($_POST['password'], $hash);
if ($checked) {
    echo 'password correct';
} else {
    echo 'wrong credentials';
}

Please note: you should not be needing this anymore! This is only here for historical purposes.

Take a look at: Portable PHP password hashing framework: phpass and make sure you use the CRYPT_BLOWFISH algorithm if at all possible.

Example of code using phpass (v0.2):

<?php
require('PasswordHash.php');

$pwdHasher = new PasswordHash(8, FALSE);

// $hash is what you would store in your database
$hash = $pwdHasher->HashPassword( $password );

// $hash would be the $hash (above) stored in your database for this user
$checked = $pwdHasher->CheckPassword($password, $hash);
if ($checked) {
    echo 'password correct';
} else {
    echo 'wrong credentials';
}
  • WordPress 2.5+ as well as bbPress

The good thing is that you do not need to worry about the details, those details have been programmed by people with experience and reviewed by many folks on the internet.

do not use MD5 or SHA1 anymore

Currently, using crypt, with CRYPT_BLOWFISH is the best practice. CRYPT_BLOWFISH in PHP is an implementation of the Bcrypt hash. Bcrypt is based on the Blowfish block cipher, making use of it's expensive key setup to slow the algorithm down.

Yes, yes, a thousand times yes.

Good answer - thanks. phpass is a good option. But note that the "standard libraries" in some popular frameworks and apps are bad. See e.g. the horrid story of the MySQL OLD_PASSWORD cryptanalysis? and the sad story of their bad replacement: Looking for example of well-known app using unsalted hashes - IT Security The latter link has other examples of bad standard password functions.

MD5 and SHA1 are not broken in general (though they have some weaknesses, and for general purpose hashing SHA-2 should be used instead), they are just too fast to avoid bruteforce/dictionary password attacks (as SHA-2 and probably SHA-3, too).

php - How can I store my users' passwords safely? - Stack Overflow

php security passwords salt password-hash
Rectangle 27 254

The new PHP password API (5.5.0+)

The easiest way to get your password storage scheme secure is by using a standard library.

Because security tends to be a lot more complicated and with more invisible screw up possibilities than most programmers could tackle alone, using a standard library is almost always easiest and most secure (if not the only) available option.

If you are using PHP version 5.5.0 or newer, you can use the new simplified password hashing API

Example of code using PHP's password API:

<?php
// $hash is what you would store in your database
$hash = password_hash($_POST['password'], PASSWORD_DEFAULT, ['cost' => 12]);

// $hash would be the $hash (above) stored in your database for this user
$checked = password_verify($_POST['password'], $hash);
if ($checked) {
    echo 'password correct';
} else {
    echo 'wrong credentials';
}

(In case you are still using legacy 5.3.7 or newer you can install ircmaxell/password_compat to have access to the build-in functions)

If you want extra security, the security folks now (2017) recommend adding a 'pepper' to the (automatically) salted password hashes.

There is a simple, drop in class that securely implements this pattern, I recommend: Netsilik/PepperedPasswords (github). It comes with a MIT License, so you can use it however you want, even in proprietary projects.

Netsilik/PepperedPasswords
<?php
use Netsilik/Lib/PepperedPasswords;

// Some long, random, binary string, encoded as hexadecimal; stored in your configuration (NOT in your Database, as that would defeat the entire purpose of the pepper).
$config['pepper'] = hex2bin('012345679ABCDEF012345679ABCDEF012345679ABCDEF012345679ABCDEF');

$hasher = new PepperedPasswords($config['pepper']);

// $hash is what you would store in your database
$hash = $hasher->hash($_POST['password']);

// $hash would be the $hash (above) stored in your database for this user
$checked = $hasher->verify($_POST['password'], $hash);
if ($checked) {
    echo 'password correct';
} else {
    echo 'wrong credentials';
}

Please note: you should not be needing this anymore! This is only here for historical purposes.

Take a look at: Portable PHP password hashing framework: phpass and make sure you use the CRYPT_BLOWFISH algorithm if at all possible.

Example of code using phpass (v0.2):

<?php
require('PasswordHash.php');

$pwdHasher = new PasswordHash(8, FALSE);

// $hash is what you would store in your database
$hash = $pwdHasher->HashPassword( $password );

// $hash would be the $hash (above) stored in your database for this user
$checked = $pwdHasher->CheckPassword($password, $hash);
if ($checked) {
    echo 'password correct';
} else {
    echo 'wrong credentials';
}
  • WordPress 2.5+ as well as bbPress

The good thing is that you do not need to worry about the details, those details have been programmed by people with experience and reviewed by many folks on the internet.

do not use MD5 or SHA1 anymore

Currently, using crypt, with CRYPT_BLOWFISH is the best practice. CRYPT_BLOWFISH in PHP is an implementation of the Bcrypt hash. Bcrypt is based on the Blowfish block cipher, making use of it's expensive key setup to slow the algorithm down.

Yes, yes, a thousand times yes.

Good answer - thanks. phpass is a good option. But note that the "standard libraries" in some popular frameworks and apps are bad. See e.g. the horrid story of the MySQL OLD_PASSWORD cryptanalysis? and the sad story of their bad replacement: Looking for example of well-known app using unsalted hashes - IT Security The latter link has other examples of bad standard password functions.

MD5 and SHA1 are not broken in general (though they have some weaknesses, and for general purpose hashing SHA-2 should be used instead), they are just too fast to avoid bruteforce/dictionary password attacks (as SHA-2 and probably SHA-3, too).

php - How can I store my users' passwords safely? - Stack Overflow

php security passwords salt password-hash
Rectangle 27 4

How to get the current key of an array when using array_filter

Regardless of how I like Vincent's solution for Maek's problem, it doesn't actually use array_filter. If you came here from a search engine you maybe where looking for something like this (PHP >= 5.3):

$array = ['apple' => 'red', 'pear' => 'green'];
reset($array); // Unimportant here, but make sure your array is reset

$apples = array_filter($array, function($color) use ($&array) {
  $key = key($array);
  next($array); // advance array pointer

  return key($array) === 'apple';
}

It passes the array you're filtering as a reference to the callback. As array_filter doesn't conventionally iterate over the array by increasing it's public internal pointer you have to advance it by yourself.

What's important here is that you need to make sure your array is reset, otherwise you might start right in the middle of it.

In PHP >= 5.4 you could make the callback even shorter:

$apples = array_filter($array, function($color) use ($&array) {
  return each($array)['key'] === 'apple';
}

PHP: How to use array_filter() to filter array keys? - Stack Overflow

php arrays
Rectangle 27 2

Since your primary key is (firstName, lastName), you don't need php to prevent insertion of duplicate values. Mysql does that for you, because primary keys have to be unique. (if it was'nt your primary key you could use a unique constraint)

mysqli_errno($dbc)
1062
or die('Error querying database.');
or die(mysqli_errno($dbc) == 1062 ? "Client already listed" : 'Error querying database.');

mysql - Prevent duplicate records to a table using PHP - Stack Overflo...

php mysql
Rectangle 27 2

Since your primary key is (firstName, lastName), you don't need php to prevent insertion of duplicate values. Mysql does that for you, because primary keys have to be unique. (if it was'nt your primary key you could use a unique constraint)

mysqli_errno($dbc)
1062
or die('Error querying database.');
or die(mysqli_errno($dbc) == 1062 ? "Client already listed" : 'Error querying database.');

mysql - Prevent duplicate records to a table using PHP - Stack Overflo...

php mysql
Rectangle 27 53

Try this PHP5 class for encryption using mcrypt. In this case it's using AES encryption. You'll want to change the key for each site you use it on. If you don't use it at least it may guide you on writing your own version of it.

<?php

class Encryption
{
    const CIPHER = MCRYPT_RIJNDAEL_128; // Rijndael-128 is AES
    const MODE   = MCRYPT_MODE_CBC;

    /* Cryptographic key of length 16, 24 or 32. NOT a password! */
    private $key;
    public function __construct($key) {
        $this->key = $key;
    }

    public function encrypt($plaintext) {
        $ivSize = mcrypt_get_iv_size(self::CIPHER, self::MODE);
        $iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
        $ciphertext = mcrypt_encrypt(self::CIPHER, $this->key, $plaintext, self::MODE, $iv);
        return base64_encode($iv.$ciphertext);
    }

    public function decrypt($ciphertext) {
        $ciphertext = base64_decode($ciphertext);
        $ivSize = mcrypt_get_iv_size(self::CIPHER, self::MODE);
        if (strlen($ciphertext) < $ivSize) {
            throw new Exception('Missing initialization vector');
        }

        $iv = substr($ciphertext, 0, $ivSize);
        $ciphertext = substr($ciphertext, $ivSize);
        $plaintext = mcrypt_decrypt(self::CIPHER, $this->key, $ciphertext, self::MODE, $iv);
        return rtrim($plaintext, "\0");
    }
}
$key = /* CRYPTOGRAPHIC!!! key */;
$crypt = new Encryption($key);
$encrypted_string = $crypt->encrypt('this is a test');
$decrypted_string = $crypt->decrypt($encrypted_string); // this is a test
  • This class is not safe for use with binary data (which may end in NUL bytes)
  • This class does not provide authenticated encryption.

Will this work for binary data such as images?

That's correct. I ran this class on text files, and it worked great. For binary files it is necessary to encode the information before encrypting it. If the files are larger than 100MB or so, base64_encode will cause performance issues, so you may want to consider splitting the files into chunks for encrypting. From a security standpoint this isn't an ideal solution because it provides more opportunity for recovering partial plaintext. But, it works.

Can we add a strong disclaimer? Authenticated encryption is absolutely essential to defend against active attackers. There's really no way to negotiate it away unless you cripple your threat model below what the average script kiddie can pull off, which helps approximately no one.

"Authenticated encryption is not necessary." Wrong. Super wrong. Authenticated encryption is no longer negotiable.

php - Encrypting / Decrypting file with Mcrypt - Stack Overflow

php file mcrypt
Rectangle 27 2

The syntax highlighter shows you where your problem is:

$sql='UPDATE style_test SET ;.$setlist.' WHERE user_id='.$user_id;
                            ^
                            Here

This needs to be a single quote:

$sql='UPDATE style_test SET '.$setlist.' WHERE user_id='.$user_id;

You should also note that the mysql_* functions are deprecated, and you should not be using them. Also, your original code is wide open to SQL injection.

For on duplicate key update, you add that to your SQL query, followed by all the column = value fields you want to update:

$sql='INSERT INTO style_test SET ' . $setlist.' WHERE user_id = ' . $user_id. ' ON DUPLICATE KEY UPDATE ' . $setlist;

That did it :-D Thanks for catching that :-) Now that it's working it made me realize that I really need to be using 'On Duplicate Key UPDATE' and I edited the question accordingly.

I also appreciate your pointing out the other issues, and I'm going to look into how to modify the code to prevent injection asap. I wasn't sure what you meant though about the mysql_* functions being deprecated since the code I've used is based on W3schools suggested code and I couldn't find anything that seemed to be an issue in their list of deprecated functions. Would it be better to use: $result = @mysql_query($qry); if($result) { exit(); }else { die('Error: ' . mysql_error()); } Instead of: if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); }

No, then you are suppressing errors. You should be using PDO. There are plenty of examples on stackoverflow and the docs to get you started.

I'll look into that :-) But would you mind clarifying for me which part of my code is a problem due to being deprecated?

mysql_query() is being deprecated, you can see the red box on the doc page for it. Also, the other part of your problem is SQL injection, which PDO can fix if you used prepared statements (all things you can search for examples).

php - Using INSERT INTO On Duplicate Key UPDATE for form input - Stack...

php mysql on-duplicate-key
Rectangle 27 18

You can access values in the $_POST array by their key. $_POST is an associative array, so to access taskOption you would use $_POST['taskOption'];.

Make sure to check if it exists in the $_POST array before proceeding though.

<form method="post" action="process.php">
  <select name="taskOption">
    <option value="first">First</option>
    <option value="second">Second</option>
    <option value="third">Third</option>
  </select>
  <input type="submit" value="Submit the form"/>
</form>
<?php
   $option = isset($_POST['taskOption']) ? $_POST['taskOption'] : false;
   if ($option) {
      echo htmlentities($_POST['taskOption'], ENT_QUOTES, "UTF-8");
   } else {
     echo "task option is required";
     exit; 
   }

Your process.php API 200s when the request is missing required parameters. It should 400.

php - Using $_POST to get select option value from HTML - Stack Overfl...

php html arrays