-
Posts
4,705 -
Joined
-
Last visited
-
Days Won
179
Everything posted by kicken
-
You need to replace the bytes C2A0. Mysql doesn't understand html entities so using to represent a non-breaking space won't work. Try REPLACE(price, X'C2A0', '')
-
It's the same as doing $values = array('A' => 5, 'B' => 4, 'C' => 3, 'D' => 2, 'E' => 1); $values[$overall]; You define an array then immediately index into it. It can be useful if you need to map one value to another but don't need the map in more than one place. function getWeekdayName($day){ return ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'][$day]; }
-
Note that you should just use an ever-increasing counter variable for your id rather than doing a count() on your callbacks array. If you're going to be removing the callbacks when done and processing requests/responses asynchronously then you may end up doubling up on the ID numbers. For example, if your code ended up executing something like this: $callbacks = []; sendRequest('something'); //generate and send id=1 sendRequest('something else'); //generate and send id=2; completeRequest('something'); //remove id=1; sendRequest('yet another thing'); //generate and send id=2; completeRequest('something else'); //calls the 'yet another thing' callback instead.
-
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;
-
Rather than try to dynamically create/remove cron jobs, just create a single job that runs on a specific interval and checks a database for work. Store your $auction_end time and whatever other data is need into your database so that when the job runs it can do what it needs to do.
-
When should PDO::closeCursor() be used?
kicken replied to NotionCommotion's topic in PHP Coding Help
That does not keep the statement open for the entire duration of the script, only for the duration of the function. Each time the function ends $stmt would go out of scope and the resources would be cleaned up automatically. Keeping a statement open indefinitely would require code that is something like this: <?php $db = new PDO(...); $stmt = $db->query('SELECT * FROM config'); $config = $stmt->fetch(); //Only fetch one row //... $loop->run(); $stmt is globally scope so it will not deconstruct until the end of the script, and fetching only one row of a possibly multi-row result would cause it to remain open. I think the only time I've needed to explicitly call closeCursor was back in 2010 to work around some issues in the MSSQL PDO driver at the time. I don't remember the exact details of the problem, something with stored procedures I think, but since switching to the newer SQLSRV driver I've not needed it. -
I use Twilio, they have been good. Some providers have an email to sms gateway you can use, but they are all different last I checked. If you want to be able to send SMS to anyone you'll want to go with a service. If you're just looking to send them to yourself or a few people you could try the email to sms systems. You could get your own hardware capable of sending messages and using that, such as trying to interface with your cell phone. That's not really cutting out the middle man though, rather just making your cell company the new middle man.
-
When are semicolons required after curly brackets?
kicken replied to NotionCommotion's topic in PHP Coding Help
They are required after single statements. Braces surrounding function bodies or conditions etc are block statements and thus do not need a terminating semi-colon. They are required after assigning a closure function because that is a single statement (the assignment). -
First, you'll have to learn enough of the IRC client protocol to connect to the server and make your DCC request. You say you have this working already, is so that's a good start. If you haven't already you should look through the RFC even if what you have works, just to make sure you're not missing anything important or doing anything incorrectly. Next you'll need to learn the CTCP Protocol and read about the DCC Extension to it to request the file. You'll have to open a listening socket on which you can receive the file then transmit it's details to the sender. Once you have all that working you'll just have to figure out the best way to tie it all together in the way you need. If the files you're transferring are small then you can probably do the whole transaction in one script. If the larger you may need to separate out the file transfer process so the browser doesn't hang up waiting for the server. I implemented DCC Transfers in an IRC bot I wrote many years ago. Most of the file transfer code has been lost over time but some of the basics is still there. You can look at it to get an idea of the process but don't try and use it as-is, it's terribly outdated and incomplete.
-
Basically you just have a fundamental mis-understanding of what the current directory means I think. Every process has a concept known as it's current working directory (see getcwd) which is what relative paths are based around, this is a fundamental concept of processes and not something PHP specific. What exactly this is set to cannot be relied upon because it depends upon how the process was launched. In the context of a web server running PHP scripts the current directory is generally set to the directory containing the initial script. In CLI mode it is whatever directory you were in when you ran the script. In other contexts it may be something entirely different. Your script or some library you're using could change it at any time to whatever value it wants. Generally what I do is have one common configuration file, say common.inc.php that is included either with a relative path or by relying on the configured include_path. Within this file I define useful path constants using __DIR__ as the base which is defined by PHP to be the directory the currently executing file is located in. Those constants can then be used throughout the rest of the code to get paths to various files or directories.
-
Making Slim generate 404 response in application
kicken replied to NotionCommotion's topic in PHP Coding Help
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. -
You can feed a .sql file as standard input to the mysql command line tool and it will execute all the statements. mysql -u username -p < Backup.sql
-
I prefer the "Interface" suffix these days. I did the "I" prefix for a while when I started doing more OO stuff. Using a suffix means that the files are still sorted alphabetically and are not all clumped up in the I's section. That makes it easier to find them in a directory listing. Having a suffix or prefix also makes it easier when see exactly which files are classes rather than interfaces. Letting your IDE break everything down by type is great but it doesn't work so well when you're not using the IDE, such as browsing code in a GitHub repository to find something. Having a suffix or prefix also means you can have an implementation who's name matches the interface if desired. class Firewall implements FirewallInterface { }
-
You might find this thread over on DevShed a good read. Why Interfaces!? It covers why one might use interfaces and abstract classes.
-
There's nothing special that needs to be done to store it or retrieve it from mysql, just use your typical queries with bound parameters. However before you display it you will want to run it through some kind of filtering to guard against scripting attacks. HTMLPurifier is one such library you could use to do the filtering. Using json_encode for your API will be fine.
-
Javascript: Unexpected token punc «(», expected punc «:» ?
kicken replied to justravis's topic in Javascript Help
What's above that code? I'm going to guess you are running into issues resulting from Automatic Semi-colon insertion. -
Kicken's guide to digging through code. The starting point: <?php $loop = Factory::create(); $socket = new React\Socket\Server($loop); $socket->on('connection', function (\React\Socket\ConnectionInterface $stream){ $stream->on('data', function($rsp) {/*bla bla bla*/}); $stream->on('close', function($conn) {/*bla bla bla*/}); $stream->on('error', function($error, $stream) { echo "Stream Error: $error"; $stream->close(); }); }); $socket->listen('0.0.0.0',1337); $loop->run(); ?> What we want to find out:What is $stream exactly? What events can it emit? What parameters do those events provide? What we know:$socket is an instance of \React\Socket\Server $socket emits a connection event that provides $stream Lets go digging! First into \React\Socket\Server to find the connection event <?php class Server extends EventEmitter implements ServerInterface { //... public function handleConnection($socket) { stream_set_blocking($socket, 0); $client = $this->createConnection($socket); $this->emit('connection', array($client)); } //... public function createConnection($socket) { return new Connection($socket, $this->loop); } //... } ?> We see here that the connection event provides one argument which is an instance of \React\Socket\Connection. Now lets look at \React\Socket\Connection to see what kind of events it can emit. <?php class Connection extends Stream implements ConnectionInterface { //... } ?> The Connection class itself doesn't appear to emit anything. However, Connection is an extension of \React\Stream\Stream so lets go look there next. <?php class Stream extends EventEmitter implements DuplexStreamInterface { //... public function __construct($stream, LoopInterface $loop) { //... $that = $this; $this->buffer->on('error', function ($error) use ($that) { $that->emit('error', array($error, $that)); $that->close(); }); $this->buffer->on('drain', function () use ($that) { $that->emit('drain', array($that)); }); //... } //... public function close() { //... $this->emit('end', array($this)); $this->emit('close', array($this)); //... } //... public function handleData($stream) { //... if ($error !== null) { $this->emit('error', array(new \RuntimeException('Unable to read from stream: ' . $error->getMessage(), 0, $error), $this)); $this->close(); return; } if ($data !== '') { $this->emit('data', array($data, $this)); } //... } } ?> So the Stream class seems to do most the work. It will emit error, drain, end, close, and data events. error provides two arguments. An exception describing the error and the stream instance. drain, end and close provide one argument, the stream instance. data provides two arguments. The data that was received and the stream instance. Now you could keep digging if you want but that covers what we set out to find initially.
-
# Function accepts one argument array(1) { # Argument number 1 is ... [0] => class React\Socket\Connection#43 ( { #... } #if there were more arguments they would also be listed. } The code is just a quick way to get the number and type of arguments being passed into a function. When the arguments are objects you get a bit of a mess to dig through unfortunately.
-
Generally that is information that would be documented. Ideally there would be some documentation detailing each event name that could be triggered, what arguments it will receive and what return value it expects (if any). Since they are lacking in the documentation area you just have to go digging around in the code to find answers to a lot of these such questions. One alternative in this case if you don't want to dig into the code is to have PHP tell you what the arguments are using func_get_args. $stream->on('error', function($error, $stream) { var_dump(func_get_args()); });
-
Put it into it's own separate class. class AnimalFactory { public function create($id){ //do stuff... return $animal; } }
-
How to get content into a ReactPHP server?
kicken replied to NotionCommotion's topic in PHP Coding Help
Yea. You'll need to add &$success to the $socket->create level use statement also. -
A factory is responsible for creating an instance of a given interface / abstract class based on some sort of criteria. For example when you asked about using React\EventLoop\Factory::create, the reason for using it is so that it can return the best event loop implementation available. It inspects the environment for various extensions before returning a generic option. In your animal case the factory would take some sort of data to identify what type of animal needs to be constructed and then do so accordingly. That might be an ID which is then looked up in the database or it might be an array with a specific member key. It might also be two separate arguments, one for the type and another for the context. The main purpose is to offload the construction to a central place, similar to how dependency injection makes the container responsible for construction of objects. Your factory might start out as simple as something like: public function getById($id){ $data = $this->lookupIdInDb($id); $class = $data['class']; return new $class($data); } but in the future end up more complex as your requirements change.
-
Use the fourth parameter to the mail() function to define custom headers and set the From address. See the examples in the manual. In general I always recommend using a library for mail such as Swiftmailer. Using mail() directly is cumbersome and error prone.
-
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.
-
zend_mm_heap corrupted-Allowed memory size exhausted
kicken replied to NotionCommotion's topic in PHP Coding Help
You need to install the php development package if you are going to try compiling xdebug. You could also check and see if a pre-compiled version already exists in your package manager.