PHP random string generator function

Jimmy Wales Reply 15:46
function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomStringValue = '';
    for ($i = 0; $i < $length; $i++) {
        $randomStringValue .= $characters[rand(0, strlen($characters) - 1)];    }
    return $randomStringValue ;}
Output the random string :-
// Echo the random string.
echo generateRandomString(); 

Displaying database records in unordered list format

Jimmy Wales Reply 09:52
Just keep a counter, increment it in the loop, and if it's an odd number set class to odd, if even set class to even. 
$result  = "";
$count = -1;

while ( $row = mysql_fetch_assoc( $query) ) {
  $class = $count++ % 2 === 0 ? "even" : "odd" ;
  $href  = $row["url"];
  $text  = $row["name"];
  $output .= "<li class='{$class}'><a href='foo?id={$href}'>{$name}</a></li>";
}

echo "<ul>{$result}</ul>";

Redirect to another url when back button is clicked using javascript

Jimmy Wales Reply 17:02
you can try this to redirect your own url when clicking browser back button


<script>
jQuery(document).ready(function($) {

      if (window.history && window.history.pushState) {

        $(window).on('popstate', function() {
          var hashLocation = location.hash;
          var hashSplit = hashLocation.split("#!/");
          var hashName = hashSplit[1];

          if (hashName !== '') {
            var hash = window.location.hash;
            if (hash === '') {
              alert('Back button was pressed.');
                window.location='www.yourweburlhere.com';
                return false;
            }
          }
        });

        window.history.pushState('forward', null, './#forward');
      }

    });
</script>

Form validation of numeric characters

Jimmy Wales Reply 15:20
You need to test for the negation of the Regular Expressions because you want the validation to alert upon failure,

(is_valid = !/^[0-9]+$/.test(x))
Example :-

<form action="" method="POST" name="cdp_form" id="cdp_form">
<input type="text" id="phone_number" name="phone_number" placeholder="Enter your phone number" maxlength="10" onkeyup="validateForm()">
<button type="submit" name="SEND" class="btn btn-brown">Send</button>
</form>
<?php echo $successmsg; ?>
<script>
//form validation
function validateForm()
{
var x=document.forms["cdp_form"]["phone_number"].value
if (x==null || x=="")
  {
  alert("Phone number  field must be filled in");
  cdp_form.phone_number.focus();
  return false;
  }
else if (is_valid = !/^[0-9]+$/.test(x))
    {
    alert("Phone number field must have numeric characters");
    cdp_form.phone_number.focus();
    return false;
  }
}
</script>

Split date string in PHP

Jimmy Wales Reply 11:56
split - Split string into array by regular expression

for Example :
Parse a Date which may b delimited with dots, hypens or slashes-

<?php
//store your date in $date variable
$date = "04-24-2014";
list($month, $day, $year) = split('[/.-]', $date);
echo "Month: $month; Day: $day; Year: $year<br />\n";
?>

2nd Example :-

<?php
//store your date in $date variable
$date = "04-24-2014";
list($month, $day, $year) = split('[/.-]', $date);

//  - convert number to month name
$monthNum  = $month;
$monthName = date('F', mktime(0, 0, 0, $monthNum, 10)); // March
echo $monthName .' '.$day .', '. $year ;
?>






Scroll to the Bottom and Top of a page with jQuery

Sangwan Pankaj Reply 12:12


This Javascript code will scroll the page bottom
$('html, body').animate({scrollTop:$(document).height()}, 'fast'); 
and change your speed as required in numerical or slow , fast. Here we use fast in example
And create jQuery function 
$(document).ready(function() {     
 $('#yourId').click(function(){
       $('html, body').animate({scrollTop:$(document).height()}, 'fast');
        return false;  });
}); 
And for body part 
Use a link to an anchor tag e.g. <div id="yourId"> or <a href="#yourId"> 
Put this code in Header part:-
(Complete Code)
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
 function bottomScroll() {
  $('html, body').animate({scrollTop:$(document).height()}, 'fast');
 }
 function topScroll() {
  $('html, body').animate({scrollTop:0}, 'fast');
 }
</script>
 
Put this code in Header part:-

 <a href="javascript:bottomScroll()">Bottom Scroll</a>
 <a href="javascript:topScroll()">Top Scroll</a> 
 



Multiple selection of Drop down listbox onChange

Sangwan Pankaj Reply 10:18

