Showing posts with label php problem solutions. Show all posts
Showing posts with label php problem solutions. Show all posts

## Saturday 18 April 2020

### How to check if a number is prime?

Question: What is Prime Number
A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers.

Question: Give the example of Prime Number
2, 3, 5, 7, 11, 13, 17, 19, 23 and 29.

Question: Write an function that check the prime number OR Not?
```function checkPrime(\$number){
if(\$number < 0 ){
return false;
}
\$return=true;
for(\$i=2; \$i < \$number; \$i++){
if(\$number % \$i ==0){
\$return=false;
break;
}
}
return \$return;
}
```

Question: How to check a number is prime Or Not?
```echo checkPrime(2)?'Prime':'Not Prime'; //Prime
echo checkPrime(4)?'Prime':'Not Prime'; //Not Prime
echo checkPrime(6)?'Prime':'Not Prime'; //Not prime
echo checkPrime(7)?'Prime':'Not Prime';  //Prime
```

Question: What are the prime numbers between 1 to 100?
```for( \$i = 2; \$i < 100; \$i++ ){
if( checkPrime( \$i ) ){
echo \$i;
echo ',';
}
}```

## Sunday 29 March 2020

### General error: 1364 Field city_id doesn't have a default value

I have upgraded the MySQL from 5.5 to 5.6 and then getting below type of errors.
General error: 1364 Field 'city_id' doesn't have a default value

(I was not getting such type of error, it must come after upgrading my MySQL Version from 5.5 to 5.6)

### Solution: It have 3 Solutions

1. In Your Code (PHP), always set a default value (if no value) before save.
```\$objSaveData->saveData(
array(
'id'=>111,
'name'=>'New user',
'city_id'=>0, //default value
);
);
```
2. Create fields with default values set in datatable. It could be empty string, which is fine for MySQL server running in strict mode.
like below:
```ALTER TABLE `users` CHANGE `city_id` `city_id` INT(10) UNSIGNED NOT NULL DEFAULT '0';
```
3. Disable MySQL Strict Mode (Most appropriate)
Disable it by setting your own SQL_MODE in the my.cnf file, then restart MySQL.

Look for the following line:
`sql-mode = "STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"`
Change it to:
`sql-mode="" `
Restart the MySQL Service.

## Saturday 21 December 2019

### What are special characters? and how to remove special characters?

Question: What are special characters?
Special characters are selected punctuation characters present on standard US keyboard.

Question: Provide list of special characters?
 Character Name Space ! Exclamation " Double quote # Number sign (hash) \$ Dollar sign % Percent & Ampersand ' Single quote ( Left parenthesis ) Right parenthesis * Asterisk + Plus , Comma - Minus . Full stop / Slash : Colon ; Semicolon < Less than = Equal sign > Greater than ? Question mark @ At sign [ Left bracket \ Backslash ] Right bracket ^ Caret _ Underscore ` Grave accent (backtick) { Left brace | Vertical bar } Right brace ~ Tilde

Question: How to remove special characters from string including space?
```\$string='test !@#ing';
echo preg_replace('/[^A-Za-z0-9\-]/', '', \$string);```

Question: How to remove special characters from string except space?
```\$string='test !@#ing';
echo preg_replace('/[^A-Za-z0-9\-\s]/', '', \$string);```

Question: How to replace special characters with hyphen?
```\$string='test !@#ing';
echo preg_replace('/[^A-Za-z0-9\-\s]/', '-', \$string);```

Question: How to replace multiple hyphen with single hyphen?
```\$string='test-----ing';
echo preg_replace('/-+/', '-',\$string);```

Question: How to remove special characters from array?
```\$array=array('test !@#ing','sdalkjsad','#\$#33');
function cleanData(\$string){
return preg_replace('/[^A-Za-z0-9\-]/', '', \$string);
}
\$array = array_map('cleanData',\$array);
print_r(\$array);```

Question: How to remove all special characters from javascript?
```var stringToReplace='test !@#ing';
stringToReplace=stringToReplace.replace(/[^\w\s]/gi, '')```

## Thursday 12 December 2019

### How to resize images in php

