Jump to content

kicken

Gurus
  • Posts

    4,696
  • Joined

  • Last visited

  • Days Won

    178

Community Answers

  1. kicken's post in COALESCE not working in CodeIgniter was marked as the answer   
    You need your join on the second table to be a LEFT JOIN, but right now you're just making it a regular (INNER) JOIN.  An inner join excludes the row from the result if no match is found in the second table.  A left join will include the row, but with all the fields from the second table set to NULL.
    I don't know code igniter, but a simple search for code igniter left join suggests you want to write your join as:
    $this->db->join('crm_clients_users c','t.agent_id = c.id', 'left');  
  2. kicken's post in Add event to an element created with javascript was marked as the answer   
    You need to use a delegated event which involves
    Adding the event to some parent element that will always exist and Adding a selector argument when calling the .on method. $('#tableDiv').on('click', '#edit', function(){ alert('Hi!'); });  
  3. kicken's post in include the script only once was marked as the answer   
    Make it a named function, then pass the name to your event handlers.
    function loadData() { $.ajax({ type: 'POST', url: 'returnPDO.php', dataType: "json", data: { id: "1", rows: "7" }, success: function (data) { ...CODE.... } }); } $("#searchTbl").keypress(loadData); $('#go').on('click', loadData);  
  4. kicken's post in fill array with " " to avoid "undefined index" errors? was marked as the answer   
    Ah, but have you tried array_fill_keys?  See also, this post: Notice: Undefined index: driving me insane.
  5. kicken's post in Block direct access to files but use them was marked as the answer   
    Some places will try and do that by checking the referrer and denying access if it doesn't exist or match the right domain.  It's not going to stop anyone with even the slightest determination from downloading your file though.   IMO, it's not worth the effort to even try and do something like that.  
    Basic rule of the web is if the browser needs access to the file, then by necessity the user can also download a copy of that file.
  6. kicken's post in echo an array inside form confirmation email was marked as the answer   
    Use a foreach loop above the $body and create a new variable containing the order details as a string, then use that variable in $body.
    $orderDetails = ''; foreach ($orders as $order){ $orderDetails .= $order . '\n'; } It seems your orders are JSON encoded, so you'll probably want to json_decode them and format them nicely within that foreach loop.
  7. kicken's post in Javascript postMessage(msg) with Instance Of Class w/Methods was marked as the answer   
    postMessage serializes the data that you want to send.  That means that for the most part, only simple data is able to be sent, not complex stuff like functions or objects with methods.
     
    What you need to do is define MyClass on both pages and give it a way to be serialized to a string or simple object on the sending page and then unserialized back into the full object of the receiving page.
     
  8. kicken's post in results are sorted by directory name and not date was marked as the answer   
    Use usort rather than sort, then you can provide a comparison function and implement whatever logic you need to get the correct sorting.  The comparison function will be given two items from the array ($a and $b) and must return a number that indicates if $a is less than $b (-1), they are equal (0), or $a is greater than $b (1).
    If your files all began with the date in Y-m-d format you'd be able to simply compare them.  In m-d-Y format though you need to parse the date out of the name and then compare the date.
    usort($files, function($a, $b){ $a = basename($a); $b = basename($b); $aDate = DateTime::createFromFormat('!m-d-Y+', $a); $bDate = DateTime::createFromFormat('!m-d-Y+', $b); if ($aDate && $bDate){ $comparison = $aDate <=> $bDate; if ($comparison === 0){ return $a <=> $b; } else { return $comparison; } } else { return $a <=> $b; } }); Here, the function reduces each path given to it's basename, then attempts to parse a date in m-d-Y format from the beginning of the filename.  If it's able to successfully parse a date from both filenames then it compares the dates to get that -1, 0, or 1 value indicating their order.  If the result is 0, meaning the dates are equal, it compares the entire string and returns that order.  If it's unable to parse a date from either of the filenames then it just returns an order based on a string comparison.
     
  9. kicken's post in CORS and Sandboxing User Javascript, and Cookies was marked as the answer   
    I downloaded your code and added that attribute and it seemed to be working fine after that.
    You need to add it to both the CSP and the iframe's sandbox attribute.
  10. kicken's post in Errors that make no sense to me. What am I doing wrong? was marked as the answer   
    A query can have more than one parameter (eg, multiple WHERE conditions), as such PDO::execute() needs to be able to accept more than one value to bind to those parameters.  The way it does that is by taking in an array of values (even if it only needs one).  Pass an array to execute with $site as an element of that array to fix that problem.
    $stmt->execute([$site]); Your foreach error is due to the variable you provide ($table) not being an array (or other Traversable object).  You don't actually define $table anywhere in your code, it just magically appears.  If you want to loop over the results of your query, then you have a couple options.
    PDO Statements can be used directly in foreach, so just loop over $stmt.  If you do this, you do not call $stmt->fetchAll() first. Grab the results using $stmt->fetchAll() and loop over that variable ($fcid in your code).  
  11. kicken's post in Does a class's constructor run when I call a static method from outside the class? was marked as the answer   
    No.  Constructors only run when you're creating an instance of an object using new.
    Static methods are not associated with an instance so there's no need to run a constructor.  You also cannot use $this or any non-static class properties or methods
  12. kicken's post in Various Issues with backslashes and replacing strings was marked as the answer   
    This is just a matter of two separate levels of escape sequence processing that you need to wrap your mind around, which can be difficult at times.
    When you're setting a string in PHP first you have PHP's escape sequence processing.  PCRE then has it's own level of processing that is done on the value that was passed to the function.  For example, if you wanted to use \0 in a replacement literally rather than have it interpreted as a back reference you have to pass the string '\\0' as your replacement.    If you're defining value in your PHP source as a string then you need to escape those slashes again for PHP's sake so you have $replacement = "\\\\0"
    If you get the value from a file or database you don't have to worry about the PHP level of escaping, but do still need to account for the PCRE level so you need your file to contain \\0 not just \0.
    It's not clear to me exactly what output you're expecting in your code sample.  The addslashes call effectively mitigates PHP's escaping meaning $replacement is set to the literal value "<pre>\\\\</pre>".  preg_replace will then see that and process it's own escaping which means the value it's working with is effectively "<pre>\\</pre>".  That means your final replaced output would be "<div><pre>\\</pre></div>"
    If you have "<pre>\\\\</pre>" stored in your database and are pulling that value from there then you should get the same result, just don't run it through addslashes() as you don't have to deal with the PHP level of escaping things.
     
  13. kicken's post in Locking a file for passing data was marked as the answer   
    filesize

    Your $filesize is only going to be correct the first time the function is called. After that you'll get the cached value back. Either clear the cache or read the file in a way that doesn't depend on obtaining the file size.
  14. kicken's post in case when in where clause? was marked as the answer   
    No, but by binding your parameter multiple times you can add a second condition that is always true.
     

    WHERE ci.id < ? AND (? IS NULL OR ci.cat_id = ?) $next24item->bind_param('iii', $lastItemID, $category_id, $category_id); If $category_id is null then the first condition ? IS NULL will always be true and cause the second condition to be ignored. If $category_id is not null then ? IS NULL will always be false and the second condition will be evaluated.
  15. kicken's post in Invalid numeric literal was marked as the answer   
    Numbers that begin with a 0 are octal based numbers. I'd guess you get the error due to running a 32-bit version of PHP, in which case 070000000000 is larger than PHP can handle as an integer.
     
    On a related note, don't try and treat phone numbers as actual numbers, treat them a strings. Just because some value only consists of digits doesn't mean it needs to be treated as an integer type.
  16. kicken's post in linux command sed was marked as the answer   
    The test.txt, file is not supposed to change, that's the backup in case you messed up. The original test.txt is the one that gets changed.
     

    kicken@web1:~$ echo 'Visit www.example.com today!' > test.txt kicken@web1:~$ sed -i, s,www,the,g test.txt kicken@web1:~$ cat test.txt Visit the.example.com today! kicken@web1:~$ cat test.txt, Visit www.example.com today! kicken@web1:~$
  17. kicken's post in Array[] or array() or wha? was marked as the answer   
    If you're just after the numerical value of the first byte, then you can simply do:

    $byte = ord($buf[0]); echo $byte; Strings in PHP can be treated like an array and you can access the individual bytes directly by using the appropriate index. ord will give you the numeric value of a byte. There's no need for unpack at all in this code. If you want all the bytes you can do a for loop over the length of the string and run ord on each byte individually.
  18. kicken's post in "anonymous" array? was marked as the answer   
    array('A' => 5, 'B' => 4, 'C' => 3, 'D' => 2, 'E' => 1)[$overall]That works fine for PHP >=5.5. 
    Adding || 0 at the end would give you a boolean result, which I don't think is what you are intending. I'm guessing you want the javascript behavior where $pt_overall would be assigned either the value of the array or 0 if undefined. || does not work that way for PHP, you always get a boolean true or false instead.
     
    If you want to lookup a value or default to 0, then you'll need to use as ternary statement, and you need to use isset() to avoid undefined index errors. You'll want to just assign your array to a variable in that case.

    $values = ['A' => 5, 'B' => 4, 'C' => 3, 'D' => 2, 'E' => 1]; $pt_overall = isset($values[$overall])?$values[$overall]:0;
  19. kicken's post in Making Slim generate 404 response in application was marked as the answer   
    Use an exception and the error handler to return an appropriate error page.
     

    $c['errorHandler'] = function($c){ return function ($request, $response, $exception) use ($c){ if ($exception instanceof NotFoundException){ return $c['notFoundHandler']($request, $response); } else { return $c['response']->withStatus(500) ->withHeader('Content-type: text/html') ->write('Generic error') ; } }; }; class SourceFactory { public function getByType($type, $subtype){ throw new NotFoundException(); } }  
    class NotFoundException extends Exception {} Whenever you want to trigger a not found error you'd just throw the exception. That will stop the current code path and jump to the error handler. The error handler will detect that it's a not found exception and call the not found handler to generate the response. 
    You could do the same with other http error conditions if you wanted, like authentication required, forbidden, etc. Symfony does something like this in their framework. They define a HTTPExceptionInterface adding methods to get the status code and extra headers. Then they have various implementations like NotFoundHttpException.
  20. kicken's post in Send mail Raspberry Pi (sSMTP) was marked as the answer   
    Your reverse aliases file does not contain an entry for the www-data user which is what your script is running as. Try adding that and see if it works.
  21. kicken's post in How to get content into a ReactPHP server? was marked as the answer   
    Your server and it's clients should communicate with some standard data layout. In my RLGL example for example every JSON structure contained a message field that indicated what type of data structure was being sent.
     
    You can use that field to then decide what to do with any data you receive. One of those actions could be something to forward data to a given client which is what your index.php script would use.
     

    $client->on('data', function($data) use ($client){ switch ($data['message']){ case 'register': $this->addConnection($client, $data['guid']); break; case 'forward': $forwardClient = $this->findConnectionByGuid($data['guid']); $forwardClient->send($data['data']); //Somehow determine success/failure and send the result //$client->send(['message'=> 'forward-result', 'success' => true]); break; default: $guid = $this->getConnectionID(); $this->app->process($data, $guid, $client); break; } }); Your index.php script can just use the react framework stuff to send your data and receive a response. Something like this:
    function sendToClient($guid, $forwardData){ $success = false; $loop = new \React\EventLoop\StreamSelectLoop(); $socket = new \React\SocketClient\TimeoutConnector(new \React\SocketClient\TcpConnector($loop), 15, $loop); $socket->create($server, $port)->then(function($stream){ $client = new \Kicken\RLGL\JSONStream($stream); $stream->on('data', function($data) use (&$success, $loop, $stream, $guid, $forwardData){ if ($data['message'] == 'forward-result'){ $success = $data['success']; $stream->close(); $loop->stop(); } }); $client->send([ 'message' => 'forward' , 'guid' => $guid , 'data' => $forwardData ]); }); //Generic timeout so this function doesn't block forever. $loop->addTimer(30, function() use ($loop){ $loop->stop(); }); $loop->run(); return $success; }
  22. kicken's post in Get SplObjectStorage by key was marked as the answer   
    You could still make a guid map if you wanted to after you know what the GUID is.

    private function addConnection($client, $guid) { $this->clientList[$client]['guid']=$guid; $this->guidMap[$guid] = $client; } private function findConnectionByGuid($guid) { return isset($this->guidMap[$guid])?$this->guidMap[$guid]:null; } If there are not a lot of clients I'd probably just stick with the loop, but use a foreach to make it simpler.

    private function findConnectionByGuid($guid) { foreach ($this->socketClients as $client){ if ($this->socketClients[$client]['guid'] == $guid){ return $client; } } return null; } That way things are kept simple with only one member variable tracking the list of clients.
  23. kicken's post in Can I use SSL over port 25? was marked as the answer   
    Unless you use port 465 (SMTPS) then you need to determine whether your application supports STARTTLS or not as that's what is needed to enable encryption on the other ports.
     
    In general it's up to your SMTP client to request that encryption be enabled by issuing a STARTTLS command. Only SMTPS provided encryption from the get-go and as mentioned that has been deprecated (though still supported in places).
     
    Regarding your initial concerns for privacy, keep in mind that even if you can get SSL working for delivering email to the GMAIL servers it may be transmitted to it's final destination over a plain-text channel. If the final address is somewhere other than google then the message will need to be forwarded and not all servers support encrypted server-to-server communication so the message would then be sent in plain text. Google tracks some statistics about this if you're interested.
  24. kicken's post in HTTP server with two hosts and same port was marked as the answer   
    Here's that example. To try and simulate your bi-direction traffic plus having a timed job I coded up a little Red-light/Green-light system. The server accepts clients and sends them random red or green light messages. When a client sees a green-light it fakes moving and stops when it gets a red-light. Periodically it also sends the server how far it's moved and it's name. The server periodically lists the players and their distance. There is pretty much no error handling (such as for disconnects) in the code, I'll leave that as an exercise to the reader.
     
    JSONStream.php - Sends and receives json documents via a socket stream.

    <?php namespace Kicken\RLGL; use Evenement\EventEmitterInterface; use Evenement\EventEmitterTrait; use React\Stream\DuplexStreamInterface; class JSONStream implements EventEmitterInterface { use EventEmitterTrait; private $socket; private $buffer; public function __construct(DuplexStreamInterface $socket){ $this->socket = $socket; $this->buffer = ''; $this->socket->on('data', function($data){ $this->buffer .= $data; $this->parseBuffer(); }); } public function send($structure){ $json = json_encode($structure); $this->socket->write($json."\r\n"); } private function parseBuffer(){ $eol = strpos($this->buffer, "\r\n"); while ($eol !== false){ $json = substr($this->buffer, 0, $eol); $this->buffer = substr($this->buffer, $eol + 2); $data = json_decode($json, true); if (json_last_error() == JSON_ERROR_NONE){ $this->emit('data', [$data]); } $eol = strpos($this->buffer, "\r\n"); } } } server.php - Short script to act as the server. Listens on port 1337 for connections and listens for info messages from each client. Sends light messages periodically. 

    <?php require 'vendor/autoload.php'; require 'JSONStream.php'; $port = isset($argv[1])?$argv[1]:1337; $clientList = new SplObjectStorage(); $loop = new \React\EventLoop\StreamSelectLoop(); $socket = new React\Socket\Server($loop); $socket->on('connection', function (\React\Socket\ConnectionInterface $client) use (&$clientList){ $client = new \Kicken\RLGL\JSONStream($client); $clientList->attach($client, []); $client->on('data', function($data) use (&$clientList, $client){ if ($data['message'] == 'info'){ $clientList[$client] = $data['info']; } }); echo "New connection accepted.\r\n"; }); $loop->addPeriodicTimer(5, function () use ($clientList){ $color = mt_rand(1,2) == 1?'red':'green'; echo "Sending {$color} light.\r\n"; /** @var \Kicken\RLGL\JSONStream $client */ foreach ($clientList as $client){ $client->send([ 'message' => 'light' , 'color' => $color ]); } }); $loop->addPeriodicTimer(60, function() use ($clientList){ echo "Current results:\r\n"; foreach ($clientList as $client){ $info = $clientList[$client]; if (!empty($info)){ echo "{$info['name']} has travelled {$info['distance']} feet.\r\n"; } } }); $socket->listen($port, '0.0.0.0'); $loop->run(); client.php - Connects to the server and listens for light messages. Periodically tells the server how far it has travelled. 

    <?php require 'vendor/autoload.php'; require 'JSONStream.php'; $server = isset($argv[1])?$argv[1]:'127.0.0.1'; $port = isset($argv[2])?$argv[2]:1337; /** @var \Kicken\RLGL\JSONStream $client */ $client = null; $clientInfo = [ 'name' => getRandomName() , 'speed' => getRandomSpeed() , 'traveled' => 0 , 'moving' => false , 'movingStartTime' => null ]; $loop = new \React\EventLoop\StreamSelectLoop(); $socket = new \React\SocketClient\TcpConnector($loop); $socket->create($server, $port)->then(function ($stream) use (&$client, &$clientInfo){ $client = new \Kicken\RLGL\JSONStream($stream); sendClientInfo(); $client->on('data', function ($data) use (&$clientInfo){ if ($data['message'] == 'light'){ if ($data['color'] == 'green' && !$clientInfo['moving']){ $clientInfo['moving'] = true; $clientInfo['movingStartTime'] = time(); echo "Received green light!\r\n"; } else if ($data['color'] == 'red' && $clientInfo['moving']){ $movingTime = time() - $clientInfo['movingStartTime']; $distance = $movingTime * $clientInfo['speed']; $clientInfo['traveled'] += $distance; $clientInfo['moving'] = false; $clientInfo['movingStartTime'] = null; echo "Received Red light! Total distance = {$distance} feet.\r\n"; } } }); }); $loop->addPeriodicTimer(15, 'sendClientInfo'); $loop->run(); function sendClientInfo(){ global $client, $clientInfo; $infoToSend = [ 'name' => $clientInfo['name'] , 'distance' => $clientInfo['traveled'] ]; echo "Updating server with data.\r\n"; $client->send(['message' => 'info', 'info' => $infoToSend]); } function getRandomName(){ static $names = ['Edmundo', 'Roxane', 'Evelynn', 'Isaias', 'Buena', 'Evan', 'Katharina', 'Darnell', 'Sharyl', 'Malka', 'Sharla', 'Delena', 'Leah', 'Marnie', 'Tammi', 'Joanna', 'Marva', 'Karyn', 'Kristal', 'Jayson']; shuffle($names); return $names[0]; } function getRandomSpeed(){ return mt_rand(1, 100) / 100; }
  25. kicken's post in Is this SVN set up properly? I don't think I'm in Trunk. was marked as the answer   
    Use svn move to move the files. Eg:

    svn move addFile.php addUser.php alertmanagement.php ... trunk/ After the commit just rename your working copy folder to move it out of the way so you can check out a new copy.
    daniel@daniel:~/NetBeansProjects$ mv development.xxxx.com development.xxxx.com-old daniel@daniel:~/NetBeansProjects$ svn co svn://development.xxxx.com/trunk development.xxxx.com
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.