Multiple selection of a drop down listbox by using onChange event trigger. 
HTML CODE
<select id=p1 name=no_year onChange="show_month()"; multiple size=4><option value=Jan>January</option>
<option value=February>February</option>
<option value=March>March</option>
<option value=April>April</option>
<option value=June>June</option>
<option value=Jul>July</option>
<option value=Auguest>Auguest</option>
<option value=September>Septembr</option>
<option value=October>October</option>
<option value=November>November</option>
<option value=December>December</option>
</select>
<div id='getValue'><br><br></div>

JAVASCTIPT
<script type="text/javascript">
function show_month(){
var str='';
for (i=0;i<p1.length;i++) {
if(p1[i].selected){
str +=p1[i].value + "<br >";
}
}
document.getElementById("getValue").innerHTML=str;
return true;
}
</script>

Single selection of Drop down listbox onChange

Sangwan Pankaj Reply 10:14
Today's topic is :- The selected option of a drop down listbox by using onChange event trigger. The onChange event will trigger 1 JavaScript function and we will try to read the selected item by using getElementById

Option 1:-
HTML CODE
<select>
    <option value="1">pankaj</option>
    <option value="2">sangwan</option>
</select>
JAVASCTIPT
$('select').on('change', function() {
  alert( this.value ); // output of your selected value

})

Option 2:-
HTML CODE
<select id="mySelect" onchange="copy();">
<option value="">Select a person:</option>
    <option value="pankaj" >pankaj</option>
    <option value="gurinder" >gurinder</option>
    <option value="avneet" >avneet</option>
    <option value="John Smith" >John Smith</option>
</select>
//value shows in here
<div id="label"></div>

JAVASCTIPT
function copy() { document.getElementById("label").innerHTML=document.getElementById("mySelect").value

}


Option 3:-
HTML CODE

<label for="continent">Select Continent</label>
  <select id="continent" onchange="countryChange(this);">
    <option value="empty">Select a Continent</option>
    <option value="North America">North America</option>
    <option value="South America">South America</option>
    <option value="Asia">Asia</option>
    <option value="Europe">Europe</option>
  </select>
  <br/>
  <label for="country">Select a country</label>
  <select id="country">
    <option value="0">Select a country</option>

  </select>

JAVASCTIPT
<script type="text/javascript">
 //<![CDATA[
 // array of possible countries in the same order as they appear in the country selection list
 var countryLists = new Array(4)
 countryLists["empty"] = ["Select a Country"];
 countryLists["Asia"] = ["India", "China", "Japan", "Nepal"];
 countryLists["North America"] = ["Canada", "United States", "Mexico"];
 countryLists["South America"] = ["Argentina", "Chile", "Brazil"];
 countryLists["Europe"]= ["Spain", "France", "Germany", "Britain"];

 function countryChange(selectObj) {
 // get the index of the selected option
 var idx = selectObj.selectedIndex;
 // get the value of the selected option
 var which = selectObj.options[idx].value;
 // use the selected option value to retrieve the list of items from the countryLists array
 cList = countryLists[which];
 // get the country select element via its known id
 var cSelect = document.getElementById("country");
 // remove the current options from the country select
 var len=cSelect.options.length;
 while (cSelect.options.length > 0) {
 cSelect.remove(0);
 }
 var newOption;
 // create new options
 for (var i=0; i<cList.length; i++) {
 newOption = document.createElement("option");
 newOption.value = cList[i];  // assumes option string and value are the same
 newOption.text=cList[i];
 // add the new option
 try {
 cSelect.add(newOption);  // this will fail in DOM browsers but is needed for IE
 }
 catch (e) {
 cSelect.appendChild(newOption);
 }
 }
 }
//]]>

</script>



Test Credit Card Account Numbers for Test Payments

Sangwan Pankaj Reply 12:58

Test Credit Card Account Numbers

While testing, use only the credit card numbers listed here. Other numbers produce an error.
Expiration Date must be a valid date in the future (use the mmyy format). for ex:- may 2018 and use cvv - 123

Test Credit Card Account Numbers

Credit Card Type
Credit Card Number
American Express
378282246310005
American Express
371449635398431
American Express Corporate
378734493671000
Australian BankCard
5610591081018250
Diners Club
30569309025904
Diners Club
38520000023237
Discover
6011111111111117
Discover
6011000990139424
JCB
3530111333300000
JCB
3566002020360505
MasterCard
5555555555554444
MasterCard
5105105105105100
Visa
4111111111111111
Visa
4012888888881881
Visa
4222222222222
Note : Even though this number has a different character count than the other test numbers, it is the correct and functional number.
Processor-specific Cards
Dankort (PBS)
76009244561
Dankort (PBS)
5019717010103742
Switch/Solo (Paymentech)
6331101999990016