Function resizeImage
```
/**
*
* @param type \$width
* @param type \$height
* @param type \$mode
* @param type \$imageName
* @param type \$extension
* @return string
*/
function resizeImage(\$width, \$height, \$mode, \$imageName,\$extension) {
\$docRoot = getenv("DOCUMENT_ROOT");

/* Get original image x y */
\$tmpNM = \$_FILES['files']['tmp_name'];

list(\$w, \$h) = getimagesize(\$_FILES['files']['tmp_name']);
/* calculate new image size with ratio */
\$ratio = max(\$width / \$w, \$height / \$h);
\$h = ceil(\$height / \$ratio);
\$x = (\$w - \$width / \$ratio) / 2;
\$w = ceil(\$width / \$ratio);
/* new file name */
if (\$mode == 'userphoto') {
\$path = \$docRoot . '/upload/userphoto/' . \$imageName;
}

/* read binary data from image file */
\$imgString = file_get_contents(\$_FILES['files']['tmp_name']);
/* create image from string */
\$image = imagecreatefromstring(\$imgString);
\$tmp = imagecreatetruecolor(\$width, \$height);
imagecopyresampled(\$tmp, \$image, 0, 0, \$x, 0, \$width, \$height, \$w, \$h);
\$fileTypes = array('jpg', 'jpeg', 'jpe', 'png', 'bmp', 'gif'); // File extensions
/* Save image */
\$extension = strtolower(\$extension);
switch (\$extension) {
case 'jpg':
case 'jpeg':
case 'jpe':
imagejpeg(\$tmp, \$path, 100);
break;
case 'png':
imagepng(\$tmp, \$path,0);
break;
case 'gif':
imagegif(\$tmp, \$path, 100);
break;
case 'bmp':
imagewbmp(\$tmp, \$path);
break;
default:

exit;
break;
}
return \$path;
/* cleanup memory */
imagedestroy(\$image);
imagedestroy(\$tmp);
}    ```

How to use Code
HTML Code

```<form action="upload.php" enctype="multipart/form-data" method="post">
<input id="image upload" name="files" type="file" />
<input name="submit" type="submit" value="Upload Image" />

```

PHP Code
```
//List of thumbnails
\$sizes = array(200 => 200, 150 => 150);

\$files=array();
if (!empty(\$_FILES)) {
//Clean the image name
\$_FILES['files']['name'] = preg_replace('/[^a-zA-Z0-9_.-]/', '', strtolower(trim(\$_FILES['files']['name'])));

//Temporary file, type, name
\$tmpNM = \$_FILES['files']['tmp_name'];
\$imageType = \$_FILES['files']['type'];
\$imageName = \$_FILES['files']['name'];

//Get image extension
\$imageNameType = explode(".", \$_FILES['files']['name']);

\$fileMimeTypes = array('image/jpeg', 'image/png', 'image/bmp', 'image/gif'); // mime  extensions
\$fileTypes = array('jpg', 'jpeg', 'jpe', 'png', 'bmp', 'gif'); // File extensions

if (in_array(strtolower(\$imageNameType[1]), \$fileTypes)) {
\$fullImageName = time('his') . '_' . \$_FILES['files']['name'];
foreach (\$sizes as \$w => \$h) {
\$files[] = \$this->resizeImage(\$w, \$h, 'userphoto', "{\$w}_{\$fullImageName}", \$imageNameType[1]);
}

}
}```

## Saturday 7 December 2019

### How to Validate email address in PHP?

Following are in built PHP function to validate the email address and Ip Address.

Validate Email - Example 1
```\$email='helo@gmail.com';
if (!filter_var(\$email, FILTER_VALIDATE_EMAIL)) {
echo \$email. ' - Invalid';
}else{
echo \$email. ' - Valid';
}
```

helo@gmail.com - Valid

Validate Email - Example 2
```\$email='464646@gmail.com';
if (!filter_var(\$email, FILTER_VALIDATE_EMAIL)) {
echo \$email. '- Invalid';
}else{
echo \$email. ' - Valid';
}
```

464646@gmail.com - Valid

Validate Email - Example 3
```\$email='arunkumar.com';
if (!filter_var(\$email, FILTER_VALIDATE_EMAIL)) {
echo \$email. ' - Invalid';
}else{
echo \$email. ' - Valid';
}

```

arunkumar.com - Invalid

Validate IP Address - Example 1
Question: How to Validate IP Address?
```\$ipAddress = '127.0.0.1';
}else{
}
```

127.0.0.1 is Valid

Validate IP Address - Example 2
```\$ipAddress = '127.test.0.0.1';
}else{
}
```

127.test.0.0.1 is Valid

Validate URL - Example 1
```\$ipAddress = '127.test.0.0.1';
\$website = 'https://www.web-technology-experts-notes.in';
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",\$website)) {
echo   "Invalid URL";
}else{
echo   "Valid URL";
}
```

Valid URL

## Saturday 9 November 2019

