-
Posts
4,704 -
Joined
-
Last visited
-
Days Won
179
Everything posted by kicken
-
Cannot redeclare class - Location where it was declared unclear ..
kicken replied to rhand's topic in PHP Coding Help
The usual cause for this is that you've included the file defining the class twice. Go through your code to make sure you are not accidentally doing that. Use the include_once/require_once functions rather than include/require to prevent double inclusion. -
Why is FireFox hitting my server twice?
kicken replied to NotionCommotion's topic in PHP Coding Help
You probably have an empty src attribute for an image tag. <img src="" ...> That is the typical cause of something like that. -
When I added that to my sig, 1 BTC was worth like $6. By today's rates that would be like 0.026 I guess.
-
Some might. Whether it's worth your time to code around that is up to you. Ajax is Javascript. There's no versus there. If Javascript is unavailable then neither is ajax.
-
! is the operator for not. So !isset() reads as "not isset" or "is not set". That code sets $content_width to 625 if it has not already been defined.
-
You'd test it by just trying to run two instances of a script concurrently. For example: <?php $filename = isset($argv[1])?$argv[1]:'lockfile.txt'; $fp = fopen($filename, 'r+'); if (!$fp){ die('Could not open file. Create it first.'); } echo 'Attempting to acquire lock'.PHP_EOL; if (flock($fp, LOCK_EX)){ echo 'Lock has been acquired'.PHP_EOL; $value = trim(fgets($fp)); rewind($fp); fwrite($fp, $value+1); echo 'Read value '.$value.'; Incremented value to '.($value+1).' and wrote it back'.PHP_EOL; echo 'Pausing for a while for testing'.PHP_EOL; sleep(10); fflush($fp); flock($fp, LOCK_UN); echo 'Lock has now been released'.PHP_EOL; } fclose($fp); echo 'Finished'.PHP_EOL; Open a couple of terminal windows and run separate copies of the script. One of them will get the lock and then pause, the other will wait until the first completes.
-
The basic gist of locking goes like this: $bse = fopen($filename, 'r+'); if (flock($bse, LOCK_EX)){ $value = fgets($bse); //Read the value rewind($bse); //Reset file pointer fwrite($bse, $value+1); //Write back new value flock($bse, LOCK_UN); //Release lock } fclose($bse); flock will wait until it either successfully obtains a lock, or something interrupts it and prevents it from doing so. If it is successful, it returns true which indicates you can go ahead and do what you want with the file. If it fails, it will return false which means you should not do anything with the file and just close it.
-
Checking with a select query first is the wrong way to handle this in the first place. What you should be doing is setting a UNIQUE constraint on your database, then check if the insert failed due to a violation of that constraint. A quick example would be: <?php $db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password'); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); /* //Uncomment to create the table $sql = ' create table unique_example ( id int auto_increment primary key not null , username varchar(100) unique not null ) '; $db->exec($sql); */ $username = 'example'; try { $stmt = $db->prepare('INSERT INTO unique_example (username) VALUES (?)'); $stmt->execute([$username]); echo 'Data inserted successfully'; } catch (PDOException $ex){ if ($ex->getCode() == 23000){ //Check if it's a duplciate key violation. echo 'Username must be unique'; } else { throw $ex; //Rethrow other errors } } Notice when the table is created (in the commented code) that I specify UNIQUE in the column attributes. This tells Mysql to create a unique index on that column. Whenever new data is inserted or existing data changed mysql will verify that the new value does not already exist. If the value does already exist it will reject the query with an error. The problem with your select-then-insert approach is that it is possible that someone else inserts the duplicate name after your select but before your insert. Eg: Client A: SELECT 1 FROM table WHERE username='blah'; Client B: SELECT 1 FROM table WHERE username='blah'; Client A: INSERT INTO table (username) VALUES ('blah'); => Ok, data added Client B: INSERT INTO table (username) VALUES ('blah'); => Ok, data added Now you have two rows with the same data despite your check.
-
I'd suggest that rather than try to highlight everywhere that it could be placed, just show a highlight over the areas that would be used if it were placed where they are currently hovering (or no highlight if invalid placement). There's really no reason to try and highlight every possible placement area. The user can see where the empty slots are and how many are needed by the size of the graphic. Your highlighting isn't even accurate as if you have more than the necessary space in a single area, you can place it anywhere in that area so you'd have to just highlight the entire space which ultimately means you're highlighting nearly every open slot. The way you'd want to handle the drag and drop is that on every drag (and final drop) you: - Determine which slot the cursor/image top-left is over - Using that as your placement slot, determine if there is enough space in that area for the item - If so, draw the placeholder. If not, indicate impossibility (eg, set cursor: no-drop and/or a red highlight). For the drop event rather than draw the placeholder you'd move the item. If your test determines the area to be invalid, cancel and leave the item in it's original location.
-
How do you detect the outside scope of a block?
kicken replied to Monkuar's topic in PHP Coding Help
The function doesn't look at the width/height of existing items, it just checks if something has been assigned to that slot. Either you'd have to change the function to take into account the width/height of items already in the grid (ie, store the entire item info, not just the id) or you'd have to fill every space that an item takes up with it's ID number (ie $grid[1 - 6][2 - 7] = 5). -
Apache writes the access log entry after the request has finished, so something in the code delaying the request would also delay the log entry. It sounds like this is what you're seeing? There could be some kind of networking issue such as apache or the code trying to connect to an external resource and failing. If the delay is fairly constant (for example always about 60 seconds) then I'd suspect this kind of problem. 60 seconds is PHP's default socket timeout, and is a relatively common default timeout for other things.
-
If you want to know why it does what it does when using !=, see the manual on comparisons, specifically: Basically if both strings consist of something that is_numeric says is a number, PHP will convert it to a number then compare them. So '00' become (int)0 and '0' becomes (int)0. 0 != 0 is false.
-
[Suggestion] Add Notification for topic replies
kicken replied to Monkuar's topic in PHPFreaks.com Website Feedback
Go to your settings then Notification Options. Check the box for 'Auto follow topics I reply to' then set your frequency. That should do it I think. -
Just because something is running 24/7 doesn't mean it is actually doing something 24/7. A properly written server would use stream_select in it's main loop so that it only does something when it needs to do something. What that function does is basically tell the operating system "Hey, let me know if anything interesting happens with these sockets. Until then, you can ignore me and do whatever." So the operating put your script into what is essentially suspended state and watch those those sockets. During this time your script is not actually running, thus consumes no CPU time. Once the operating system sees some activity on the sockets it will resume your script and let it do what it needs to do. As for computing what kind of memory you might need, the best way obviously is to do some profiling and stress testing to see what kinds of memory the script actually uses. You can however estimate it. There are a few different types of memory consumption that you'll want to look at: How much memory PHP consumes just to run a script. Last time I checked this was about 30MB, but this will vary greatly depending on how PHP was compiled, so check for yourself. How much memory your script consumes in general. For things like the global configuration, the server information, etc. Memory that is used regardless of any clients being connected How much memory each connection will required, both when activly doing something and when just passivly listening. The first two values you can get just by running your server script then checking how much memory is being used before anything connects to it. The last value you can estimate by just looking at what kind of information you store for each connected user. For example, every user will have at least their socket connection, and possibly some additional details like an identifier, socket buffer, etc. Lets assume each client connection contains the following for the entire duration of the script: The socket resource A 60-character identifier token Character stats (hp, str, armor, etc) A 1KiB recieving buffer A 1KiB sending buffer Estimate the memory usage for each of those items. To make things easy, use a precision of 0.5KiB so anything that would be less than 0.5KiB is counted as 0.5KiB instead. By over-estimating you can balance out PHP's overhead. That would give estimates of:0.5KiB 0.5KiB 0.5KiB 1.0KiB 1.0KiB Total: 3.5KiB constant usage per connection. Figuring the usage when the client is activly doing something would depend on what is being done. What you'll want to do is just look at each possible operation and try and come up with a memory usage profile for each one. Then you could either average them out, use the maximum, or just whichever would be the most common. How you choose to do that is pretty much up to you. I'm just going to 1MB typical usage for activity for example purposes. So if you had for example 128MB of memory to work with, you could in theory support: 131072KiB / 3.5KiB = 37,449 connections that are doing nothing but sitting there. 131072KiB / 1027.5 = 127 connections all doing something at the same time So how much you could realistically support would fall somewhere in that range. That said, just because you theoretically have enough memory to support 37 thousand clients doesn't mean you actually can. You also need to factor in various OS limitions (ie # of allowed file descriptors), processing power (need to be able to process the requests fast enough), other running programs (web server, database, etc). All these additional factors are why it's generally best to just profile and stress test. With some work you can estimate a ball-park of what you might need resource wise though.
-
How does one get their website listed on Google in this manner?
kicken replied to helloworld001's topic in Other
They are called Sitelinks. Google will analyze your site and show them if it decides they are helpful. The only thing you can do to help get them enabled is ensure that you have well-designed sematic markup and link text in order to help google's algorithm determine whether they are appropriate or not. -
Relatively secure server to server communication
kicken replied to NotionCommotion's topic in PHP Coding Help
Yes, make sure you setup HTTPS between the servers. That is your main protection. If you want to just use a self-generated certificate that is fine, you'll just need to tell curl to accept certificates from your custom CA. You can do this with the CURLOPT_CAINFO option. You also want to ensure that CURLOPT_SSL_VERIFYPEER is enabled. $ch = curl_init($url); curl_setopt($ch, CURLOPT_CAINFO, '/path/to/caroot.pem'); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); //... Once HTTPS is up and running, you could just use something as simple as HTTP Basic Auth rather than have to code specific verification procedures into your application. -
Move the right-floated div so it is above the text in the source of the page.
-
Recommend turning errors into exceptions?
kicken replied to NotionCommotion's topic in PHP Coding Help
I wouldn't do it permanently for the whole script. If you want to change it for the duration of a particular function or something maybe it'd be ok. I can't think of any reason why you couldn't just fix the code to properly check everything with isset() though and prevent the error in the first place. It can be an annoying amount of extra typing sometimes but such is life. -
Basically in order to do what you want, you'd have to proxy everything a user visits through your server which isn't really possible/practical. As you've discovered through the example with google, sites will prevent you from framing them either with this header or by using javascript to break your frame. Aside from that the same origin policy would prevent you from interacting with the page which could be a problem depending on what kind of features you want to do. That leaves two basic solutions: 1) Write your own browser. You can find libraries that handle all the rendering and what not, you'd just have to create your shell UI and tie things together. Then you'd have to get users to download, install, and use your custom browser which you're probably not going to be able to do. 2) Write extensions for existing browsers. You'd write extensions for Firefox, Chrome and IE that will modify their UI with your functions. Then users would just need to install your extension on their browser of choice. Much more likely to happen and much less work on your end. There are already extensions for the browsers that let you do things like attach notes to pages. You could find one of those and use it as a base for your own extension. Then you'd create an API on your site that your extension can use to communicate with your server to save/load users details.
-
What mode should MySQL be running in when used with PHP?
kicken replied to NotionCommotion's topic in PHP Coding Help
They are not really modes. The options in the configuration file are divide into various groups. Each of mysql's programs has a set of groups it will look at for options. mysqld is the actual executable for the mysql server. [mysqld] is it's unique group. mysqld_safe is a wrapper script that adds a little bit of extra safety by restarting the server if it crashes and some error logging. It will look at the [mysqld_safe] group for it's options. mysql refers to the mysql client application, not the server. It will look for options in the [mysql] group. If you installed mysql using your system's package manager, it's probably already setup the service to start using whatever method is appropriate. I wouldn't worry about ensuring it uses mysqld_safe vs mysqld. All you need to look into is configuring mysql's options (ie memory limits, connections, etc.) so that it runs well for your environment -
Is mb_check_encoding really required for all inputs?
kicken replied to NotionCommotion's topic in PHP Coding Help
That would be one quick and easy thing you could do, but not necessarily the most flexible. Similar to the old register globals hack, just loop over the input arrays ($_COOKIE and $_FILES also) and check each value. If any value is an invalid UTF8 sequence you could just reject the request. The default_charset parameter is used in a few functions (such as htmlentities). Overall PHP is basically character set unaware and deals in plain ascii. Yes. You can set the encoding for the entire table or on a per-column basis. eg: create table blah ( name varchar(255) ) DEFAULT CHARACTER SET=utf8 or create table blah ( name varchar(255) CHARACTER SET utf8 ) You should set the character set in the Content-type header. This applies for both your HTML pages and the JSON data. header('Content-type: text/html; charset=utf-8'); or header('Content-type: application/json; charset=utf-8'); -
Legal implications of selling cellular data
kicken replied to moose-en-a-gant's topic in Miscellaneous
This is specifically for Verizion, but I'm sure all other companies have something very similar: Customer Agreement So while (probably) not strictly illegal, they would most likely terminate your service if they discovered you doing this, which if you're trying to make a business out of it they probably will. There may be other legal issues though resulting from your selling services, such as taxes, regulatory fees, whatever. As usually, whenever you want legal advice, ask a lawyer, not the internet. -
You have to use Javascript to do the actual dragging. You do so by using it to adjust the items CSS top and left properties as you move the mouse around the screen. The simplest thing to do would be to use a library that handles it for you such as jQuery UI's Draggable widget.
-
set variable and compare in one command
kicken replied to NotionCommotion's topic in PHP Coding Help
Actually it has lower precedence.. Since the = comes after the > in the example, it works without the extra parenthesis. This on the other hand: if($f1_x=f1($x) > f2($y)){ would be interpreted as $f1_x = (f1($x) > f2($y)) and $f1_x would be a boolean true/false not the return value of the function. -
Why am I being asked to define a descriptor?
kicken replied to Butterbean's topic in PHP Coding Help
while ($row = sqlsrv_fetch_array($query)){ $sumUsageKWH += $row[totalUsage]; } Code like that will throw an undefined variable notice because it is the same as: $sumUsageKWH = $sumUsageKWH + $row[totalUsage]; Notice how you are trying to read the variables current value, add the total usage, then assign the result? On the first iteration of the loop $sumUsageKWH does not exist so you get the notice. To fix the notice, just assign the variable before the loop to an initial value. 0 would work well in this case. $sumUsageKWH=0; while ($row = sqlsrv_fetch_array($query)){ $sumUsageKWH += $row['totalUsage']; } Note also that your array index needs to be quoted when it is a string (as shown above). Not doing so will cause another notice error about an undefined constant.