Upload and fetch images from database (Mysql) in PHP

Sangwan Pankaj Reply 22:09
<html>
<body>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<input type="file" name="file" >
<input type="submit" name="submit" value="Upload">
</form>
</body>
</html>

<?php
$host = 'localhost';
$user = 'root';
$pw = '';
$db = 'Database name';

$con = mysql_connect($host,$user,$pw);
mysql_select_db($db, $con);

if(@$_POST['submit'])
{
    $query=null;
   
    $file = $_FILES['file'];
    $file_name = $file['name'];   
    $file_type = $file['type'];   
    $file_size = $file['size'];
    $file_path = $file['tmp_name'];   

    if($file_name!="" && ($file_type="image/jpeg"|| $file_type="image/png"|| $file_type="image/gif") && $file_size<=1048576) {
    if(move_uploaded_file($file_path,'images/'.$file_name)){
        $query = " INSERT INTO `tablename`(`id`, `name`, `image`) VALUES('','$file_name','images/$file_name')";
          $res = mysql_query("$query");
          if($res == 'true')
          {
              echo "File uploaded!";
           }
        }
      }
     }       
        echo '</br>';
        // Fetch data from database and show on front page. If you want to show in different page just copy the below code and paste on that page

        $result = mysql_query("SELECT * FROM `tablename`");       
        while ($row = mysql_fetch_array($result)) {
        echo "<img src='".$row['image']."' height='150px' width='250px'></br>";       
        }   
    ?>

MyISAM storage engine of MYSQL

Sangwan Pankaj Reply 17:12
MyISAM was the default storage engine for the MySQL relational database management system versions prior to 5.5. It is based on the older ISAM code but has many useful extensions.
Each MyISAM table is stored on disk in three files. The files have names that begin with the table name and have an extension to indicate the file type. The data file has a .MYD (MYData) extension,  index file has a .MYI (MYIndex) extension & uses a .frm file to store the definition of the table, but this file is not a part of the MyISAM engine; instead it is a part of the server.

In a simple way :-

MYISAM supports Table-level Locking
MyISAM designed for need of speed
MyISAM does not support foreign keys hence we call MySQL with MYISAM is DBMS
MyISAM stores its tables, data and indexes in diskspace using separate three different files. (tablename.FRM, tablename.MYD, tablename.MYI)
MYISAM not supports transaction. You cannot commit and rollback with MYISAM. Once you issue a command it’s done.
MYISAM supports fulltext search
You can use MyISAM, if the table is more static with lots of select and less update and delete.

( Storage engine :- A database engine (or storage engine) is the underlying software component that a database management system (DBMS) uses to create, read, update and delete (CRUD) data from a database. Most database management systems include their own application programming interface (API) that allows the user to interact with their underlying engine without going through the user interface of the DBMS. )

Basic functions generally used in WordPress

Sangwan Pankaj Reply 01:31


1. is_page() :- Condition for check if page is displayed. Its return true or false.
2.
is_category() :- Condition for check if category is displayed. Its return true or false. 
3. wp_nav_menu() :- Enabling WordPress 3.0′s Navigation Menu Feature 
4. wp_list_pages() :- Listing All Pages in wordpress
5.
get_excerpt() :- Displays the excerpt of the current post with read more link for display full post. 
6. bloginfo(‘url’) :- Getting the Site’s URL
7. bloginfo(‘template_url’) :- Getting the URL to the Current Theme
8. the_content():- Displays the contents of the current post. 
9. the_title():- Displays the title of the current post.
10.the_time():- Display the time the post was published (uses PHP date formatting as a parameter)





Disable Wordpress Updates

Sangwan Pankaj 1 11:59
To disable the update in WordPress
First open functions.php file and write these lines in functions.php of your theme folder.

To Disable Core Updates of Wordpress
add_filter( ‘pre_site_transient_update_core’, create_function( ‘$a’, “return null;” ) );
wp_clear_scheduled_hook( ‘wp_version_check’ );

To Disable Theme Updates
remove_action( ‘load-update-core.php’, ‘wp_update_themes’ );
add_filter( ‘pre_site_transient_update_themes’, create_function( ‘$a’, “return null;” ) );
wp_clear_scheduled_hook( ‘wp_update_themes’ );