### Git interview questions and answers - Problem and Solutions

Question: How to delete a Git branch both locally and remotely?
To remove a local branch from your local system.
`git branch -d the_local_branch`

To remove a remote branch from the server.
`git push origin :the_remote_branch`

Question: How do you undo the last commit?
`git revert commit-id`

Question: How to Edit an incorrect commit message in Git?
`git commit --amend -m "This is your new git message"`

Question: What are the differences between 'git pull' and 'git fetch'?
Git pull automatically merges the commits without letting you review them first.
Git fetch stores them in your local repository but it not merge them with your current branch.
git fetch similar to guit pull but it does not merge the changes.

Question: How do you rename the local branch?
`git branch -m oldBranchName newBranchName`

Question: How do I remove local files (Not in Repo) from my current Git branch?
`git clean -f -n`

Question: How to Checkout remote Git branch?
`git checkout test`

Question: How do I remove a Git submodule?
```git rm the_submodule
rm -rf .git/modules/the_submodule```

Question: How do you create a remote Git branch?
```git checkout -b your_branch_name
git push -u origin your_branch_name```

Question: How to Change the URL for a remote Git repository?
`git remote set-url origin git://this.is.new.url`

Question: How to Change the author of a commit in Git?
`git filter-branch -f --env-filter "GIT_AUTHOR_NAME='NewAuthorName'; GIT_AUTHOR_EMAIL='authoremail@gmail.com'; GIT_COMMITTER_NAME='CommiterName'; GIT_COMMITTER_EMAIL='committergmail@gmail.com';" HEAD`

Question: What is .gitignore?
.gitignore tells git which files/folder should be ignore.
Create a file with name of .gitignore in root.
temporay files, system files, hidden files or local downloaded modules we can add in .gitignore file, so that git will not added this.

Question: How do I delete a Git branch locally?
`git branch -d {the_local_branch}`

Question: How do I delete a Git branch remotely?
`git push origin --delete {the_remote_branch}`
(use -D instead to force deleting the branch without checking merged status)

Question: What is the difference between git pull and git fetch?
git pull does a git fetch followed by a git merge.

Question: How do I undo git add before commit?
`git reset file.php`

Question: How do I rename a local Git branch?
```git branch -m oldname newname
```

Question: How do I discard unstaged changes in Git?
```git stash save --keep-index --include-untracked
```

You don't need to include --include-untracked if you don't want to be thorough about it.
After that, you can drop that stash with a git stash drop command if you like.

## Tuesday 13 August 2019

### How do I add environment variables in Unix

Question: How to print the environment values?
`printenv`

OR
`env`

Question: How to SET the environment values For Korn shell (KSH)?
```var=value
export varname```

Question: How to SET the environment values For Bourne shell (sh and bash)?
`export var=value`

Question: How to SET the environment values For C shell (csh or tcsh)?
`setenv var value`

Question: What is .bashrc?
.bashrc is a shell script that Bash runs whenever it is started interactively.

Question: Can we set the environment value in .bashrc?
Yes, you can set the value in this also. like below
`export PATH="\$PATH:/some/addition"`

## Friday 23 February 2018

### PHP Redirect, 301 or 302 Redirection With PHP and benefits

Question: What is Redirection?
On a Web site, redirection is a technique for moving visitors to a different web page OR Different website.

Question: Why we do need redirection?
We do need redirection, because we want to tell the visitor that current page is not appropriate for you or current page have been moved to new location.

Following are different reason, we do Redirection
1. If user already login, and try to open the login page redirect him to user dashboard.
2. Trying to access a page which is temporary not available.
3. If user trying to access un-authorized page, Redirect him to user dashboard.
4. Tring to access non-exist page, redirect him sitemap page OR 404 page.
5. Trying to access non-exist website.

Question: What are different type of redirects?
1. 301 permanent redirects
2. 302 temporary redirects

Question: What is 301 permanent redirect?
301 code refers to the HTTP status code.
A 301 redirect is a permanent redirect which passes between ranking power(>90%) to the redirected page.

Question: When we use 301 redirects?
1. When a web page permanently removed, we redirect user to new page.
2. When we want to transfer the ranking benefits(SEO point of view) to new web page.
3. Redirect user to new web page and stopped him to access old page(not available page).
4. If you have updated the contents to new web page, MUST USE 301 Redirects
5. 301 indicates to both browsers and search engine bots(Google, bing, yahoo) that the page has moved permanently.

Question: What is 302 temporary redirects?
302 refers to the HTTP status code.
A 302 redirect is a temporary redirect. We have to tell user its temporary unavailable and will be available very soon.

