PHP - Need Help Avoiding $75k Bill For One Night Of Loopin' In The Cloud! Measuring Cpu In Php Script?
I have questions but I also have some good info to share about putting your software in the cloud. The situation: Some of you may have read about the nightmare stories. A developer had a infinite loop in his code that ran all night. This code did things inefficiently that devoured CPU in each iteration. This developer, greatly skilled, opened his email the next morning and saw a email bill from his cloud provider totaling for $75K. True story. Most cloud providers let you define CPU usage thresholds that, when breached, send you a warning but these thresholds, if I understand them, are per account. It would seem the claim that cloud resources are available in whatever amounts you need, CPU, disk space, enough RAM to never have to wait on a page faults, etc... the claim that the cloud provides you with infinitely elastic resources in an "all you can eat for one price" contract smells just a like a little like 💩 I did cloud development for many years with ServiceNow starting when it was a help desk and I watched it evolve into one of the best cloud development platforms out there. At one customer site I installed and managed it it out of the cloud and saw its insides and I can tell you its core code is not so terribly efficient. IMHO the cloud DOES take away 90% of a developer's worries about app performance.. If you call ServiceNow tech support and your problem is diagnosed as a performance issue with your code the first thing they will ask you is "did you follow the developer best practices"? They will politely say "sorry. Here's a link to them implying "fix your code". Questions: PHP Functions that devour CPU and where there is a better way? What PHP functions or code techniques waste CPU? I am using similar_text and it does the job but it is slow. Better way? What is the best way to measure CPU used by a PHP script or by a particular code module, defined as a set of related functions that fulfill a common purpose or by a single line of code? The purpose being to identify inefficient modules of code and improve them and even if the code is damn near perfect then at least can know what code modules are the most expensive. CPU killin users (and developers too), how can they be identified? I need to store data on cumulative CPU usage for any of the above and compare it with the free amount they give you and warn CPU hogs before they breach a threshold and generate $75K bills that were not in the plan. Any info you have on avoiding surprise $75K CPU bills from a cloud provider are welcome
It would seem the Similar TutorialsI have currently developed a script that consumes a web service. It is running real slow. I think this is due to the web service provider. How do I diagnose/measure this?
Hi my name is Alexander and i am new to coding. i am in need for tommorow for this task , but i cant figure out how to make it. Can anyone explain where is my mistake and how the code should look? I have some code but its full with errors....
Hi Everyone, In redesigning my new web site, with the skills I am learning in PHP I struck upon a thought which I would like to ask: Is it possible to switch my heading banner from a daytime scene to a night time scene using the time of the local server. Basically I have two links in my database to two separate SWF files. Is there a script available anywhere that would do this? Thanks! Hello all, i just joined today, because am going nuts with php and the include or require statement/function I want to use them to link to a header. Nothing hard about that , I would say. But my bit of code below just does not work. I am running them in a test area on my server. Just to be safe The file L2.php is in the same directory/folder ( showing my age).
I should say that am have been programming a while but only using php for about 4 weeks and this normal simple bit of code has me stumped. I am building the site in visual studio and atom. any pointer would be received with joy
The content of L" is also below . Danler
<?php include_once('L2.php'); ?> centents of l2.php below <h3> line 2 <br><H2>Hello world AM TRYING 6</h2> </h3>
I've messed around with this for three hours now, and it's driving me batty. I'm running the following Query: mysql_select_db("myDB", $con); $query = "UPDATE mytable SET Name = '$Name', Address = '$Address', City = '$City', State = '$State', Zip = '$Zip', Phone = '$Phone', Website = '$Website', Type = '$Type' WHERE id = '$ID'"; The problem is that it's not updating my database. I've tried everything. I've forced the page to Echo out the variables so that I know they're right. I've run (successful) Delete queries to make sure I'm connecting to the right table. I've forced it to spit out the variables at the end of the Update. Everything I've tried works beautifully... except the Update itself. It doesn't error out or anything- it acts like it's Updating, but the data never changes. I can add to the database and delete from it, but it refuses to let me Update anything. I've looked all over the net, and tried every variation I can find. Nothing works. I also tried this: $query = "UPDATE `testbed` SET `Name`=[$Name],`Address`=[$Address],`City`=[$City],`State`=[$State],`Zip`=[$Zip],`Type`=[$Type],`Phone`=[&Phone],`website`=[$Website] WHERE `ID`=[$ID]"; And $result = mysql_query("UPDATE mytable SET Name = '$Name', Address = '$Address', City = '$City', State = '$State', Zip = '$Zip', Phone = '$Phone', Website = '$Website', Type = '$Type' WHERE id = '$ID'"); None of them do anything at all. I am trying to build an app which will scan a site multple times, the only problem is the 403 error, how do I get around this. Searching seems to imply curl or user_agent, but can't get it working. Any suggestions? Thanks I've got some PHP code that accesses SQL on an Amazon cloud server. Other machines running Unix and Windows can perform accesses fine using the server name (IP for Windows, label for Unix), database name (string) and a password (string). However, the same code FAILS on OSX (my Macbook Pro). SQL managers on my MBP have no problem accessing it, since I've made the proper exceptions on the AWS firewall. But PHP can't do any MS SQL reads of this database. Is there something else I don't know? Is there some other key information being exchanged that my MBP needs to send that I can't see? TIA!! Hey there, I am trying out some tag cloud code, but something is amiss, as am getting no tags displaying. Using PHP/MYSQL and JQuery. <?php //connection information $host = "localhost"; $user = "username"; $password = "pw"; $database = "DBName"; //make connection $server = mysql_connect($host, $user, $password); $connection = mysql_select_db($database, $server); //query the database $query = mysql_query("SELECT * FROM tags"); //start json object $json = "({ tags:["; //loop through and return results for ($x = 0; $x < mysql_num_rows($query); $x++) { $row = mysql_fetch_assoc($query); //continue json object $json .= "{tag:'" . $row["tag"] . "',freq:'" . $row["frequency"] . "'}"; //add comma if not last row, closing brackets if is if ($x < mysql_num_rows($query) -1) $json .= ","; else $json .= "]})"; } //return JSON with GET for JSONP callback $response = $_GET["callback"] . $json; echo $response; //close connection mysql_close($server); ?> and the JS Code: [Select] <script type="text/javascript"> $(function() { //get tag feed $.getJSON("/tagcloud.php?callback=?", function(data) { //create list for tag links $("<ul>").attr("id", "tagList").appendTo("#tagCloud"); //create tags $.each(data.tags, function(i, val) { //create item var li = $("<li>"); //create link $("<a>").text(val.tag).attr({title:"See all pages tagged with " + val.tag, href:"http://localhost/tags/" + val.tag + ".html"}).appendTo(li); //set tag size li.children().css("fontSize", (val.freq / 10 < 1) ? val.freq / 10 + 1 + "em": (val.freq / 10 > 2) ? "2em" : val.freq / 10 + "em"); //add to list li.appendTo("#tagList"); }); }); }); </script> when i turn on error reporting I get a lot of undefined index notices for tag and frequency so not sure if that is causing the problem or not. When user submits data through a textarea input and he then refreshes the page, the data will be re-submitted and inserted into the database a second time. I used to avoid this with a header redirect, but this solution is not an option to me anymore, since I need to echo out in the header.php, which I have to put before the submission area. Another weak point with the header redirect solution is that the user could go a page back and then hit refresh. I'm wondering how are other sites avoiding resubmission? When you post a comment on YouTube it will simply freeze the submit button after you've posted, I'm guessing they have achieved that with JavaScript, is that solution recommended? And which type of other techniques are people generally using to avoid resubmission on page refresh? If I have a web page located he www . company . com / how-to-repair-your-computer.html
And I decide to re-structure my website like this www . company . com / articles / how-to-repair-your-computer.html
How do I make sure that people don't search and end up at the old, now broken, link?
It seem inevitable that as a website grows, that you will want to re-organize things. What is the best way to make sure that anyone who searches or clicks on an old link - say from an email from a friend - doesn't get a 404 error?
Also, how do you avoid ruining a web pages rank on Google after you move things? (I think if the URL changes, Google makes you start all over as far as getting listed on page-1 and all of that?
Is this something I have to hande on my end, or is it a Google issue, or something else?
As the title says, I have a .txt file with about 30,000+ lines of data presented in a pipe delimited list, which i'm parsing and inserting into my database. Problem is, my server seems to always time out every time I try to parse the whole file at once. I'm sure naturally it would work with out any timeout errors, but i'm ensuring the data is xss clean before it's being inserted and i'm doing that on about 15 items on each line, which means i'm calling the xss clean function over 450,000 times in one execution. So my friend suggested I break the files down maybe into each file having 5,000 lines of code, which would mean i'd generate about 6 files (if I had 30,000 lines of data). I've managed to code a script that breaks the main file into several files. Now what I want to do is pass each of those files to my parser method, but i'd like to do them one by one, rather than in one execution as I want to avoid the timeout error. Any ideas? Excuse the beginner question. Though, how do you avoid the processing of HTML when text becomes inputted, without stripping away the tags, or trimming the text in any way, simply leaving it as is? I have a tag column in the table of posts. I store tags as "tag1,tag2,tag3,...". When displaying tags in the post, I explode to have an array. Everything is OK, but I cannot create a tags cloud; as I need to have the occurrence of each tag to increase the font. What is a practical trick to create tag clouds? I think the common method is to build a table for post tags and store each single tag in a separate cell. But I hope to keep my database tidy. Hi all, I have a simple mysql table of articles with one Keyword field which can hold an indeterminate number of comma-separated strings per article. I want to create a tag cloud of these keywords and score them according to how many times they appear overall. My question is two-fold. First, I have elected to do this by pulling all the keywords out into an associative array, but I'm not sure how to go about counting the number of times each string appears. Any suggestions? Second. Is this the most efficient way to do this or would it be better to keep another table of keywords and a count field? I guess it wouldn't be much more efficient as I still have to run through all the keywords in the article table to look for new entries and update the keyword table with new words and/ or counter increments. Any suggestions would be much appreciated. I'm running about 50 domains on a private host that's going out of business, so I need to move providers soon. The Amazon or Google cloud platforms are intriguing. Does anyone have any experience using either for website hosting?
My current solution is a Plesk management interface. So, I'm hoping to install the same wherever I go (because migrating 50 domains manually ...)
I want to purchase cloud servers from DigitalOcean, however I know very little about managing and maintaining servers (I just develop the websites). I know what I need without knowing how to do it. I've got a script where the client can upload pictures. The pictures are then resized, thumbnailed, and added to the database. In the process I'm trying to search the database for a duplicate file name and create a new name if necessary: Code: [Select] $userfile = 'userfile' . $i; $tmpLoc = $_FILES[$userfile]['tmp_name']; $name = $_FILES[$userfile]['name']; $error = $_FILES[$userfile]['error']; $type = $_FILES[$userfile]['type']; $temp = 'album' . $i; $album = $_POST[$temp]; if($error > 0) { echo "Error on $name: "; switch ($error) { case 1: echo "File exceeded upload_max_filesize"; break; case 2: echo "File exceeded max_file_size"; break; case 3: echo 'File only partially uploaded'; break; case 4: echo 'No file uploaded'; break; } echo "</div>"; exit; } // Check for name duplicates and deal with $query = "SELECT * FROM pictures WHERE src = $name"; $result = mysql_query($query); if($result) $dup = true; while($dup) { echo "Duplicate file name $name <br />"; $ext; if($type == 'image/gif') $ext = '.gif'; else if($type == 'image/jpeg') $ext = '.jpg'; else if($type == 'image/png') $ext = '.png'; else die("Error: Unsupported file type"); $x = 0; $name = $x . $ext; echo "Checking $name <br />"; $query = "SELECT * FROM pictures WHERE src = $name"; $result = mysql_query($query); if(!$result) { $dup = false; echo "File successfully renamed to $name to avoid duplicate <br />"; } $x++; } I don't get any errors of any sort, it just never enters the loop I read the conditions for hosting at PHP Fog, and they state that I can't use session variables as such variables are not copied between servers. Therefore I changed session variables for login info, language selection etc to cookies. Hence my own code is now free from session varibables, but Zend that I use for e.g. OAuth is not. Is it typical that cloud hosting providers disallow session variables for the above reason, or are there others that can handle such replication between servers? If not, is work going on to remove use of session variables from popular frameworks? Cheers, Anders Hey Guys.
I want to implement google cloud vision api for recognise the image. Everything installed fine, I'm getting the error Google\Cloud\Core\Exception\ServiceException { "error": { "code": 403, "message": "The request is missing a valid API key.", "status": "PERMISSION_DENIED" } } 1. in C:\xampp\htdocs\vofms\vendor\google\cloud-core\src\RequestWrapper.php at line 336 327328329330331332333334335336337338339340341342343344345 case 504: $exception = Exception\DeadlineExceededException::class; break; default: $exception = Exception\ServiceException::class; break; } return new $exception($this->getExceptionMessage($ex), $ex->getCode(), $ex); } /** * Gets the exception message. * * @param \Exception $ex * @return string */ private function getExceptionMessage(\Exception $ex) 2. in C:\xampp\htdocs\vofms\vendor\google\cloud-core\src\RequestWrapper.php at line 189 – Google\Cloud\Core\RequestWrapper::convertToGoogleException(GuzzleHttp\Exception\ClientException) 183184185186187188189190191192193194195 try { return $backoff->execute($this->httpHandler, [ $this->applyHeaders($request), $this->getRequestOptions($options) ]); } catch (\Exception $ex) { throw $this->convertToGoogleException($ex); } } /** * Deliver the request asynchronously. * 3. in C:\xampp\htdocs\vofms\vendor\google\cloud-core\src\RestTrait.php at line 96 – Google\Cloud\Core\RequestWrapper::send(GuzzleHttp\Psr7\Request, []) 90919293949596979899100101102 try { return json_decode( $this->requestWrapper->send( $this->requestBuilder->build($resource, $method, $options), $requestOptions )->getBody(), true ); } catch (NotFoundException $e) { if ($whitelisted) { throw $this->modifyWhitelistedError($e); } 4. in C:\xampp\htdocs\vofms\vendor\google\cloud-vision\src\Connection\Rest.php at line 59 – Google\Cloud\Vision\Connection\Rest::send('images', 'annotate', ['requests' => [['image' => ['content' => '/9j/4AAQSkZJRgABAQEBLAEsAAD/2wBD...'], 'features' => [['type' => 'FACE_DETECTION']]]]]) 535455565758596061 /** * @param array $args */ public function annotate(array $args) { return $this->send('images', 'annotate', $args); } } 5. in C:\xampp\htdocs\vofms\vendor\google\cloud-vision\src\VisionClient.php at line 272 – Google\Cloud\Vision\Connection\Rest::annotate(['requests' => [['image' => ['content' => '/9j/4AAQSkZJRgABAQEBLAEsAAD/2wBD...'], 'features' => [['type' => 'FACE_DETECTION']]]]]) 266267268269270271272273274275276277278 foreach ($images as $image) { $requests[] = $image->requestObject(); } $res = $this->connection->annotate([ 'requests' => $requests ] + $options); $annotations = []; if (isset($res['responses'])) { foreach ($res['responses'] as $response) { $annotations[] = new Annotation($response); } 6. in C:\xampp\htdocs\vofms\vendor\google\cloud-vision\src\VisionClient.php at line 229 – Google\Cloud\Vision\VisionClient::annotateBatch([Google\Cloud\Vision\Image], []) 223224225226227228229230231232233234235 * @param Image $image The image to annotate * @param array $options Configuration options * @return Annotation */ public function annotate(Image $image, array $options = []) { $res = $this->annotateBatch([$image], $options); return $res[0]; } /** * Annotate a set of images. * 7. in C:\xampp\htdocs\vofms\frontend\themes\admin_lte\site\index.php at line 22 – Google\Cloud\Vision\VisionClient::annotate(Google\Cloud\Vision\Image) 16171819202122232425262728 $image = $vision->image( fopen('C:\xampp\htdocs\vofms\frontend\themes\admin_lte\images\1.jpg', 'r'), ['faces'] ); $annotation = $vision->annotate($image); // Determine if the detected faces have headwear. foreach ($annotation->faces() as $key => $face) { if ($face->hasHeadwear()) { echo "Face $key has headwear.\n"; } 8. in C:\xampp\htdocs\vofms\vendor\yiisoft\yii2\base\View.php at line 348 – require('C:\xampp\htdocs\vofms\frontend\t...') 9. in C:\xampp\htdocs\vofms\vendor\yiisoft\yii2\base\View.php at line 257 – yii\base\View::renderPhpFile('C:\xampp\htdocs\vofms\frontend\t...', ['dataProvider' => yii\data\ActiveDataProvider]) 10. in C:\xampp\htdocs\vofms\vendor\yiisoft\yii2\base\View.php at line 156 – yii\base\View::renderFile('C:\xampp\htdocs\vofms\frontend\v...', ['dataProvider' => yii\data\ActiveDataProvider], frontend\controllers\SiteController) 11. in C:\xampp\htdocs\vofms\vendor\yiisoft\yii2\base\Controller.php at line 384 – yii\base\View::render('index', ['dataProvider' => yii\data\ActiveDataProvider], frontend\controllers\SiteController) 12. in C:\xampp\htdocs\vofms\frontend\controllers\SiteController.php at line 89 – yii\base\Controller::render('index', ['dataProvider' => yii\data\ActiveDataProvider]) 83848586878889909192939495 $dataProvider = new ActiveDataProvider([ 'query' => Offenses::find(), ]); return $this->render('index', [ 'dataProvider' => $dataProvider, ]); } /** * Displays a single Offenses model. * @param integer $id * @return mixed 13. frontend\controllers\SiteController::actionIndex() 14. in C:\xampp\htdocs\vofms\vendor\yiisoft\yii2\base\InlineAction.php at line 57 – call_user_func_array([frontend\controllers\SiteController, 'actionIndex'], []) 15. in C:\xampp\htdocs\vofms\vendor\yiisoft\yii2\base\Controller.php at line 157 – yii\base\InlineAction::runWithParams(['r' => 'site/index']) 16. in C:\xampp\htdocs\vofms\vendor\yiisoft\yii2\base\Module.php at line 528 – yii\base\Controller::runAction('index', ['r' => 'site/index']) 17. in C:\xampp\htdocs\vofms\vendor\yiisoft\yii2\web\Application.php at line 103 – yii\base\Module::runAction('site/index', ['r' => 'site/index']) 18. in C:\xampp\htdocs\vofms\vendor\yiisoft\yii2\base\Application.php at line 386 – yii\web\Application::handleRequest(yii\web\Request) 19. in C:\xampp\htdocs\vofms\frontend\web\index.php at line 17 – yii\base\Application::run() 11121314151617 require _DIR_ . '/../../common/config/main.php', require _DIR_ . '/../../common/config/main-local.php', require _DIR_ . '/../config/main.php', require _DIR_ . '/../config/main-local.php' ); (new yii\web\Application($config))->run()Quote
Where I can set GOOGLE_APPLICATION_CREDENTIALS environment variable in Yii2 framework.
Edited February 9, 2019 by PHPLazy I have the following code:
$fp = fopen(“path_to_file”, ‘a’); flock($fp, LOCK_EX); fwrite($fp, $string); flock($fp, LOCK_UN); fclose($fp);If I try to lock the file in two different places at the same time, this will cause a race condition. How can I prevent this? I know in Java, for example, it has a concurrent library which contains reentrant lock, which basically tries to get the lock and if can't waits. What can I do in PHP? |