Docker, along with a few service containers, makes a fast and slick development environment. There are a few examples and tutorials out there for its use. Here's one: https://docs.docker.com/samples/library/php/
You are probably running this on Windows, which has a maximum rand() value of 32767, which means every 32768 tries will repeat the entire deterministic pattern of rand().
And to answer your question, rand() is certainly not "random" in any cryptographical or even useful sense.
As a long-time user of Laravel, the best advice I can offer is Laracast's 'From Scratch' series on the version you're using. Each one is completely free, and you can find the current version (Laravel 8's) here: https://laracasts.com/series/laravel-8-from-scratch
I will admit, as far as PHP frameworks go each one is overwhelming at first. But having worked in Yii, Laravel, Symfony, CakePHP, WordPress, and CodeIgnitor, once you start picking things up, building an application that works well becomes incredibly fast with Laravel. The biggest thing though is that the framework does rely on a lot of 'magic' and a method of thinking for how to do things the 'Laravel Way'.
I wish you the best of luck in your journey!
The initial thought most developers have is to start over from scratch, which is almost always a really, really bad idea. A huge refactor that involves moving to a different framework is almost as bad for exactly the same reasons - it will take a long time, during which you'll be trying to merge code between the two versions, and you'll end up breaking a ton of shit while doing it.
Pick up a copy of Working Effectively with Legacy Code. In the meantime, I'll give you the tldr:
The more changes you make at a time, the more likely you're going to break something. And this is a production app - not breaking things is your highest priority.
You should apply these steps to any work you do on the app - add more test coverage, and leave that area of the code better than how it was when you left it. When this is how the entire development team treats a codebase, it will turn around surprisingly quickly. And you will be much more valuable to your employer than someone who came in, argued for a whole bunch of work, and then after months of neglecting the current customers ended up with something that's works significantly less well than the original project. Work with what you have, and try to understand the business perspective.
If the specific technologies are really really a problem, you can go with the current trend of moving to a microservice architecture (so you could rewrite pieces in Laravel, or even better, not PHP). But this is the same idea: take a tiny piece and rewrite it, and do that continually over a period of years.
Good luck!
$value = filter_var($value, FILTER_SANITIZE_STRING);
To verify that it is a certain type, use the Validate filters from the second link.
Not only is it bad, but it has been deprecated since 5.3 and is removed since 5.4.
>What does this do exactly?
Register globals places data submitted by the user into variables, which may affect your code.
Take the following code for example:
if (is_user_authenticated()) { $authorized = true; }
if ($authorized) { //grant admin rights }
now assume you got register globals turned on and visit the following URL:
http://domain.com/admin.php?authorized=1
The data submitted in the query string will populate variables matching the names of the fields in the query string, meaning that the $authorized variable will be set to "1" without ever needing to pass through authentication, and the user will thus have access to administration privileges.
> How do I salvage my scripts and "fix" it?
I suggest you read through the following:
Laravel uses an Active Record style ORM called Eloquent which is very easy to use. It also uses a templating system called Blade which is also great. And lastly, Laravel uses Symfony components where it makes sense. My vote is for Laravel.
References: http://laravel.com/docs/eloquent http://laravel.com/docs/templates
EDIT: After reading the comments I thought of another cool Laravel plus. It has the "Artisan" command console which let's you write a lot of infrastructure code without actually writing ANY code. In addition, Jeffery Way created some great generators that can be added in to really take it up a notch. If you are a sublime text user, there is a generators plugin to make it even easier. And finally, Laravel has migrations which is a godsend over many of the other frameworks I have used.
Big find? Well, not really. Third-party mirrors, official or not, are still just that: mirrors. They're ultimately controlled by the kind person who volunteered. In fact, PHP makes this pretty damn clear by listing the mirror provider on the mirror selection page.
Calling it a "a not-so-hidden secret on [PHP's] website" is pretty misleading. It's properly PT Pasifik Satelit Nusantara's not-so-hidden secret.
Also suspicious: notice there's not a single mention of the word "mirror" in that article. If the author weren't trying to sensationalize he'd at least mention how the content got there.
I just don't see why we don't model a Code of Conduct after Debian's:
https://www.debian.org/code_of_conduct
This is actually an adaptation of the JS adaptation of Clean Code. And over the years, the open source community has injected their own thoughts into it -- sometimes for the better, sometimes not. Which means parts of this adaption didn't come from Martin's Clean Code, parts of Martin's Clean Code aren't in this adaptation, and most code examples don't resemble Martin's.
Personally, I recommend you avoid this game of telephone and just read the original book.
PHPStorm and watch this free Laracast: Be awesome in PHPStorm
You have to learn (take your time) to use source versioning (Git).
If you're a student, PHPStorm and most of Jetbrains tools are free: https://www.jetbrains.com/student/
PHP Manual says:
>If a file is pure PHP code, it is preferable omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines after PHP closing tag which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.
Especially not reading non-PHP books: SICP, Code Complete, Design Patterns, Refactoring, Patterns of Enterprise Application Architecture, Clean Code, Working Effectively with Legacy Code...
Honestly I think the best book for a brand new PHP developer is probably Sandy Metz' Practical Object-Oriented Design in Ruby.
After reading your github page, I still have no idea how or why to use your package. I see a lot of fancy terms explaining an overly complex architecture with no instructions on how to actually use it. As a senior engineer whose job is to get things done, I'd have to nope right out of there.
Let's say I wanted to get data from stripe. I could take a look at their api page and know exactly how to use it - they give examples right there on the page, easy!
Or if I wanted to make a standard curl request and scrape a regular page, I could just look into guzzle and boom, there's an 10 line snippet on the frontpage that I could just copy/paste.
But yours? No idea how to use it, or why. Instead I see a detailed guide on how to write my own provider, which I guess is nice ??? but don't care for in the slightest.
TLDR; less technical mumbo jumbo and more practical instructions/explanations
Ask them what they spend most their time developing with... whether it's a framework, cms, vanilla... learn the basics from phptherightway.com then sandbox using whatever they develop with?
You should know how to approach this if you have dev background...
I would recommend checking out Yii Framework. It's a PHP5-only MVC framework which has been around for a while, has a strong community, and is being actively developed with daily commits and frequent releases. I found this framework very easy to learn (much easier than CakePHP IMO). It has strong documentation and even a couple of Books which are very well written. If you are considering Symfony, CakePHP, or CodeIgniter I would highly recommend checking out Yii.
Also, most all of these frameworks will give you what you are looking for. I found that most people learn and are more comfortable with various frameworks due to either which one they learned first, how a framework is organized, documentation, etc.. So it comes down to experimentation. I recommend downloading a few of your most promising-looking frameworks and run through their 15-minute blog tutorials. You'll get a good idea for the feel of each framework, and a better understanding of how it may fit your needs.
Hope this helps! Edit: Link Formatting >.<
In short, here are the reasons why I created a new library:
You can read https://www.drupal.org/project/drupal/issues/1333730#comment-9301135 to learn more from the author of HTMLPurifer himself :) .
Probably posted to the wrong sub by OP, yeah. But I do think that the PHP community should learn about Let's Encrypt and tell the world to embrace it. Hopefully it'll be included by default in many LAMP stacks, just like PHP.
For those interested, here's how it works: https://letsencrypt.org/howitworks/
http://www.indeed.com/jobs?q=junior+php&l=Brooklyn%2C+NY
Looks like most JR PHP positions in Brooklyn are starting in the $50k area, with about half of them starting at $70k plus. You're being severely underpaid and your company is making a killing off of you.
For the first experience, Laracasts have good videos with TDD https://laracasts.com/series/build-a-laravel-app-with-tdd you can try. I'm not big fun of Laravel but to understand this approach this videos is good.
> Now I have some free time and would like to refactor some of my old projects to improve them and learn a few new skills in the process.
Have I got the book for you: Modernizing Legacy Applications in PHP. I am the author, but you don't need to take my word for it -- read the reviews linked on that page (the one from SitePoint is fair), and of course ask around.
Hope it helps!
Just noticed Jeffrey Way made "Laravel 5 Fundamentals" free today. It wasn't yesterday. Kudos, Jeffrey. :)
https://laracasts.com/series/laravel-5-fundamentals
Dayle Rees, where is "Code Smart?" :P You're losing ground to Mr. Way!
The series currently sits at over 4 hours of FREE Laravel 5 video training from one of the best teachers out there. That is truly amazing. I'm not a paid shill or even a friend of Jeffrey, I just recognize a kick ass bargain.
I do sortof wonder if Way is earning more off of the existence of Laravel than Mr. Otwell himself. They should really form a company together and share. :)
Sublime Text and VS Code are both great. Both customizable with a lot of plugins/packages that improve PHP integration.
But, you can always just use http://www.jetbrains.com/phpstorm/eap/, which only gives you 30 days but since they update once a month, you can pretty much have a perpetually valid license if you keep updating.
My two most obscure (almost never met anyone using them) :
An optimization trick (relevant at really high load): if(!isset($myString{10})) { //do something }
Instead of : if(strlen($myString) < 10) { //do something }
And a common sense one: Instead of doing stupid Regex for basic input check (alpha, numeric, ...), use Ctype. Much faster.
Why has no one, including OP, replied to this comment? The two patterns linked here are the solution to the problem: the DI pattern doesn't say every object in your application should be constructed via the container. In your case, you would create a factory, eg ConnectorFactory
. The factory itself would be responsible for creating the correct connector at runtime, based on criteria provided from outside.
The strategy pattern comes into view when looking at single connectors, each connector should implement the same interface, eg. Connector
to be sure a set of known methods can be called.
There's nothing wrong with the DI pattern, but we must be careful not to abuse it (like eg. a service locator). There are good reasons not to use the DI container as a service locator: https://stackoverflow.com/a/1557804/3437882
Note that if you're comparing hashes, encrypted values or other strings that need to be secure, using === or strcmp() can make your application vulnerable to timing attacks. You can mitigate this by hashing both strings with something like md5, or better, compare both strings character by character without returning early.
PHP 5.6 users can use http://php.net/manual/en/function.hash-equals.php
Also have a look at Symfony's implementation of comparing strings in the security component: https://github.com/symfony/symfony/blob/v2.5.6/src/Symfony/Component/Security/Core/Util/StringUtils.php#L28-L65
For the first 3, I would recommend the Symfony HTTP Foundation component (https://github.com/symfony/HttpFoundation). It used by many different frameworks so you know it's well supported. It allows you to access all the superglobals use an entity called a ParameterBag which makes it easy to specify defaults when retrieving values. It utilizes the PHP filter_var function when using $request->$request->filter().
// Set up the object $request = Request::createFromGlobals(); // Get the email value from the $_POST, but set as 'NA' if not found $email = $request->request->get('email', 'NA');
For complex validation, take a looks at the Symfony and Silex Validator. They allow you to create assertions to ensure the data you get is acceptable: http://silex.sensiolabs.org/doc/providers/validator.html.
I went to Symfony2 conference in Cologne this year and one of the standout talks was by Igor Wiedler on Silex. I would recommend it based on that talk alone.
You really shouldn't use ctype. Use the Filter library. People commonly use ctype_digit() which has side effects if the values you're testing are actually integers.
Here's the problem:
<?php
var_dump(ctype_digit(10)); // false
var_dump(ctype_digit(-1)); // false
var_dump(ctype_digit("-1")); // false
var_dump(ctype_digit(12345); // true
var_dump(ctype_digit("10")); // true
var_dump(ctype_digit(53)); // true
var_dump(ctype_digit('0123')); // true
?>
The reason for 10 not validating is that integer values from 0 - 255 are treated as character representations instead of actual numbers. What it sees in this case is the same as chr(10). The reason for 53 validating is because chr(53) is '5'. Integers greater than 255 are suddenly seen as expected again.
Signed values are just not supported at all and will always be false.
ctype_alpha suffers from the same problem as does every other member of the ctype family:
<?php var_dump(ctype_alpha(97)); // true ?>
In this case, chr(97) is the letter 'a'.
Working Effectively with Legacy Code
Might be a good place to start. Don't rebuild in one hit, isolate functionality, wrap with tests and abstraction layer, rebuild one component at a time
I'm assuming you're American? I've only just 'learnt' this tonight, but Americans say 'learned' and the British (i.e. me in this case) say 'learnt'. I'm sorry it put you off, but it's not incorrect, just Ye Olde British English haha http://www.oxforddictionaries.com/words/learnt-vs-learned
PHP loads and parses the file, then starts executing it. The same goes for every file you require/include. The error you mentioned occurred because syntax errors are fatal so the whole execution halts when PHP can't parse a file.
Starting from 5.5, PHP comes with OPcache that stores precompiled script bytecode in shared memory, thereby removing the need for PHP to load and parse scripts on each request, which improves performance. Prior to this version, the APC extension was a common alternative.
Other than this cache, PHP itself shares nothing from your code between requests. So what you say about "keeping a reference for all members in a class" is true for the scope of each request. Classes are defined on each request when the code defining them is executed, and keep defined until the end of each request. Objects exist from the point they are instantiated to the point when the garbage collector identifies they're no longer needed; longest case scenario, they're destructed and freed from memory at the end of each request.
That's pretty much it without going very deep. Does it answer you?
WordPress licence page says "There is some legal grey area regarding what is considered a derivative work, but we feel strongly that plugins and themes are derivative work and thus inherit the GPL license."
The Drupal page says "If I write a module or theme, do I have to license it under the GPL? Yes. Drupal modules and themes are a derivative work of Drupal. If you distribute them, you must do so under the terms of the GPL version 2 or later. You are not required to distribute them at all, however." (point 7)
So if you want to be sure, contact a lawyer.
It's been a heck of a lot of work, but today we've released Bolt 3 stable! Check the site for details.
If you have any questions or remarks, feel free to post them here, or join us on IRC, Slack or Twitter
what are the values that you're comparing? If you can, use the === operator instead of ==
ideally, this should be enough:
return (($val_1 === $val_2) && ($val_1 === $val_3))
It's not buit-in. It's a PECL extension: http://php.net/manual/en/yaf.installation.php
This » PECL extension is not bundled with PHP.
PHP should remove such documentation from the main docs.
> Over-stepping your authority and making threats of banning/unpublishing actions against other contributors: https://www.drupal.org/node/2391219
There's literally NOTHING I can interpret like so in his 6 or so comments in that thread. Can anybody help? I went through every issue linked and wasn't able to find anything toxic or offensive.
I'm not sure I trust those.
I went to this site here:
https://howsecureismypassword.net/
I typed in "red potatoes are my friends" (without the quotes). It tells me that it would take a PC 3 octillion years to crack my password.
However, if said PC is running at 4 billion hashes per second and stepping down a the list of all words in the english language sorted by frequency of use, my password would last about 2 days. "chili dog monkey nutso" (from the article) is better than my own password would be in terms of word frequency ("nutso" in particular isn't in the top 50,000 words), but it sure as fuck wouldn't be able to hold out for 18 quintillion years.
In fact, imagine you're the NSA and you have shit tons of money. The entire english language is about 1,000,000 words. Assuming a desktop PC can check 4 billion hashes per second, a password with four words in the space of the entire english language would take 8 million years for a single PC to crack. At $500 a pop, 8 million PCs would cost about 4 billion dollars, well within the NSA's budget. In other words, in the space of a single year, they could crack every single 4 word combination in the english language. If, as many people would, you stick in the top 10,000 words (like my red potatoes password), then they could get all combinations of 6 words or less in the same timeframe.
In short, password entropy checkers aren't a whole lot of good unless they check a word frequency list. Words have a lot less entropy than a random string of letters.
/u/jeffreyway did an awesome set of PHPStorm intro videos which cover everything from decluttering, to theming, to keyboard shortcuts, to templates/macros... it's basically my goto for "tips". And it's one of his Free series...https://laracasts.com/series/how-to-be-awesome-in-phpstorm.
I use probably... 70 or 80% of what he mentions in there.
Also the plugin ecosystem is a bit of a goldmine if you're happy to wade through it to find stuff. The Emberjs plugin is great if you use Ember, the Doctrine Annotations is a must have if you are using annotations, and the .editorconfig plugin saves configuring code styles at a project level (just reads the editorconfig file and applies them).
WAMP server can be used to run the scripts and then you can shut it off when it's not needed.
But honestly, permissions are annoying in windows. You would be better off running a server in virtualbox. But that requires a lot more work to get configured properly.
As with all things management, it depends.
You should be giving them feedback regardless. In the coding realm, that often takes the form of code reviews but there's also no harm in pointing out code smells as you find them. "Jimmy, when you use a variable named $fg, it leads to a situation where the rest of us have to spend time figuring out what that means. Remember, code is read way more often than it is written. What do you think about changing that to $futureGoals?"
As far as cleanup goes, you have to balance the goals of the project. If there is a tight deadline but you can revisit after the launch, slap some @todo comments in there. If there isn't a deadline and you will be maintaining this code for years to come, spend the time cleaning up now.
And if these Jr. Devs are going to be with you for a long while, invest in them. Get them a subscription to Laracasts or a copy of Clean Code. At the very least, if you clean the code yourself, write a good commit message as to why you changed it and then share those with them.
Read stuff. For example, you may wanna get a copy of Code Complete for a few cents, and read it. The old version is totally fine. No need to spend >30$ for the newer edition.
Then you might wanna check out a php framework. I'm pretty happy with CakePHP. Figure out how to use it, and try to figure out why they work like they do. It may have quite a learning curve, but it sure is worth it.
You code-fu will improve. I promise.
MySQLi
does have some advantages; see this comparsion. If you need asynchronous queries it's the only option you have.
If either driver suits you I recommend PDO.
The main point of prevention is making sure that whatever is passed into the query cannot begin another query. If your ProductID's are numbers, you can simply do
$_GET["link"] = (int)$_GET["link"];
As casting it as an int will just change it to 0 if someone tries to pass something malicious in. So you can then use your value in the query, however, if it's a string, you should look into PDO - http://php.net/manual/en/ref.pdo-mysql.php - basically it would have you change your queries to something like
$Statement = $db->prepare("SELECT * FROM Products WHERE ProductID=?"); $Statement->execute(array($_GET['link'])); $rows = $Statement->fetchAll(PDO::FETCH_ASSOC);
The ? is replaced with your value, in a way that is secure. PDO is a small change in the way you likely think about things, but makes it much easier to be secure, and you'll likely wonder how you lived without it after a few hours of using it.
The article says:
>Keep in mind that not all your PHP extensions may support PHP 7 yet, sadly I can no longer use the excellent XCache opcode cacher that worked perfectly for me for so many years.
You might want to mention that PHP has a bundled OP Cache since 5.5 and that it is further improved in PHP 7. For example PHP 7's OP Cache brings a file backend that will accelerate even CGI and CLI scripts and applications that couldn't fit in shared memory.
If you building small website (especially heavily depended on API), try Slimframework. Another lightweight is Silex, witch is small framework from Symphony components.
It's one thing to learn PHP. The language itself is pretty straightforward.
It's another thing entirely to learn how to program. There are many techniques and which ones you can leverage will depends on the capabilities of the language itself.
In recent years, PHP has morphed into a half decent programming language, and as such the community is finally coming around to using more elaborate object-oriented programming techniques, test-driven development, and SOLID coding principles.
Laracasts is a good place to start. There's a free series about starting from scratch with the Laravel framework: https://laracasts.com/series/laravel-from-scratch
Although this series is tailored to beginners learning Laravel, it makes no assumption about your skills aside from understanding PHP itself. Jeffrey takes the time to explain the programming concepts at play - especially ones that may not already be familiar to PHP developers.
Even if you never use Laravel, I think this series is useful as it starts to expose you to good practice architecture decisions.
I think it's terrible and there is zero reason to write it like that except to be a smartass. I would definitely prefer
if ($email !== null) { $this->setEmail($email); } // On a single line ...
But then I would also not initialize properties with setter functions like that, and also, if $email
really is optional,
why can't I just call setEmail(null)
anyway? But of course, example code, etc.
Slightly unrelated:
In an ideal world, I would also like if
to be an expression like in Kotlin (https://kotlinlang.org/docs/reference/control-flow.html), but we have to work with the language limitations we have. Abusing the short-circuiting of operators like this often suggests a missing language feature.
You shouldn't rely on any information sent by the client. Not on the filename, not on the mimetype.
Use <code>finfo_file()</code> to detect the actual file mimetype based on the file's content.
function file_mimetype($filepath) { $finfo = finfo_open(FILEINFO_MIME_TYPE); $mime = finfo_file($finfo, $filepath); fclose($finfo);
return $mime; }
if(file_mimetype($_FILES['myfile']['tmp_name']) == 'application/zip')) {
}
I'm currently doing the reverse - learning Java when I already have years of PHP experience under my belt.
I'm using Thinking in Java
, and have basically flown through 250 pages because modern PHP is so similar to Java, other than a few syntax differences here and there.
My suggestion would be to learn programming using Java. It is not on its way out - hell, all Android apps are written in Java! Learning programming using Java will introduce you to OOP concepts which will serve you well in the future and easily translate to PHP and other languages.
Yes, but documentation is nonexistent. For example, there used to be overhead when using count() in a for loop. However, PHP now stores the value internally so basically the performance hit is negligible. But you would only know that if you read the PHP source code or have a co-worker who knows (great person to have in a code-review)
Are you still stuck on old 5.3, or can you move to newer versions? If you can, generators will address this issue for you - they allow you to iterate over data sets without loading them all into memory first.
http://php.net/manual/en/language.generators.overview.php
Further, if you can get onto PHP 5.4, you can make use of League/CSV which uses iterators to make working with large data sets, easier.
Absolutely this. First year I started my career I swore by sublime. And I wasn't that type of dude who said that uses sublime just cause I downloaded it and ran it. No sir, I had it configured and tuned exactly as I wanted, with all them nice packages and plugins and all that jazz, and I just flew between classes and methods like no other.
But then I saw my boss using phpstorm. I think it was version.. 5? Anyway, I very quickly realised the importance of having some features of phpstorm that were unthinkable in something as sublime.
I started trying to pick the best of both worlds. What did I miss in phpstorm that sublime had to offer? Well, turns out, I very well could configure that in phpstorm. Make an effort and really try to see what you like about sublime. The speed you say? Not really a strong argument In 2020, in my opinion. Ask for better hardware. The light-weight interface? You can very well tune that. Have a look at https://laracasts.com/series/how-to-be-awesome-in-phpstorm
I'm seeing this as a post where you're trying to not change, but fail to come up with strong arguments, so you're trying to find the right echo chamber on the Internet to support you.
Put on your big boy pants and accept that in this industry you're always gonna have to be learning new things, new tools, adapting, and give phpstorm a good try.
At this moment, I'd have all my team use phpstorm no questions asked.
Meanwhile in Java they are adding <code>var</code> as a keyword.
It's functionally unrelated to this deprecation, but it seemed funny to me that we are deprecating the word and they are trying to add it.
I wouldn't use phpMyAdmin on a production server, I just don't trust any 3rd party web-app with admin access to my db server. The web-server gets basic CRUD permissions and all management is done via remote MySQL over a secure connection. I use http://www.heidisql.com/ (free/feature-full/fast).
Best practice is to store the database connection details in a configuration file outside of the web root, and outside of your source control. As an aside: it's also not good practice to connect to MySQL as the root user.
Have a look at parse_ini_file() to give you a few pointers.
Having the username and password (and hostname, and database name for that matter) in a configuration file also means you can easily set up multiple instances of your code that run on different databases without having to change the code.
Having a template configuration file in your source control is not a bad idea; and is actually encouraged (by me at the very least :-P).
Thanks for checking Spiral out and your feedback. Maybe you can clarify the part about singletons since the only singleton is in the IoC container itself. No other places in the application. What you may have been looking at is an ORM command bus which does not have any dependency.
P.S. Already read my copy of Code Complete and Clean Code when it came out http://imgur.com/a/75zAD ;)
I'm pretty sure you are checking if the $_GET['Tc'] and $_GET['Tf'] are empty and that's why the zero is not accepted. empty() will return false if the the input is 0, 0.0, or '0' http://php.net/manual/en/function.empty.php. To check if in empty but allow also 0 you can use the following:
if ( empty($_GET['Tc']) && $_GET['Tc'] !== '0' ) { // $_GET['Tc'] is empty }
Do the same for $_GET['Tf'].
And in case you are wondering, we check for '0' instead of 0 because the GET and POST variables are always going to be strings.
::class
notation makes a string with a FQCN: http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.class.class
well, the example above is rather stupid IMHO, you could just write strings with these class names. It is much more useful if you have the class already "used".
use Some\Long\Namespace\Service;
// ...
$providers = [ Service::class ];
makes code more readable.
New Symfony (> 2.8) makes also a good usage of it:
use Symfony\Component\Form\Extension\Core\Type\IntegerType; use Symfony\Component\Form\Extension\Core\Type\TextType;
$form = $this->createFormBuilder() ->add('name', TextType::class) ->add('age', IntegerType::class) ->add('occupation', TextType::class) ->getForm();
It is also very useful if you are already in the namespace and you want to pass the FQCN to some other services.
<?php
namespace Some\Long\Namespace;
class Service { // ...
function foo() { $this->otherService->doSomething(self::class); } }
self::class
will be expanded to a string Some\Long\Namespace\Service
.
http://php.net/manual/en/function.set-error-handler.php
http://php.net/manual/en/function.set-exception-handler.php
Why get one when you can get them all? Set these at the beginning and you can capture all the generated errors without letting them hit the client.
Hope this doesn't become annoying when trying to find documentation:
https://laravel-news.com/laravel-elixir-to-laravel-mix
http://elixir-lang.org/getting-started/mix-otp/introduction-to-mix.html
:P
I can't say I've seen anyone willingly choose IIS for development when production is linux, no.
Vagrant makes it very easy to spin up a linux virtual machine that can mimic the production environment. You can keep using the same windows editors and browsers and share the code with the virtual machine using NFS (supported out the box with vagrant).
I've been discussing PSR-6 with the authors on the public mailing list for months. I've written test implementations and provided feedback as well as reviewed test implementations done by others.
Some of these points were raised by someone (Aaron Scherer) on the mailing list only today. I didn't consider the significance of them until his post.
This also doesn't change the fact that the spec isn't ready. It's not great having these things raised now, I agree, but that doesn't mean they shouldn't be raised at all.
With regards to the issue on voting, I didn't foresee the objections from Doctrine, Guzzle and Laravel. Maybe they did object publicly on the mailing list before the vote but I wasn't aware of it. I'd also like to know the reasons for their objection. I would guess that it's because the interface is too complicated (common criticism also made by others). My point here is that the most relevant projects in the group are against the proposal and everyone else appears to be voting '+1' without thinking why.
On number two, the problem isn't that they'll throw the 'CacheException', the problem is that the specification doesn't require exceptions implementing the 'InvalidArgumentException' interface to also extend the root 'InvalidArgumentException' class (the root class isn't event mentioned).
Problem three is that you'll need to provide a public method that you only want to use for internal purposes (for the reason that it isn't a public method on the interface in the first place).
[edit] Someone's down voting you, not sure why. It's a valid response and I should probably make some things clearer in the article.
Not just blogspam -- it's just quoting the linked Quora question without adding anything else of substance -- it's hella outdated blogspam - February 27, 2012.
From the docs:
Example #4 password_hash() example finding a good cost
<?php /** * This code will benchmark your server to determine how high of a cost you can * afford. You want to set the highest cost that you can without slowing down * you server too much. 8-10 is a good baseline, and more is good if your servers * are fast enough. The code below aims for ≤ 50 milliseconds stretching time, * which is a good baseline for systems handling interactive logins. */ $timeTarget = 0.05; // 50 milliseconds
$cost = 8; do { $cost++; $start = microtime(true); password_hash("test", PASSWORD_BCRYPT, ["cost" => $cost]); $end = microtime(true); } while (($end - $start) < $timeTarget);
echo "Appropriate Cost Found: " . $cost . "\n"; ?>
Output:
Appropriate Cost Found: 10
preg_replace with /e
is basically eval
- it's a somewhat common way to get around eval itself being disabled. The /e
modifier was deprecated in 5.5 and removed in 7.0, so upgrading to a newer version will at least help.
HTTP_SBCEM
is a mystery to me, but check the nginx/apache configs to see if it's being injected as an environment variable by the webserver. Normally you may see HTTP headers added in $_SERVER
(e.g. X-Forwarded-For would be available in $_SERVER['HTTP_X_FORWARDED_FOR']
). In the environment... is weird.
I've seen much better attempts.
it's a bit-shifting operator. quite interesting. quite opaque/uncommon in everyday usage.
a good start can be found here: bitwise operators
Items is not an array. It is an iterator. In fact, it's a SimpleXMLIterator.
This means that it looks like an element, behaves like one, but has a "next" method. This is just bad design.
As proof, it you check, $items
will be equal to $item
in the loop:
foreach ($items as $item) { var_dump($items === $item); // should be true }
The first thing you always want to consider regarding caching is whether or not you actually need it. (Insert a thousand blog posts about premature optimization here.) How long does the query take to run? What are the performance requirements of that particular page?
If you decide that you do actually want to cache that information, you have a couple good options:
php_value
& php_flag
are generally used for ini settings.
Use SetEnv
: http://httpd.apache.org/docs/2.2/mod/mod_env.html.
The variable is now exposed in the $_SERVER superglobal:
e.g.:
SetEnv TEST_VAR 123
*.php
$_SERVER['TEST_VAR']; //123
Since you're already a programmer, I think it's fine to learn what you need about php as you're working with laravel. Take a look at this php series. It looks like it will give you a good primer in a couple of hours. https://laracasts.com/series/php-for-beginners
I haven't gone through it but if it's like the rest of laracasts, it should be awesome.
> Maybe I'm waffling and this is probably too open a question without the right details but after a year of trying to plan out the best approach I need more opinions rather than my own.
Might I suggest my book on Modernizing Legacy Applications in PHP ? It details a step-by-step process to transform your legacy PHP application into an organized, modern, testable application. (You don't have to take my word for it that it works; here's a review from SitePoint.)
Regardless, good luck!
You can create a virtual machine with Vagrant and Laravel Homestead. The nice thing about this is if you screw up your environment, you can just make a new virtual machine.
I don't think anyone replaces a needle with a haystack... ;) But agreed, ideally the needle position would be consistent there. But from the FAQ:
> PHP is a glue that brings together hundreds of external libraries, so sometimes this gets messy. However, a simple rule of thumb is as follows:
> Array function parameters are ordered as "needle, haystack" whereas String functions are the opposite, so "haystack, needle".
One can argue that str_replace() is like an array function, as its arguments can be arrays, so the general rule of thumb kinda sorta still applies!
And they used <code>preg_split</code> which I imagine is a lot slower than just using <code>str_word_count</code>
edit: ah they're actually keeping count of all occurences of each word, so that wouldn't work.
edit2: I did get 20% better performance by using isset()
instead of array_key_exists()
, made a PR for it.
> He's pushing very hard for libsodium being introduced
Which is very well respected and not his library.
>We should be using a widely adopted open standard like OpenSSL.
Oh hell no. Aside from the "unmaintained" angle, it's got exactly the same isssues as mcrypt - it assumes the developer will make good choices (they won't). Let's look at the man page. That even refers to it as largely undocumented. So let's look at the most upvoted answers.
You won't have to look far to find a recommendation for unauthenticated CBC mode. If you can't see what's wrong with that - that is exactly what's wrong with using OpenSSL in this scenario.
You might be able to disable eval()
using an INI setting, but I haven't tried it before.
In terms of fixing a hacked site, sometimes the safest approach is to render everything down to data (e.g. blog posts) and then reimport it into a fresh, trusted installation.
> Haystack-needle or needle-haystack? No longer need to read the same documentation for the third time this week.
Sure you do, to figure out how those functions report errors (you are checking return values, right?), which might not even be properly documented.
Does this one throw exceptions, return null
, return false
, return 0
, raise a PHP error, or some combination of the aforementioned? Better yet, does it indicate error by returning a value that's distinguishable from a valid return value (looking at you <code>json_decode</code>).
Ignorance - Alexa rankings (http://www.alexa.com/topsites):
Edit: typo
Congrats on publishing the project. Some thoughts for you:
I'm not sure you can really call this framework agnostic when you directly extend illuminate\support\collection. At a glance it doesn't look like you really need that dependency, I'd probably suggest you extend ArrayObject instead.
You might also want to consider how other types of cost could be applied, like shipping or discounts. You would probably want to differentiate these from normal items. On a similar note, how could you apply taxes to products. Each item could have variable tax rates, and I'd need a way to set/display them.
Write some unit tests too if you can; a package without any form of tests is unlikely to be one I would use on a production project.
Hi gang, this is the first post I've made in the forum (I think?). Well if it isn't my first then I don't remember any others.
I've known Larry ever since getting involved in Drupal a decade ago. He's always been argumentative but respectful. Even when arguments get heated and the adrenaline amps up, he states his points / opinions and gives others the opportunity to state theirs. That's the thing I've come to expect from him, respect.
It doesn't sound like Larry was given a real opportunity defend his position. In Dries post:http://buytaert.net/tag/living-our-values and the Drupal Associations' response : https://www.drupal.org/association/blog/a-statement-from-the-executive-director , it sounds like a board of directors decided to exclude Larry from being in a leadership position (but not full excommunication from the community) and then allowed Larry to appeal the decision. But Larry asserts that he never got to speak for his case or respond to questions from the board. It's also not clear if Larry was presented all the evidence they have accumulated against him.
As someone who has invested over a decade of their professional life in this community, BECAUSE of how inclusive the community has been to me and others who have come in because it is so welcoming, it shocks me to learn there are limits.
I'm left with either hoping that the evidence they say they have and that they say they won't share was strong enough for this firm decision. Because otherwise I just witnessed a friend tell another friend "You're dead to me" because of something they won't talk about.
I guess I'm in stage one: Grief.
https://laracasts.com My go to when first looking for video tutorials related to Laravel. My advice would be to look at some of the free videos on the site and compare them to others, to see if it fits your needs, before buying a licence.
Let me just start by saying, what is the closure class? What does it do, and why is it useful?
What could this class be possibly used for?
Closure { /* Methods */ private __construct ( void ) public static Closure bind ( Closure $closure , object $newthis [, mixed $newscope = "static" ] ) public Closure bindTo ( object $newthis [, mixed $newscope = "static" ] ) }
The manual may come in handy to understand the default configuration upstream and what is going on.
> If set to TRUE, PHP will always populate the $HTTP_RAW_POST_DATA containing the raw POST data. Otherwise, the variable is populated only when the MIME type of the data is unrecognised.
So it could be that certain requests trigger the deprecation warning simply because of how some requests are coming in.
However, on the note of the default configuration not making any sense, here it is:
If it shipped as -1 by default, that would break BC currently since some poorly written/age-old apps could still be using it. Best annoy them during the upgrade so they know to update their code then cover it up with -1 as default to just opt them into the new behavior without any notice.
Package maintainers may set the value to -1 by default since they are doing what they think is best for developers. Upstream is doing what their guidelines say, which is don't break BC as much as possible.
I suspect you have newlines in field values. fgets treats those as EOL indicators. Try fgetcsv with correct delimiters and escape chars set.
A good hexeditor can help you see what's going on.
> I think the namespace declaration has to be on the first line or something silly like that
Namespaces must be the first line of executable code outside of a declare
statement, but there is no whitespace (or comment) prohibition (edit: within a <?php
block. Non-PHP code, including whitespace, before the <?php
declaration is still prohibited). This is valid PHP:
<?php
// This is a comment namespace Purse;
use Jade;
I've sworn by LastPass for a long time now. Great with the YubiKey.
https://www.yubico.com/applications/password-management/consumer/lastpass/
However, I'm staying vigilant on their progression from them being recently bought out by LogMeIn. As long as LogMeIn doesn't screw with their process, it's my go to password manager and one I recommend.
It's best practice to expose as little PHP (or any other language) as possible, in case the handler doesn't parse it. In this case someone seems to have borked the php opening tag, but something else that's also likely is a botched software upgrade that results in Apache running without PHP. Now all .php files are served as plain text directly to the browser. This is especially true for low-budget shared hosting servers.
That's the reason why you'll want as little PHP in your publicly accessible directory. My index.php generally only consists of:
<?php
require_once '../application/Application.php';
So if for some reason the PHP file is served as-is, that's the only thing leaking out. The rest of the PHP code is outside of the publicly accessible document root directory.
This is also the layout that Zend Framework encourages.
Learn 5.
Best starting point would be Jeffrey Way's aforementioned Laracasts, in particular "Laravel 5 Fundamentals" followed by "Build Your Own App".
You're better off using php's crypt() function (either CRYPT_BLOWFISH or CRYPT_SHA*) than trying to roll your own.
This article is correct to use a salt, but standard hash functions like SHA are designed to be fast, which is the opposite of what you want - the longer it takes to generate a single password hash, the longer it takes to break the hash using a brute force guessing attack (if your DB was compromised and password hashes were stolen).
crypt() gets around this issue for the SHA series by running the SHA hash 5000 times - increasing the time to compute a single hash by 5000.
Use the $_SESSION superglobal variables. They're not deprecated. Only specific functions I found that were deprecated are:
session_register() (use the $_SESSION superglobal instead)
session_unregister() (use the $_SESSION superglobal instead) and
session_is_registered() (use the $_SESSION superglobal instead).
You can still use things like session_start() and all these functions apart from the ones above I mentioned.
Sessions are still critical for logins, they're not going away anytime soon.
array_walk can modify the values of the input array in place. It's particularly handy if you have several kinds of transformations you may want to use. array_walk_recursive is particularly handy if you need to touch every item in an array of arrays.
Don't use die() for code related errors. Instead: throw new Exception($errormessage)
The only time you should ever use die() is if you're writing shell scripts.
I see dbname being set in the constructor, but when do the address/user/password details get set? You'd be better off having the constructor call those, and having connect() set the dbname.
Your life might be a little bit easier if you rolled a singleton routine into this.
static $stored_connection;
static function Link() {
if (!self::$stored_connection) {
$d = new self();
$d->connect();
self::$stored_connection = $d;
}
return self::$stored_connection;
}
Since someone else is going to say it anyway, take a look at using PDO instead of the old PHP4 mysql_ functions. It makes classes like this obsolete.
When outputting data in HTML context i find the alternate syntax much more intuitive:
<div id="container"> <? foreach($guests as $person): ?> <span class="name"><?=$person->name?>></span> <span class="phone"><?=$person->phone?></span> <? endforeach ?> </div>
This has the added benefit of making the HTML more editable for someone not well versed in PHP. edit: syntax error
Bit shifting and bitwise operations will at least eliminate the string stuff:
$bools = [ ... ]; // Still a string, but think of it as an array of 8-bit unsigned ints. Basically what it is anyways $out = ''; // This will store the result of our bit building $tmp = 0; for ($i = 0; $i < count($bools); $i++) { // Bitwise OR the boolean value to the working byte. I'm not 100% certain what // would happen if you ORd a boolean to an int, hence the cast. I suspect it'd do this // behind the scenes anyways $tmp |= (int) $bools[$i];
// On every eighth bit, push the current int value as an 8-bit byte if ($i % 8 === 0 && $i > 0) { $out .= chr($tmp); $tmp = 0; }
// Otherwise, shift all the bits to the left one in preparation for the next value else { $tmp = $tmp << 1; } }
No doubt there's an even better way than what I've written (which may not even work), but I'd definitely recommend reading up on bitwise operations.
EDIT: Not really related to the above, but also the ternary operator.
For auto-numbered fields, the last insert ID goes into a per-connection "variable". The result of an INSERT/UPDATE/DELETE query is normally the number of records modified or a success/failure flag.
Some databases, such as MySQL, have functions to specifically retrieve the last insert ID. For example, mysqli_insert_id. You'll notice that this function takes a connection as a parameter. You can also get the last insert ID from inside SQL with the LAST_INSERT_ID() function (e.g. SELECT LAST_INSERT_ID()
).
Php has autoloading for exactly this purpose. One autoloader class can scan specified areas for the necessary files and load them without any extra code. Take a look at http://php.net/manual/en/language.oop5.autoload.php for more info.