Question: When we use 302 redirects?
1. If user already login, and try to open the login page redirect him to user dashboard.
2. Trying to access a page which is temporary not available.
3. If user trying to access un-authorized page, Redirect him to user dashboard.

Question: How to make 301 redirect with php (Permanent)?
`header('Location: http://www.example.com/new-web-page.php', true, 301);exit;`

Question: How to make 302 redirect with php (Temp)?
`header('Location: http://www.example.com/new-web-page.php', true, 302);exit;`

OR
`header('Location: http://www.example.com/new-web-page.php');exit;`

Both are same and works same.

Question: Can we use regular express in Redirection?
Yes, See Example:
```if(preg_match("/^\/old\./", \$_SERVER['REQUEST_URI'], \$m)){
}```

Question: Give an URL to check 301 redirects?

Question: Where can I test redirect online? http://www.redirect-checker.org/index.php
(Check Your Redirects and Statuscode 301 vs 302, meta refresh & javascript redirects)

Question: How to make 301 redirect with htaccess?
`Redirect 301 /old/ /new/`

Make Sure "RewriteEngine On" and installed "mod_rewrite" on server.

Question: How to make 302 redirect with htaccess?
`Redirect 302 /old/ /new/`

Make Sure "RewriteEngine On" and installed "mod_rewrite" on server.

Question: What are different HTTP status code used in web?
301 - Permanent movement(redirection)
302 - Temporary movement(redirection)
401 - Authorization Required
For More details http://www.web-technology-experts-notes.in/2014/02/htaccess-code-snippets-example.html

## Wednesday 6 September 2017

### jQuery multi column sorting with jQuery - Live Demo

tablesorter is a jQuery plugin used for turning a standard HTML table with THEAD and TBODY tags into a sortable table without page refreshes also no ajax call. tablesorter can successfully parse and sort many types of data including linked data in a cell. It has many useful features including:
• Multi-column sorting
• Parsers for sorting text, URIs, integers, currency, floats, IP addresses, dates (ISO, long and short formats), time. Add your own easily
• Support secondary "hidden" sorting (e.g., maintain alphabetical sort when sorting on other criteria)
• Extensibility via widget system
• Cross-browser: IE 6.0+, FF 2+, Safari 2.0+, Opera 9.0+
• Small code size

### How to Select / Deselect All Checkboxes using jQuery

If you are developer and looking for a jQuery code-snippet that selects and de-selects multiple checkboxes by clicking “Select All” checkbox, like in Gmail.com, rediffmail.com and yahoo.com. Then you are at right place.

This is very simple and most commonly used in web application and specially its used where there is multiple record listing.

In Admin section,  this functionality is needed in every page, like User Listing, Product Listing, Album Listing  & images listing etc.

When selected "Select All" checkbox, It will select all the checkbox under the main checkbox.
If you de-select the "Select All", It will de-select all the checkbox under this main checkbox.

You can use below code and do the modification as per your requirement. This code is very useful not just in current web application but also for future.

select all checkbox jquery DEMO
```

jQuery('#checkbox_all').click(function(){

if(\$(this).is(":checked")){
jQuery('input[type="checkbox"].chk').each(function(){

jQuery(this).prop("checked",true);

});

}else{

jQuery('input[type="checkbox"].chk').each(function(){

jQuery(this).prop("checked",false);

});

}

});

});

Select All

Name2

Name3

Name4

Name5

Name6

```
Code Snippet
```<script src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script type="text/javascript">

jQuery('#checkbox_all').click(function(){

if(\$(this).is(":checked")){
jQuery('input[type="checkbox"].chk').each(function(){

jQuery(this).prop("checked",true);

});

}else{

jQuery('input[type="checkbox"].chk').each(function(){

jQuery(this).prop("checked",false);

});

}

});

});

</script>
<table border="1" rules="groups" style="width: 200pxpx;">
<tbody>
<tr>

<th><input id="checkbox_all" name="checkbox" type="checkbox" /></th>

<th>Select All</th>

</tr>
<tr>

<td><input class="chk" name="checkbox" type="checkbox" /></td>

<td>Name2</td>

</tr>
<tr>

<td><input class="chk" name="checkbox" type="checkbox" /></td>

<td>Name3</td>

</tr>
<tr>

<td><input class="chk" name="checkbox" type="checkbox" /></td>

<td>Name4</td>

</tr>
<tr>

<td><input class="chk" name="checkbox" type="checkbox" /></td>

<td>Name5</td>

</tr>
<tr>

<td><input class="chk" name="checkbox" type="checkbox" /></td>

<td>Name6</td>

</tr>
</tbody></table>

```

