1

Hi,

in addition, have you tried with SplFixedArray? It should be faster than standard arrays. Also if you want to open files from the script, than use fopen() instead of file_get_contents(), because the latter will load the entire file in memory before starting processing, while the former will read in chunks and start the execution immediately.

See: http://php.net/manual/en/class.splfixedarray.php

1

Hmm, no, here I'm not accepting passwords from users. It's a server side configuration step to connect Solr with MySQL. Solr is a search engine service developed by Apache. Here I'm setting the credentials into a configuration file, named data-config.xml to access the database. This file can store the database password in plain text or in an encrypted version.

I have an issue with the encrypted implementation. In practice it reads the value from the configuration file, but it does not decrypt and I wonder if it's caused by the IV value. I understand your point, but I cannot refactor this part, unless I'm missing something, also because resetting those values would mean to restart Solr, unless doing something like suggested (but not shown :D):

I'm not sure it's doable with the current version. Anyway, the methods I'm showing above are from the Solr code, I seeked them from the source version, to understand the error log.

As far as I know it can be added the Data Encryption (SSL) to the JDBC driver to enhance security, which will happen as soon this works, but in order to make the connection to the database, Solr has to decrypt the password stored in the configuration file.

3

Just to support rproffitt's, on Ubuntu 16.04 it redirects to 127::1:

» ping -c 3 0.0.0.0                                                                                       
PING 0.0.0.0 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.055 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.029 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.048 ms

--- 0.0.0.0 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1998ms
rtt min/avg/max/mdev = 0.029/0.044/0.055/0.011 ms

On Mac OS it fails:

$ ping -c 3 0.0.0.0
PING 0.0.0.0 (0.0.0.0): 56 data bytes
ping: sendto: No route to host
ping: sendto: No route to host
Request timeout for icmp_seq 0
ping: sendto: No route to host
Request timeout for icmp_seq 1
^C
--- 0.0.0.0 ping statistics ---
3 packets transmitted, 0 packets received, 100.0% packet loss
Votes + Comments
Thanks for the tests.
1

Ah, no. Okay for that you need variable variables:

For example:

<?php

$start_balance = 2;
$stop = 5;
$roi  = 5;
$sum  = 0;

for($i = 1; $i <= $stop; $i++)  
{
    if(1 == $i)
        $sum = $roi * $start_balance;

    elseif(2 == $i)
        ${'sum' . $i} = $roi * $sum;

    else
        ${'sum' . $i} = $roi * ${'sum' . ($i - 1)};
}

print_r(get_defined_vars()) . PHP_EOL;

Which prints, among the other variables:

[sum]  => 10
[sum2] => 50
[sum3] => 250
[sum4] => 1250
[sum5] => 6250

Which means the loop defined these variables $sum, $sum2, ..., $sum5. If you want to use a function, then keep in mind that the variables will be set in the function scope, so these won't be available outside, unless you set them global:

function _sum($start_balance = 0, $stop = 1, $roi = 1)
{
    for($i = 1; $i <= $stop; $i++)  
    {
        if(1 == $i)
        {
            global $sum;
            $sum = $roi * $start_balance;
        }

        elseif(2 == $i)
        {
            global ${'sum' . $i};
            ${'sum' . $i} = $roi * $sum;
        }

        else
        {
            global ${'sum' . $i};
            ${'sum' . $i} = $roi * ${'sum' . ($i - 1)};
        }
    }
}

_sum(2, 5, 5);

If you explain why you need it like this, maybe we can suggest a better solution.

Votes + Comments
+ for making a solution with variable variables. This same approach can be done with an array resulting cleaner code and easier maintenance
1

Hi,

you can use a for() loop and the assignment operator *=, for example:

<?php

function _sum($start_balance = 0, $stop = 1, $roi = 1)
{
    for($i = 0, $sum = $start_balance * $roi; $i < $stop - 1; $sum *= $roi, $i++) { }
    return $sum;
}

print _sum(2, 5, 5);

But if you plan to use floats or to produce big numbers, then you have to change approach, use BCMath or GMP and read carefully about floating point quirks (which BCMath solves):

