January 3, 2019 in Tips and Tricks, Ubuntu
What’s the version of my OS?
|
January 3, 2019 in Tips and Tricks, Ubuntu
|
January 1, 2019 in MySql, Php, Tips and Tricks
What’s the difference between the include() and require()functions?
They both include a specific file but on require the process exits with a fatal error if the file can’t be included, while include statement may still pass and jump to the next step in the execution.
How can we get the IP address of the client?
This question might show you how playful and creative the candidate is because there are many options. $_SERVER["REMOTE_ADDR"]; is the easiest solution, but the candidate can write x line scripts for this question.
What’s the difference between unset() and unlink()
unset() sets a variable to “undefined” while unlink() deletes a file we pass to it from the file system.
What is the output of the following code:
$a = '1';
$b = &$a;
$b = "2$b";
echo $a.", ".$b;
What are the main error types in PHP and how do they differ?
In PHP there are three main type of errors:
include() a file that does not exist.require() a non-existent file.Understanding the error types is very important as they help developers understand what is going on during the development, and what to look out for during debugging.
What is the difference between GET and POST?
Understanding the fundamentals of the HTTP protocol is very important to have for a PHP developer, and the differences between GET and POST are an essential part of it.
How can you enable error reporting in PHP?
Check if “display_errors” is equal “on” in the php.ini or declare “ini_set('display_errors', 1)” in your script.
Then, include “error_reporting(E_ALL)” in your code to display all types of error messages during the script execution.
Enabling error messages is very important especially during the debugging process as one can instantly get the exact line that is producing the error and can see also if the script in general is behaving correctly.
What are Traits?
Traits are a mechanism that allows you to create reusable code in languages like PHP where multiple inheritance is not supported. A Trait cannot be instantiated on its own.
It’s important that a developer knows the powerful features of the language (s)he is working on, and Trait is one of such features.
Can the value of a constant change during the script’s execution?
No, the value of a constant cannot be changed once it’s declared during the PHP execution.
Can you extend a Final defined class?
No, you cannot extend a Final defined class. A Final class or method declaration prevents child class or method overriding.
What are the __construct() and __destruct() methods in a PHP class?
All objects in PHP have Constructor and Destructor methods built-in. The Constructor method is called immediately after a new instance of the class is being created, and it’s used to initialize class properties. The Destructor method takes no parameters.
Understanding these two in PHP means that the candidate knows the very basics of OOP in PHP.
How we can get the number of elements in an array?
The count() function is used to return the number of elements in an array.
Understanding of arrays and array related helper functions is important for any PHP developer.
How would you declare a function that receives one parameter name hello?
If hello is true, then the function must print hello, but if the function doesn’t receive hello or hello is false the function must print bye.
<?php
function showMessage($hello=false){
echo ($hello)?'hello':'bye';
}
?>
In this question, you can evaluate if the developer knows how to declare a function and how they would manage the fact of the parameter can or cannot be on the function call. You can also evaluate if the developer knows the if syntax and how to print text(echo function).
The value of the variable input is a string 1,2,3,4,5,6,7. How would you get the sum of the integers contained inside input?
<?php
echo array_sum(explode(',',$input));
?>
The explode function is one of the most used functions in PHP, so it’s important to know if the developer knows this function. There is no unique answer to this question, but the answer must be similar to this one.
Suppose you receive a form submitted by a post to subscribe to a newsletter. This form has only one field, an input text field named email. How would you validate whether the field is empty? Print a message "The email cannot be empty" in this case.
<?php
if(empty($_POST['email'])){
echo "The email cannot be empty";
}
?>
In this question, the candidate should be evaluated on his/her knowledge about forms management and validation. There is not unique answer for this question, but it must be similar to this one.
Suppose that you have to implement a class named Dragonball. This class must have an attribute named ballCount (which starts from 0) and a method iFoundaBall. When iFoundaBall is called, ballCount is increased by one. If the value of ballCount is equal to seven, then the message You can ask your wish is printed, and ballCount is reset to 0. How would you implement this class?
<?php
class dragonBall{
private $ballCount;
public function __construct(){
$this->ballCount=0;
}
public function iFoundaBall(){
$this->ballCount++;
if($this->ballCount===7){
echo "You can ask for your wish.";
$this->ballCount=0;
}
}
}
?>
This question will evaluate a candidate’s knowledge about OOP.
What are the 3 scope levels available in PHP and how would you define them?
Private – Visible only in its own class
Public – Visible to any other code accessing the class
Protected – Visible only to classes parent(s) and classes that extend the current class
This is important for any PHP developer to know because it shows an understanding that building applications is more than just being able to write code. One must also have an understanding about privileges and accessibility of that code. There are times protected variables or methods are extremely important, and an understanding of scope is needed to protect the integrity of the data in your application along with provide a clear path through the code.
What are getters and setters and why are they important?
Getters and setters are methods used to declare or obtain the values of variables, usually private ones. They are important because it allows for a central location that is able to handle data prior to declaring it or returning it to the developer. Within a getter or setter one is able to consistently handle data that will eventually be passed into a variable or additional functions. An example of this would be a user’s name. If a setter is not being used and the developer is just declaring the $userName variable by hand, you could end up with results as such: "kevin", "KEVIN", "KeViN", "", etc. With a setter, the developer can not only adjust the value, for example, ucfirst($userName), but can also handle situations where the data is not valid such as the example where "" is passed. The same applies to a getter – when the data is being returned, it can be modifyed the results to include strtoupper($userName) for proper formatting further up the chain.
This is important for any developer who is looking to enter a team-based / application development job to know. Getters and setters are often used when dealing with objects, especially ones that will end up in a database or other storage medium. Because PHP is commonly used to build web applications, developers will run across getters and setters in more advanced environments. They are extremely powerful yet not talked about very much. It is impressive if a developer shows that he/she knows what they are and how to use them early on.
What does MVC stand for and what does each component do?
MVC stands for Model View Controller.
The controller handles data passed to it by the view and also passes data to the view. It’s responsible for interpretation of the data sent by the view and dispersing that data to the appropriate models awaiting results to pass back to the view. Very little, if any business logic should be occurring in the controller.
The model’s job is to handle specific tasks related to a specific area of the application or functionality. Models will communicate directly with your database or other storage system and will handle business logic related to the results.
The view is passed data by the controller and is displayed to the user.
Overall, this question is worth knowing as the MVC design pattern has been used a lot in the last few years and is a very good design pattern to know. Even with more advanced flows that go down to repositories and entities, they still are following the same basic idea for the Controller and View. The Model is typically just split out into multiple components to handle specific tasks related to database data, business logic etc. The MVC design pattern helps draw a better understanding of what is being used, as a whole, in the industry.
How does one prevent the following Warning ‘Warning: Cannot modify header information – headers already sent’ and why does it occur in the first place?
The candidate should not output anything to the browser before using code that modifies the HTTP headers. Once the developer calls echoor any other code that clears the buffer, the developer can no longer set cookies or headers. That is also true for error messages, so if an error happens before using the header command and the INI directive display_errors is set, then that will also cause that error to show.
What are SQL Injections, how do you prevent them and what are the best practices?
SQL injections are a method to alter a query in a SQL statement send to the database server. That modified query then might leak information like username/password combinations and can help the intruder to further compromise the server.
To prevent SQL injections, one should always check & escape all user input. In PHP, this is easily forgotten due to the easy access to $_GET & $_POST, and is often forgotten by inexperienced developers. But there are also many other ways that users can manipulate variables used in a SQL query through cookies or even uploaded files (filenames). The only real protection is to use prepared statements everywhere consistently.
Do not use any of the mysql_* functions which have been deprecated since PHP 5.5 ,but rather use PDO, as it allows you to use other servers than MySQL out of the box. mysqli_* are still an option, but there is no real reason nowadays not to use PDO, ODBC or DBA to get real abstraction. Ideally you want to use Doctrine or Propel to get rid of writing SQL queries all together and use object-relational mapping which binds rows from the database to objects in the application.
What does the following code output?
$i = 016;
echo $i / 2;
The Output should be 7. The leading zero indicates an octal number in PHP, so the number evaluates to the decimal number 14 instead to decimal 16.
Why would you use === instead of ==?
If you would want to check for a certain type, like an integer or boolean, the === will do that exactly like one would expect from a strongly typed language, while == would convert the data temporarily and try to match both operand’s types. The identity operator (===) also performs better as a result of not having to deal with type conversion. Especially when checking variables for true/false, one should avoid using == as this would also take into account 0/1 or other similar representation.
What are PSRs? Choose 1 and briefly describe it.
PSRs are PHP Standards Recommendations that aim at standardising common aspects of PHP Development.
An example of a PSR is PSR-2, which is a coding style guide. More info on PSR-2.
What PSR Standards do you follow? Why would you follow a PSR standard?
One should folow a PSR because coding standards often vary between developers and companies. This can cause issues when reviewing or fixing another developer’s code and finding a code structure that is different from yours. A PSR standard can help streamline the expectations of how the code should look, thus cutting down confusion and in some cases, syntax errors.
Do you use Composer? If yes, what benefits have you found in it?
Using Composer is a tool for dependency management. The candidate can declare the libraries your product relies on and Composer will manage the installation and updating of the libraries. The benefit is a consistent way of managing the libraries depended on so less time is spent managing the libraries.
December 25, 2018 in Learning, Tips and Tricks
# 1.To use URL Alias you need to be running apache with mod_rewrite enabled.
# 2. In your opencart directory rename htaccess.txt to .htaccess.
# For any support issues please visit: http://www.opencart.com
Options +FollowSymlinks
# Prevent Directoy listing
Options -Indexes
# Prevent Direct Access to files
<FilesMatch “(?i)((\.tpl|\.ini|\.log|(?<!robots)\.txt))”>
Require all denied
## For apache 2.2 and older, replace “Require all denied” with these two lines :
# Order deny,allow
# Deny from all
</FilesMatch>
# SEO URL Settings
RewriteEngine On
# If your opencart installation does not run on the main web folder make sure you folder it does run in ie. / becomes /shop/
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteBase /
RewriteRule ^sitemap.xml$ index.php?route=extension/feed/google_sitemap [L]
RewriteRule ^googlebase.xml$ index.php?route=extension/feed/google_base [L]
RewriteRule ^system/download/(.*) index.php?route=error/not_found [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]
### Additional Settings that may need to be enabled for some servers
### Uncomment the commands by removing the # sign in front of it.
### If you get an “Internal Server Error 500” after enabling any of the following settings, restore the # as this means your host doesn’t allow that.
# 1. If your cart only allows you to add one item at a time, it is possible register_globals is on. This may work to disable it:
# php_flag register_globals off
# 2. If your cart has magic quotes enabled, This may work to disable it:
# php_flag magic_quotes_gpc Off
# 3. Set max upload file size. Most hosts will limit this and not allow it to be overridden but you can try
# php_value upload_max_filesize 999M
# 4. set max post size. uncomment this line if you have a lot of product options or are getting errors where forms are not saving all fields
# php_value post_max_size 999M
# 5. set max time script can take. uncomment this line if you have a lot of product options or are getting errors where forms are not saving all fields
# php_value max_execution_time 200
# 6. set max time for input to be recieved. Uncomment this line if you have a lot of product options or are getting errors where forms are not saving all fields
# php_value max_input_time 200
# 7. disable open_basedir limitations
# php_admin_value open_basedir none
<IfModule pagespeed_module>
ModPageSpeed on
ModPagespeedRewriteLevel CoreFilters
ModPagespeedEnableFilters prioritize_critical_css
ModPagespeedEnableFilters defer_javascript
ModPagespeedEnableFilters sprite_images
ModPagespeedEnableFilters convert_png_to_jpeg,convert_jpeg_to_webp
ModPagespeedEnableFilters collapse_whitespace,remove_comments
</IfModule>
## EXPIRES CACHING ##
<IfModule mod_expires.c>
#ExpiresActive On
#ExpiresByType image/jpg “access 1 year”
#ExpiresByType image/jpeg “access 1 year”
#ExpiresByType image/gif “access 1 year”
#ExpiresByType image/png “access 1 year”
#ExpiresByType text/css “access 1 month”
#ExpiresByType text/html “access 1 month”
#ExpiresByType application/pdf “access 1 month”
#ExpiresByType text/x-javascript “access 1 month”
#ExpiresByType application/x-shockwave-flash “access 1 month”
#ExpiresByType image/x-icon “access 1 year”
#ExpiresDefault “access 1 month”
</IfModule>
<IfModule mod_deflate.c>
# Compress HTML, CSS, JavaScript, Text, XML and fonts
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
AddOutputFilterByType DEFLATE application/x-font
AddOutputFilterByType DEFLATE application/x-font-opentype
AddOutputFilterByType DEFLATE application/x-font-otf
AddOutputFilterByType DEFLATE application/x-font-truetype
AddOutputFilterByType DEFLATE application/x-font-ttf
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE font/opentype
AddOutputFilterByType DEFLATE font/otf
AddOutputFilterByType DEFLATE font/ttf
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE image/x-icon
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/xml
# Remove browser bugs (only needed for really old browsers)
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
Header append Vary User-Agent
</IfModule>
<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>
December 22, 2018 in Tips and Tricks
You could install forever using npm like this:
# sudo npm install -g forever
And then start your application with:
# forever server.js
Or as a service:
# forever start server.js
Forever restarts your app when it crashes or stops for some reason. To restrict restarts to 5 you could use:
forever -m5 server.js
To list all running processes:
# forever list
Note the integer in the brackets and use it as following to stop a process:
# forever stop 0
Restarting a running process goes:
# forever restart 0
If you’re working on your application file, you can use the -w parameter to restart automatically whenever your server.js file changes:
# forever -w server.js
December 18, 2018 in MySql, Tips and Tricks
To use multiple databases in OpenCart (1.5.*), just update 3 files as given below:
//New DB
$newdb = new DB(NEWDB_DRIVER, NEWDB_HOSTNAME, NEWDB_USERNAME, NEWDB_PASSWORD, NEWDB_DATABASE);
change:
After these above steps we can access the new database by:
$this->newdb->query("SELECT * FROM ". NEWDB_PREFIX . "users");
December 18, 2018 in Laravel, MySql, Tips and Tricks
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database1 //database first
DB_DATABASE_OPENCART=database2 // database second
DB_USERNAME=root
DB_PASSWORD=aaaa@#2233
‘mysql’ => [
‘driver’ => ‘mysql’,
‘host’ => env(‘DB_HOST’, ‘localhost’),
‘port’ => env(‘DB_PORT’, ‘3306’),
‘database’ => env(‘DB_DATABASE’, ‘database1’),
‘username’ => env(‘DB_USERNAME’, ‘root’),
‘password’ => env(‘DB_PASSWORD’, ‘aaaa@#2233’),
‘charset’ => ‘utf8’,
‘collation’ => ‘utf8_unicode_ci’,
‘prefix’ => ”,
‘strict’ => false,
‘engine’ => null,
],
‘opencart’ => [
‘driver’ => ‘mysql’,
‘host’ => env(‘DB_HOST’, ‘localhost’),
‘port’ => env(‘DB_PORT’, ‘3306’),
‘database’ => env(‘DB_DATABASE_OPENCART’, ‘database2’),
‘username’ => env(‘DB_USERNAME’, ‘root’),
‘password’ => env(‘DB_PASSWORD’, ‘aaaa@#2233’),
‘charset’ => ‘utf8’,
‘collation’ => ‘utf8_unicode_ci’,
‘prefix’ => ”,
‘strict’ => false,
‘engine’ => null,
],
$db_ext = DB::connection(‘opencart’);
$countries = $db_ext->table(‘fit_cart’)->get();
print_r($countries);
December 15, 2018 in Tips and Tricks
Have you ever updated to the newest version of WordPress, and then noticed that your site starts to have a bunch of problems? Don’t freak out. A lot of the times, it’s an issue with a plugin or theme that’s not compatible with the newest update. Sometimes (rarely) there’s an issue with the WordPress update itself. Whatever the case, one of of the quickest solutions to bring your site back to normal is to downgrade WordPress back to the previous version.
Compatibility issues are one of the reasons I try to avoid plugins and themes that don’t get updated regularly. I don’t want to be stuck with an older version of WordPress just because one of my plugins or themes doesn’t work with the latest update. Before you go through the process of downgrading, I’d suggest checking to see if a plugin is what’s causing the issue. If it is, you can just disable the plugin until there’s an update for it. If it’s a problem with the theme though, that’s an entirely different story. That’s when you’ll want to consider downgrading your version of WordPress.
Before you downgrade, I’d highly recommend making sure you have a backup of your site just in case things don’t go as planned and everything gets screwed up. I’ve never run into an issue but I always have the feeling that the one time I downgrade and my site goes berserk, I won’t have a backup. There are tons of backup plugins for WordPress and your web host might/should be able to provide you with the latest backup they have.
The first thing you’re going to need is a previous WordPress release. You can download any of the previous WordPress versions here –> WordPress releases. Only downgrade down to the version before the newest one. Don’t go way back into the archives to version 1.1. Some of the older versions of WordPress have security issues that could put your site at risk.
Here’s how to downgrade WordPress to an older version.
After you’ve created a backup of your site and downloaded the WordPress version you want to downgrade to, it’s time to actually downgrade. The first thing you want to do is login to your WP Dashboard and deactivate all of your plugins.
After all your plugins have been deactivated, logout of WordPress.
This step will require that you have an FTP client. An FTP client allows you to access all of the files on your site. I use FireFTP from Firefox and FileZilla is another very popular option. Both are free and you can’t go wrong with either. The images in this tutorial are from FireFTP. In your FTP client, locate your WordPress files (wp-admin, wp-content, etc.). In FireFTP, they will be the first thing you see when you open your site’s folder.
Delete both the wp-admin and wp-includes folders. Do not touch the wp-content folder! You can leave all of the other files alone because you will overwrite them in the next step.
While you’re still in your FTP client, go into the folder where you have the WordPress version you want to downgrade to. Transfer over everything except the wp-contentfolder. After all the files have been transferred, your downgrade is finished.
Login to your WP Dashboard. You will be prompted to update your WordPress database. Click on “Update WordPress Database” and then click continue to login.
Once you’re logged in, you should see that you’re running whatever version of WordPress that you downgraded to. Congrats!
A word of caution. I don’t recommend using older versions of WordPress when newer ones are available. Like I said in the beginning, a lot of the updates come with security patches to stop known security threats that could leave your site open to hackers.
If your theme isn’t compatible with the most current version of WordPress, contact the theme developer and let them know. If there’s no support offered for your theme, then you’ll want to switch to a different one that’s updated on a regular basis.
I hope you found my guide helpful. If you have any questions, feel free to leave a comment below!
December 14, 2018 in MySql, News, Php, Tips and Tricks
In Mysql
SELECT from_unixtime(last_login_date)
FROM `user`
LIMIT 50
In Php
echo time();
echo strtotime($date[0]).”<br>”;
echo date(‘m/d/Y’, 1535104800);
December 4, 2018 in Tips and Tricks
This article will walk a user through the process of converting a .pfx file to a .crt and .key file so that the SSL certificate can be uploaded into the StackPath control panel.
A .pfx file is a PKCS#12 archive: a file that can contain a lot of objects with optional password protection; but, usually, a PKCS#12 archive has a certificate (possibly with its assorted set of CA certificates) attached to it and the corresponding private key.
Thats how .crt or .cer files differ from .pfx files – they contain a single certificate file, without any keys attached.
The StackPath portal requires that you upload the certificate and key in their separate corresponding fields and this is how you can extract them from your .pfx file.
Navigate to the terminal of your operating system and execute the following commands to extract the files:
Certificate:
{code}
openssl pkcs12 -in [yourfile.pfx] -clcerts -nokeys -out [certificate.crt]
{code}
Key:
{code}
openssl rsa -in [keyfile-encrypted.key] -out [keyfile-decrypted.key]
{code}
These two commands will generate two separate files which you can later use in your Stackpath SSL configuration.
December 1, 2018 in Tips and Tricks
We always stress the importance of a strong sending reputation. By keeping an eye on your engagement (opens, clicks TiNs, etc.) and reputation (spam complaints, spam traps, unknown users, etc.) metrics you’ll get a good picture of how your emails are being received by subscribers.
But if you’re looking for another measure of your reputation, you can take advantage of a handful of resources that will let you know where you stand. Here are 5 sites that will help you check your sending reputation and keep you on track:
Like a credit score, a Sender Score is a measure of your reputation. Scores are calculated from 0 to 100. The higher your score, the better your reputation and the higher your email deliverability rate. Numbers are calculated on a rolling 30-day average and illustrate where your IP address ranks against other IP addresses. This service is provided by Return Path.
Senderbase is a product of Cisco and provides you with the tools to check your reputation by ranking you as Good, Neutral, or Poor. Good means there is little or no threat activity. Neutral means your IP address or domain is within acceptable parameters, but may still be filtered or blocked. Poor means there is a problematic level of threat activity and you are likely to be filtered or blocked.
WatchGuard’s ReputationAuthority helps protect business and government organizations from unwanted email and web traffic that contain spam, malware, spyware, malicious code, and phishing attacks. You can look up your IP address or domain, receive a reputation score from 0-100, and get the percentage of emails that were good versus bad.

IP lookup for ReputationAuthority
Barracuda Networks provides both an IP and domain reputation lookup via their Barracuda Reputation System; a real-time database of IP addresses with “poor” or “good” reputations.
TrustedSource is a site very similar to senderbase.org, but run by McAfee. It provides information on both your domain’s email and web reputations as well as affiliations, domain name system (DNS), and mail server information. It also provides details on the history, activation, and associations of your domain.
Your email reputation is always in your control. By taking advantage of these resources, you can ensure that you’re being proactive about your email deliverability. But our delivery team likes to emphasize that while these reputation monitoring systems are a great help, they are not the authoritative metric by which you should determine the health of your entire email program.
They are best used as one data point (an important one) in an overarching holistic assessment of your email program. It is not uncommon to see senders with SenderScores around 98-99 that are still having inboxing problems, so it’s important to know that just because you get a high score on one of these sites, it doesn’t mean you won’t be getting throttled, sent to the spam folder, or blocked outright. So the more eyes and ears you can have on your IP and domain reputation the better.