To Disable Plugin Updates
remove_action( ‘load-update-core.php’, ‘wp_update_plugins’ );
add_filter( ‘pre_site_transient_update_plugins’, create_function( ‘$a’, “return null;” ) );
wp_clear_scheduled_hook( ‘wp_update_plugins’ ); 
That it!

Install Opencart with easy steps

Sangwan Pankaj 1 18:54
Install Opencart with easy steps

Click on this link to download opencart setup file Download Opencart  download a stable version of opencart.
after download opencart rar file extract setup file.
copy opencart folder to your www folder.
run wamp server make sure it will show green icon at right side  in taskbar of your window or if you are using xamap active mysql apache services.
open http://localhost in your browser address bar and find your opencart folder which moved or extracted in www folder.
then run opencart setup on clicking upload folder or which name you given to folder.
step1 ==> agree to opencart license and click continue.
step2 ==> step 2 wil appear now it show you services list which must to run current opencart version you seen if all services is activated in your wamp server it display in green color icon. if there is any red color icon in front of given service then activate wamp or xamp server service.
before continue you need to rename file in opencart upload\admin folder from [config-dist.php] to [ config.php ] respectively in front side catelog folder rename  [config-dist.php] to [ config.php ]
step3 ==>configration of database choose your databse driver eg. mysql   db host [eg.localhost or your live site db path]  user name, password,dbname,and prefix of database.  enter a username and password for the administration. set   username and password for admin panel make it safe with secure password
step4  ===> if you seen  step for finished installation then you have successfully installed opencart click on link Go to your Online Shop   check your site front end and by clicking on Login to your Administration  log in to your admin panel  and manage your product and store. delete Install folder  for security reasons!

PHP Interview Quertions for Experience

Sangwan Pankaj Reply 18:34

PHP-Mysql Interview Questions

Q:1
How can we submit a form without a submit button?

A:1
The main idea behind this is to use Java script submit() function in order to submit the form without explicitly clicking any submit button. You can attach the document.formname.submit() method to onclick, onchange events of different inputs and perform the form submission. you
can even built a timer function where you can automatically submit the form after xx seconds once the loading is done (can be seen in online test sites).

Q:2
In how many ways we can retrieve the data in the result set of MySQL using PHP?

A:2
You can do it by 4 Ways
1. mysql_fetch_row.

2. mysql_fetch_array

3. mysql_fetch_object

4. mysql_fetch_assoc

Q:3
What is the difference between mysql_fetch_object and mysql_fetch_array?

A:3
mysql_fetch_object() is similar tomysql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

Q:4
What is the difference between $message and $$message?
A:4
It is a classic example of PHP’s variable variables. take the following example.$message = “Mizan”;$$message = “is a moderator of PHPXperts.”;$message is a simple PHP variable that we are used to. But the $$message is not a very familiar face. It creates a variable name $mizan
with the value “is a moderator of PHPXperts.” assigned. break it like this${$message} => $mizanSometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically.

Q:5
How can we extract string ‘abc.com ‘ from a string ‘http://info@abc.com’
using regular expression of PHP?