1

Hi,

usually you define which column (or columns) mark a row as a duplicate and set a unique key index, so you have to alter your table schema. Once this is done add IGNORE to your insert query:

INSERT IGNORE into excel(excel_name, excel_email) values('name', 'email@address');

Then use:

$affected = mysqli_affected_rows($connect);

It will return an integer: 0 if the insert failed, 1 if it occurred, -1 means there was an error. For more information, read:

Also, use prepared statements, do not use PHP variables inside queries. And, please, make meaningful titles for your threads: "php" does not help anyone.

2

If implemented, IMO, it should be consistent through all code as jQuery does.

Using mutators and accessors, as described by jkon, can simplify because the naming suggests what to expect: setSomething(), getSomething(). Even if more verbose.

Anyway, I made a small research, this could be defined as dynamic dispatch which can be combined with traits, in the end you could create methods with similar names which are choosen by the reflection library basing on the signature (parameter types).

An example is here:

Here's the source:

Which however does not deal with empty methods, so I made few small changes to __candidateMatch() and to __resolveparameterTypes() which was not handling booleans correctly, now it seems to work fine (pasting outside, because the post is too long):

Here's the test class:

<?php

require 'overloader.php';

class Test {

    use Overloader;

    private $_producers;
    private $_song;
    private $_songs;

    // Producers //

    public function producers_set(string $str)
    {
        $this->_producers = $str;
        return $this;
    }

    public function producers_get()
    {
        if(property_exists($this, '_producers'))
            return $this->_producers;

        return '';
    }

    public function producers_unset(bool $unset)
    {
        $this->_producers = NULL;
        return $this;
    }

    // Song //

    public function song_set(string $str)
    {
        $this->_song = $str;
        return $this;
    }

    public function song_get()
    {
        if(property_exists($this, '_song'))
            return $this->_song;

        return '';
    }

    public function song_unset(bool $unset)
    {
        $this->_song = NULL;
        return $this;
    }

    // Songs //

    public function songs_set(string $str)
    {
        $this->_songs[] = $str;
        return $this;
    }

    public function songs_get()
    {
        if(property_exists($this, '_songs'))
            return implode(', ', $this->_songs);

        return '';
    }