## Thursday 18 August 2016

### How to get visitor location with JavaScript ?

Today there are lots Free/Paid API avaiable which give you client information.
Following are two example which give you client information like city, country, country code, ip, local date time, timezone etc with javascript.
Question: How to get visitor location javascript with freegeoip.net?
```<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
\$.getJSON("http://freegeoip.net/json/", function(result){
console.log(result);

});
});
```

Output
```{  "ip": "112.196.3.177",
"country_code": "IN",
"country_name": "India",
"region_code": "PB",
"region_name": "Punjab",
"city": "Mohali",
"zip_code": "",
"time_zone": "Asia/Kolkata",
"latitude": 30.78,
"longitude": 76.69,
"metro_code": 0
}```

Question: How to get visitor location javascript with ipinfo.io?
```
<script>
\$.getJSON('http://ipinfo.io', function(data){
console.log(data)
})
});
</script>
```

Output
```  {"ip": "112.196.3.177",
"hostname": "No Hostname",
"city": "Mohali",
"region": "Punjab",
"country": "IN",
"loc": "30.7800,76.6900",
}```

## Wednesday 10 August 2016

Question: How to make twitter bootstrap menu dropdown on hover rather than click?
```ul.nav li.dropdown:hover > ul.dropdown-menu {
display: block;
}```

Question: How can I make Bootstrap columns all the same height??
```.row {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
flex-wrap: wrap;
}
.row > [class*='col-'] {
display: flex;
flex-direction: column;
}
```

Question: What is sr-only in Bootstrap 3??
It is class used to hide information intended only for screen readers from the layout of the rendered page.

Question: How to disallow twitter bootstrap modal window from closing?
`<a data-backdrop="static" data-controls-modal="my_div_id" data-keyboard="false" href="https://www.blogger.com/blogger.g?blogID=5911253879674558037#"></a>`

Question: What are different 4 tiers in twitter bootstrap?
1. Extra small devices like smartphones (.col-xs-*)
2. Small devices like tablets(.col-sm-*)
3. Medium devices like laptops (.col-md-*)
4. large devices like laptops/desktops(.col-lg-*)

Question: How to use media queries in twitter bootstrap 3?
```@media(max-width:767px){}
@media(min-width:768px){}
@media(min-width:992px){}
@media(min-width:1200px){}```

Question: How to use media queries in twitter bootstrap 4?
```@media(min-width:34em){}
@media(min-width:48em){}
@media(min-width:62em){}
@media(min-width:75em){}```

Question: What is an em?
An em is a unit in the field of typography, One em is equal to the 16 point size.

Question: How to open a Bootstrap modal?
```\$('#myModalId').modal('toggle');
\$('#myModalId').modal('show');
\$('#myModalId').modal('hide');
```

Question: How to make responsive image with align center?
```.img-responsive {
margin: 0 auto;
}
```

Question: How to create Confirm box before deleting modal/dialog?
```
<a data-href="/delete-rec?id=203" data-target="#confirm-delete-id" data-toggle="modal" href="https://www.blogger.com/blogger.g?blogID=5911253879674558037#">Delete record #203</a>
```

```<div aria-hidden="true" aria-labelledby="myModalLabel" class="modal fade" id="confirm-delete-id" role="dialog" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button class="btn btn-default" data-dismiss="modal" type="button">Cancel</button>
<a class="btn btn-danger btn-ok" href="https://www.blogger.com/null">Delete</a>
</div>
</div>
</div>
</div>

```

Question: How to disabled the button?
```\$('#buttonId').prop('disabled', true);
```

## Wednesday 15 June 2016

### How to convert image to base64 encoding?

Question: How to convert image to base64 encoding?
```\$path = 'https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLFLf9nQIN5wxoF75u0dsWuC7yhk4CjYze033kBDarmAYFoIaOg88NdSy68HbVS4NRBrVbp94kgZ5b39hf1JpD5xf9DhM2ZrJ7qIrErySknjs17Fg_oHiPnmWUh2P4yEuASsxzD1b228Wo/s1600/Hosted+Field+Integration+-+Braintree.png';
\$imageType = pathinfo(\$path, PATHINFO_EXTENSION);
\$imageData = base64_encode(file_get_contents(\$path));
echo \$binaryData = 'data:image/' . \$imageType . ';base64,' . \$imageData;
```

Output
```
```