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:

0

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.

1

However internalImageUpload() writes only to the database.

Instead, it's in:

imagejpeg($im, $upload_path.$filename);

I overlooked that, and yes by defining a second parameter you would save the resource loaded into $im. However you cannot inject (as far as I know) the contents from $_POST['image'] to $im.

Try something like this:

<?php

$uid      = $_POST['uid'];
$token    = $_POST['token'];
$group_id = $_POST['group_id'];
$needle   = $_POST['image'];
$haystack = 'data:image/png;base64,';
$png_blob = substr($needle, mb_stripos($needle, $haystack) + mb_strlen($haystack));

$upload_path = '../' . UPLOAD_PATH;
$filename    = time() . $uid . '.jpg';

// save to image folder
file_put_contents($upload_path . $filename, base64_decode($png_blob));

// save to database
internalImageUpload($uid, $filename, $group_id, FALSE);

$imageID       = internalGetUploadImage($uid, $filename);
$fullImagePath = BASE_URL . UPLOAD_PATH . $filename;

echo "<img src='".$fullImagePath."'  class='webcam_preview' id='".$imageID[0]->id."'/>";

Just make sure the path is correct, that ../ in $upload_path makes me nervous :D as it would always be relative to the link in the frontend side and to the system path in the backend side.

0

The point is that you cannot use $_POST['image'] that way. See the definition of imagecreatefrompng():

resource imagecreatefrompng ( string $filename )

It means it expects a string to define the filename, not the contents. Something that would work would be:

$im = imagecreatefrompng('file.png');

And from here you create a resource that will be saved into file.png, you cannot import the value of $_POST['image'] into this resource. The value in $_POST['image'] is a base64 encoded string, which once decoded is a binary blob.

Hence, you don't need that code to save the input.

For more details, take this part:

$image = $_POST['image'];
$filter_image = str_replace("data:image/png;base64,", "", $image);
// input is in format 1,2,3...|1,2,3...|...
if($filter_image == $invalid)
{
    $im = "";
    echo "false";
}
else
{
    $im = imagecreatetruecolor(320, 240);
    foreach (explode("|", $_POST['image']) as $y => $csv) {
        foreach (explode(";", $csv) as $x => $color) {
            imagesetpixel($im, $x, $y, $color);
        }
    }
}

the comment says the expected format is: 1,2,3...|1,2,3...|... but it is not like this, it is something like:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKAQMAAAC3/F3+AAAABGdBTUEAAYagMeiWXwAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABlBMVEUA///+/v7eZjVAAAAAAWJLR0QB/wIt3gAAAAd0SU1FB+EIAQ0VMIC0C8gAAAALSURBVAjXY2DABwAAHgABboVHMgAAAABJRU5ErkJggg==

Which, decoded with my post.php script, produces a 10x10 cyan PNG image. Call it a.png.

The IF statement: if($filter_image == $invalid) is trying to compare an hardcoded blank blob to what is received by $_POST, to make sure it's not an empty snapshot. This can easily fail because the PNG specification allows to set a tIME value everytime the file is modified (or created), in practice some softwares as Gimp and in some cases ImageMagick, will add it and even ...