A:5
preg_match(”/^http:\/\/.+@(.+)$/”,’http://info@abc.com’,$found);

echo $found[1];

Q:6
How can we create a database using PHP and MySQL?

A:6
We can create MySQL database with the use of

mysql_create_db(“Database Name”)

Q:7
What are the differences between require and include, include_once and require_once?

A:7
The include() statement includes and evaluates the specified file.The documentation below also applies to require(). The two constructs are identical in every way except how they handlefailure. include() produces a Warning while require() results in a Fatal Error. In other words, use require() if you want a missingfile to halt processing of the page.
include() does not behave this way, the script will continue regardless.
The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only differencebeing that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.include_once() should be used in cases where the same file might be included and evaluated more than once during a particularexecution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.
require_once()
should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.

Q:8
Can we use include (”abc.PHP”) two times in a PHP page “makeit.PHP”?
A:8
Yes we can use include() more than one time in any page though it is not a very good practice.


Q:9
What are the different tables present in MySQL, which type of table is generated when we are creating a table in the following syntax:
create table employee (eno int(2),ename varchar(10)) ?


A:9
Total 5 types of tables we can create
1. MyISAM
2. Heap
3. Merge
4. INNO DB
5. ISAM

MyISAM is the default storage engine as of MySQL 3.23 and as a result if we do not specify the table name explicitly it will be assigned to the default engine.

Q:10
How can we encrypt the username and password using PHP?
A:10
The functions in this section perform encryption and decryption, and compression and uncompression:
encryption decryption
AES_ENCRYT() AES_DECRYPT()

ENCODE() DECODE()
DES_ENCRYPT()   DES_DECRYPT()

ENCRYPT()       Not available

MD5()           Not available

OLD_PASSWORD()  Not available

PASSWORD()      Not available

SHA() or SHA1() Not available

Not available   UNCOMPRESSED_LENGTH()   
Q:11
Describe functions STRSTR() and STRISTR.

AnswerBoth the functions are used to find the first occurrence of a string. Parameters includes: input String, string whose occurrence needs to be found, TRUE or FALSE (If TRUE, the functions return the string before the first occurrence.

STRISTR is similar to STRSTR. However, it is case-insensitive E.g. strstr ($input_string, string)   Q:12 What is Full form of PHP ? Who is the father or inventor of PHP ?  answer: Rasmus Lerdorf is known as the father of PHP that started development of PHP in 1994 for their own Personal Home Page (PHP) and they released PHP/FI (Forms Interpreter) version 1.0 publicly on 8 June 1995 But in 1997 two Israeli developers named Zeev Suraski and Andi Gutmans rewrote the parser that formed the base of PHP 3 and then changed the language's name to the PHP: Hypertext Preprocessor. Q:13 What are the differences between Get and post methods.  Answer: There are some defference between GET and POST method 1. GET Method have some limit like only 2Kb data able to send for request But in POST method unlimited data can we send 2. when we use GET method requested data show in url but Not in POST method so POST method is good for send sensetive request 
Q:12 What is meant by nl2br()?
Ans: Inserts HTML line breaks (<BR />) before all newlines in a string.



 
 
Q:13 What is htaccess? Why do we use this and Where?
Answers .htaccess files are configuration files of Apache Server which provide
a way to make configuration changes on a per-directory basis. A file,
containing one or more configuration directives, is placed in a particular
document directory, and the directives apply to that directory, and all
subdirectories thereof.
 
 
Q: 14 What are the features and advantages of object-oriented
programming?
Answer One of the main advantages of OO programming is its ease of
modification; objects can easily be modified and added to a system there
by reducing maintenance costs. OO programming is also considered to be
better at modeling the real world than is procedural programming. It
allows for more complicated and flexible interactions. OO systems are
also easier for non-technical personnel to understand and easier for
them to participate in the maintenance and enhancement of a system
because it appeals to natural human cognition patterns.
For some systems, an OO approach can speed development time since many
objects are standard across systems and can be reused. Components that
manage dates, shipping, shopping carts, etc. can be purchased and easily
modified for a specific system
 
Q: 15
What is meant by MIME?
Answer Multipurpose Internet Mail Extensions.
WWW ability to recognise and handle files of different types is largely dependent on the use of the MIME (Multipurpose Internet Mail Extensions) standard. The standard provides for a system of registration of file types with information about the applications needed to process them. This information is incorporated into Web server and browser software, and enables the automatic recognition and display of registered file types.

Q: 16
What is meant by PEAR in php?
Answer PEAR is short for "PHP Extension and Application Repository" and is pronounced just like the fruit. The purpose of PEAR is to provide:
A structured library of open-sourced code for PHP users
A system for code distribution and package maintenance
A standard style for code written in PHP
The PHP Foundation Classes (PFC),
The PHP Extension Community Library (PECL),
A web site, mailing lists and download mirrors to support the PHP/PEAR community
PEAR is a community-driven project with the PEAR Group as the governing body. The project has been founded by Stig S. Bakken in 1999 and quite a lot of people have joined the project since then.

Get current user data in wordpress

Sangwan Pankaj Reply 09:54
Use wp_get_current_user() to get current users value.
  wp_get_current_user() return WP_User object. 
<?php
    $current_user 
wp_get_current_user();
    
echo 'Username: ' $current_user->user_login '<br />';
    echo 
'User email: ' $current_user->user_email '<br />';
    echo 
'User first name: ' $current_user->user_firstname '<br />';
    echo 
'User last name: ' $current_user->user_lastname '<br />';
    echo 
'User display name: ' $current_user->display_name '<br />';
    echo 
'User ID: ' $current_user->ID '<br />';?>
Copyright by GhostPHP. Powered by Blogger.

Search

Recent Post

Popular Posts

Follow us