    public function songs_unset(bool ...
Votes + Comments
Outstanding post and effort. Give me some time to process it! Songs :D
Very interesting songs
2

Hi,

you can create DOM nodes, see:

As example:

<button id="button">Add</button>
<div id="box"></div>

<script type="text/javascript">
    var btn = document.getElementById('button');
    var box = document.getElementById('box');

    btn.addEventListener('click', function(event) {
      event.preventDefault();

      // create elements
      let child_img = document.createElement('img');
      let div1 = document.createElement('div');
      let div1_text = document.createTextNode('$87.03');

      let div2 = document.createElement('div');
      let div2_text = document.createTextNode('Some text');

      // append attributes
      div1.classList.add('value');
      div2.classList.add('subtext');
      child_img.setAttribute('src', 'http://lorempixel.com/400/200/sports/');

      // append img to box
      box.appendChild(child_img);

      // append text node to div1 and div1 to box
      div1.appendChild(div1_text);
      box.appendChild(div1);

      // append text node to div2 and div2 to box
      div2.appendChild(div2_text);
      box.appendChild(div2);

    }, {
      passive: false
    });
</script>

The live example is here: https://jsfiddle.net/fmbe1yyd/

Obviously you have to change the code to insert dynamic data, so if you have difficulties to make it work, explain better your issue, for example from where you get the input used to populate the elements that you want to create?

1

I would say there are many drawbacks with shared hostings. What do you need it for?

Personally I try to avoid them. Once I was asked to find why a specific website at a specific hour stopped working, after some research I saw that MySQL had max_user_connections & max_connections set to 161 (which is very low). In practice one of the other websites opened so many permanent connections, during that hour, that the pool of the server was saturated, so all the other attempts were going in timeout.

Similar issues happens if the open file limit of MySQL is to low and if in the server there are too many tables, which are files. If the limit is reached, then it causes accessing errors.

1

// EDIT
I just saw your reply, I'm glad you solved!

// Old answer
Hmm,

as far $permissions is defined by the input and defaulting to the database and not like an array:

$permissions = ((isset($_POST['permissions']) && $_POST['permissions'] != '')?sanitize($_POST['permissions']):$User['permissions']);

you can hardcode the options in the select tag, and then just compare which is set:

<select name="permissions">
    <option value="editor" <?php echo (0 == strcasecmp($permissions, 'editor')) ? ' selected="selected"' : ''; ?>>Editor</option>
    <option value="admin,editor" <?php echo (0 == strcasecmp($permissions, 'admin,editor')) ? ' selected="selected"' : ''; ?>>Admin,Editor</option>
</select>

For the sanitazation you could also write:

$permissions = filter_input(INPUT_POST, 'permissions', FILTER_SANITIZE_STRING) ? : $User['permissions'];

filter_input() will fail to FALSE or NULL if the filter fails or the input is not set, in both cases will fallback to $User['permission'], instead, it will return a string on success.

I usually manage selects through two functions:

if ( ! function_exists('_form_select'))
{
    /**
     * Create <select>
     *
     * $array_options format:
     *
     *  'option value' => 'text'
     * 
     * @param  string $name
     * @param  string $label
     * @param  array  $array_options
     * @param  string $selected
     * @return string
     */
    function _form_select($name, $label, $array_options, $selected = FALSE)
    {
        $template = '
        <label for="%1$s">%2$s</label>
        <select name="%1$s" id="%1$s">
            %3$s
        </select>
        ';

        $options = '';

        foreach($array_options as $key => $value)
            $options .= _form_options($key, $value, $selected);        

        return sprintf($template, $name, $label, $options);
    }
}

if ( ! function_exists('_form_options'))
{
    /**
     * Create <option>
     * 
     * @param  string  $key
     * @param  string  $value
     * @param  boolean $selected
     * @return string
     */
    function _form_options($key, $value, $selected ...
1

Hi,

you are trying to iterate the same result set two times: on line 28 and 106. On line 28 you get the first row, so if the query returns only one, you don't get anything when you call mysqli_fetch_assoc() again on line 106. You can use $User otherwise, if you need to loop again, insert data_seek() at line 105:

mysqli_data_seek($userResults, 0);

This will rewind the result set. Documentation:

1

Hi,

it can depend on the path of the files, for example:

$xls  = "Sealing Report/{$date}/sealing_production.xls";
$xls1 = "Sealing Report/{$date}/sealing_assembly.xls";

the path is relative to the script position, so if the files are in the same directory of the main index.php, then change them to:

$xls  = FCPATH . "Sealing Report/{$date}/sealing_production.xls";
$xls1 = FCPATH . "Sealing Report/{$date}/sealing_assembly.xls";

the FCPATH constant is set in the main index.php file and refers to the directory of this file. Also you could serve an array list to the function, so:

$attach_list = [$xls, $xlsl];

Once you have done this, add the $attachments argument to your function and a loop to add the files to the message:

<?php

function sendfullmail($receipient, $title, $message, $cc = '', $bcc = '', $attachments = [])
{
    $this->load->library('email');

    $this->email->from($this->from, $this->fromname);
    $this->email->to($receipient);

    if('' !== $cc)
        $this->email->cc($cc);

    if('' === $bcc)
        $bcc = 'sindisystem@gmail.com';

    else
        $bcc .= ',sindisystem@gmail.com';

    $this->email->bcc($bcc);

    if(is_array($attachments) && 0 < ($c = count($attachments)))
        for($i = 0; $i < $c; $i++)
            $this->email->attach($attachments[$i]);

    elseif(is_string($attachments))
        $this->email->attach($attachments);

    $this->email->subject($title);
    $this->email->message($message);
    $this->email->set_alt_message($this->alt);
    return $this->email->send();
}

$xls  = FCPATH . "Sealing Report/{$date}/sealing_production.xls";
$xls1 = FCPATH . "Sealing Report/{$date}/sealing_assembly.xls";

// or submit a string: $attach_list = $xls;
$attach_list = [$xls, $xlsl];

sendfullmail('recipient@mail.tld', 'Hello', 'here you go', '', '', $attach_list);

If by adjusting the path it still does not work, then set send() to FALSE and add the print_debugger() method:

// You need to pass FALSE while sending in order for the email data
// to not be cleared - if that happens, print_debugger() would have
// nothing to ...
1

Hi,

if your target is worldwide, then provide an English version of the site: not only of the contents, but also of the links. See this for example:

http://iraniantranslate.com/%D8%AF%D8%B1%D8%A8%D8%A7%D8%B1%D9%87-%D9%85%D8%A7/

which on the browser bar displays http://iraniantranslate.com/درباره-ما/, but if I use the browser option Copy link address then I get the encoded version which doesn't help to understand the meaning of the link. Also not all pages look complete.

Votes + Comments
Sound advice
2

You're welcome :)

As I said the script block must be placed at the bottom of the <body> block, after all the other codes, so:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Example</title>
  <style type="text/css">
    body {
      font-family:Arial, sans-serif;
    }

    #wrapper {
      margin-left:300px;
    }

    .column {
      float: left;
    }

    .column div {
      border: 1px solid #000;
      padding: 4px;
      margin: 2px;
      width: 15px;
      height: 15px;
      text-align: center;
      cursor: pointer;
    }

  </style>
</head>
<body>

  <div id="wrapper">
   <div id="Content">

      <p>
        <input class="btn_colors" data-color="#007FFF" type="button" name="blue" id="blue" value="Blue" />
        <input class="btn_colors" data-color="#F2B400" type="button" name="yellow" id="yellow" value="Yellow" />
        <input class="btn_colors" data-color="#66B447" type="button" name="green" id="green" value="Green" />
      </p>

      <div class="column">
        <div>20</div>
        <div>60</div>
      </div>
      <div class="column">
        <div>72</div>
        <div>71</div>
      </div>
      <div class="column">
        <div>88</div>
        <div>87</div>
      </div>
      <div class="column">
        <div>64</div>
        <div>53</div>
      </div>
      <div class="column">
        <div>90</div>
        <div>79</div>
      </div>
      <div class="column">
        <div>54</div>
        <div>73</div>
      </div>
      <div class="column">
        <div>74</div>
        <div>63</div>
      </div>
      <div class="column">
        <div>98</div>
        <div>57</div>
      </div>
      <div class="column">
        <div>74</div>
        <div>63</div>
      </div>

    </div>
  </div>

  <script type='text/javascript'>

    // variables
    var buttons = document.getElementsByClassName('btn_colors');
    var numbers = document.querySelectorAll('.column > div');
    var current_color = document.getElementById('green').getAttribute('data-color');

    // listener for button clicks
    for (let i = 0, c = buttons.length; i < c; i++)
      buttons[i].addEventListener('click', set_color, {
        passive: false
      });

    // listener for number cells
    for (let i = 0, c = numbers.length; i < c; i++)
      numbers[i].addEventListener('click', set_bg, {
        passive: false
      });

    // functions
    function set_color(event) {
      event.preventDefault();
      current_color = this.getAttribute('data-color');
    }

    function set_bg(event) {
      if(this.classList.contains('clicked'))
      {
        this.classList.remove('clicked');
        this.style.backgroundColor = 'transparent';
        return ;
      }

      this.style.backgroundColor = current_color;
      this.classList.add('clicked');
    }

  </script>

</body>
</html>

In this position the browser has already parsed ...

Votes + Comments
Beautiful
2

Hi,

you can use plain javascript:

// variables
var buttons = document.getElementsByClassName('btn_colors');
var numbers = document.querySelectorAll('.column > div');
var current_color = document.getElementById('green').getAttribute('data-color');

// listener for button clicks
for (let i = 0, c = buttons.length; i < c; i++)
  buttons[i].addEventListener('click', set_color, {
    passive: false
  });

// listener for number cells
for (let i = 0, c = numbers.length; i < c; i++)
  numbers[i].addEventListener('click', set_bg, {
    passive: false
  });

// functions
function set_color(event) {
  event.preventDefault();
  current_color = this.getAttribute('data-color');
}

function set_bg(event) {
  if(this.classList.contains('clicked'))
  {
    this.classList.remove('clicked');
    this.style.backgroundColor = 'transparent';
    return ;
  }

  this.style.backgroundColor = current_color;
  this.classList.add('clicked');
}

And in the HTML part just add data-color="COLOR" and class="btn_colors" to the buttons, where COLOR is the name or the code to assign to the backgroundColor property:

<p>
    <input class="btn_colors" data-color="#007FFF" type="button" name="blue" id="blue" value="Blue" />
    <input class="btn_colors" data-color="#F2B400" type="button" name="yellow" id="yellow" value="Yellow" />
    <input class="btn_colors" data-color="#66B447" type="button" name="green" id="green" value="Green" />
</p>

Live example: https://jsfiddle.net/tsLgtzkv/

In your case, in your example you were not loading JQuery, and not setting to run on onDomready. In my example there is no dependency, but it should run in the body, after all the HTML, to allow the browser to complete the parsing.

Votes + Comments
Excellent!
1
3

Hi,

if you don't want to allow duplicates then set a unique constraint to the brand column, and then use INSERT IGNORE ..., INSERT ... ON DUPLICATE KEY UPDATE ... or a regular update query. An example:

create table `brands` (
  `id` int unsigned auto_increment primary key,
  `brand` varchar(100) unique not null
) engine = innodb;

insert into `brands` (`brand`) values('sony'),('canon'),('nikon'),('fuji'),('pentax'),('zeiss');

> select * from `brands` order by `id`;
+------+---------+
|   id | brand   |
|------+---------|
|    1 | sony    |
|    2 | canon   |
|    3 | nikon   |
|    4 | fuji    |
|    5 | pentax  |
|    6 | zeiss   |
+------+---------+
6 rows in set
Time: 0.003s

Now, if you try a regular insert, you get an error for duplicated entry:

> insert into `brands` (`brand`) values('Canon');
(1062, "Duplicate entry 'Canon' for key 'brand'")

If instead you use the INSERT ... ON DUPLICATE KEY UPDATE ... the existing row gets updated and your script can continue:

> insert into `brands` (`brand`) values('Canon') on duplicate key update `brand` = 'Canon';
> select * from `brands` order by `id`;

+------+---------+
|   id | brand   |
|------+---------|
|    1 | sony    |
|    2 | Canon   |
|    3 | nikon   |
|    4 | fuji    |
|    5 | pentax  |
|    6 | zeiss   |
+------+---------+
6 rows in set
Time: 0.003s

What can happen? If in the edit form you select Canon id, and in the input field you write Zeiss, with this setup ...

Votes + Comments
Great
1

It should be easy, in practice there are 5 select queries that group the rows by the choosen pairs, in the case below the pair is composed by the columns b1 and b2:

SELECT b1 AS 'x', b2 AS 'y', tot
  FROM (SELECT b1, b2, COUNT(id) AS tot
          FROM numbers
         GROUP BY b1, b2
         ORDER BY tot DESC)
    AS sub
 WHERE sub.tot > @threshold

each following query moves to the next column, so you go from b1,b2 to b2,b3 and so on until you reach the last b5,b6.

The UNION ALL statement is used to return the results together. Otherwise you should run five separated requests. It's not a join because each result is separated from the others, the database engine checks only that, the number of columns defined in the SELECT statements, matches all along the query. By using strings it would look like this:

> select 'a', 'b' union all select 'b', 'c' union all select 'c', 'd';

+-----+-----+
| a   | b   |
|-----+-----|
| a   | b   |
| b   | c   |
| c   | d   |
+-----+-----+

With such approach if 20,21 is repeated 3 times in b1,b2 and one time in b2,b3 you will get only 3, not 4. I don't know what you expect, but in case you want 4 then RJ's approach is probably the best, or at least you could use these queries as base for a script.

Right now it does not enter on my mind how to fix ...

2

As example:

-- table definition
CREATE TABLE `numbers` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `b1` tinyint(3) unsigned DEFAULT NULL,
  `b2` tinyint(3) unsigned DEFAULT NULL,
  `b3` tinyint(3) unsigned DEFAULT NULL,
  `b4` tinyint(3) unsigned DEFAULT NULL,
  `b5` tinyint(3) unsigned DEFAULT NULL,
  `b6` tinyint(3) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- sample data
INSERT INTO `numbers`
VALUES (1, 6, 8, 10, 26, 27, 36),
       (2, 2, 5, 10, 11, 32, 42),
       (3, 20, 21, 23, 24, 29, 38),
       (4, 3, 4, 17, 19, 33, 49),
       (5, 2, 17, 20, 23, 33, 41),
       (6, 1, 12, 13, 20, 31, 48),
       (7, 20, 21, 26, 41, 44, 47),
       (8, 3, 4, 43, 44, 46, 47),
       (9, 6, 7, 20, 23, 29, 46),
       (10, 1, 5, 13, 20, 46, 40),
       (11, 2, 5, 10, 18, 47, 40),
       (12, 20, 21, 23, 23, 37, 39),
       (13, 3, 4, 17, 25, 38, 41),
       (14, 5, 17, 20, 29, 30, 41),
       (15, 12, 14, 28, 31, 32, 43);

-- query
> SELECT * FROM numbers;
+------+------+------+------+------+------+------+
|   id |   b1 |   b2 |   b3 |   b4 |   b5 |   b6 |
|------+------+------+------+------+------+------|
|    1 |    6 |    8 |   10 |   26 |   27 |   36 |
|    2 |    2 |    5 |   10 |   11 |   32 |   42 |
|    3 |   20 |   21 |   23 |   24 |   29 |   38 |
|    4 |    3 |    4 |   17 |   19 |   33 |   49 |
|    5 ...
2

Hi,

that's a JSONP response, so in order to process this through PHP you need to remove the callback function that wraps the JSON data, for example:

callback({JSON DATA});

At this point you can remove it from the string:

<?php

$jsonp = 'callback({"name": "micheal"});';
$callb = 'callback'; // to remove

$s = substr($jsonp, mb_strlen($callb) + 1); // +1 to include the opening `(`
$s = substr($s, 0, -2); // -2 to remove `);`

print_r(json_decode($s, true));

Now, most JSON servers allows the client to define a callback in the requesting link:

http://url/page.php?callback=foo

So you receive:

foo({JSON DATA});

This allows you to write a more robust solution, as it's should not affect your script if they change their default callback function. See also if the server allows to get other formats, like simple JSON or XML.

2

Embedded contens like YouTube and Vimeo are served by them directly to the client, your page just sends the resource link, then the client opens a connection to the resource. You can see this through the developer console in Chrome: select the Network tab, hit reload for your page and see how the browser start to request data do different domains.

This means that your website bandwidth is not affected by these streams. It would if the video file was hosted and streamed by your server. Or if it was streamed as a proxy system from your web server to the clients connecting to your domain, an example:

It's the same with Google fonts or javascript libraries served by CDN systems.

Votes + Comments
Good explanation of how things work.
2

This brings me straight to 2000-2003 years, at that time I was working in a small lab assembling & repairing computers, the worst was when people wanted to recover EFS encrypted files from Windows XP drives. Windows XP policy was insane, they allowed to use EFS without a recovery agent, so people could backup the files, format the disk, reinstall Windows and ta-da when copying back they could not anymore access the files. You try to explain that using the same username would not lead to success and that an additional step, previous to the encryption, was needed but nothing. The only available solution that I knew was to try to recover the temporary copy created when processing the file, but at that time it was really difficult to find information and open source solutions, at least to try.

Lately, instead, I was able to recover data from a damaged CF card through PhotoRec: http://www.cgsecurity.org/wiki/PhotoRec
actually it recovered not only the shoot day but also jobs from the last year.