Tuesday, October 17, 2017

Anil kr Prajapati

How To Create Random URL .txt File From Sitemap.xml In PHP ?

Here I am sharing a simple PHP script to generate number of txt file from Sitemap.xml. This is a simple PHP script I wrote quickly for myself to create number of .txt files according to length of sitemap.xml for my page.

This script will help you If you want to generate random .txt file from the URL existed in sitemap.xml.

Follow the steps to generate random URL .txt file :

Step #1 : Generate & Download sitemap.xml for your website.

There are number of websites where you can generate sitemap.xml like :



you can also generate sitemap.xml by visiting link http://www.yourwebsite.com/sitemap.xml

Step #2 : Run the below script to generate random URL .txt file :

<?php
function xmldata($xmlurl){   
   $i=1;
 $ucount=1;
   $rss=simplexml_load_file($xmlurl); 
    $rss_split=array();  
    foreach ($rss->channel->url as $item){ 
        echo $link   = (string) $item->loc; // Url Link
        $file = 'dq-india/adurlDq/'.$i.'.txt'; //folder path to generate url.txt
        $fh = fopen($file, 'w') or die("can't open file");
        $url =$link;
        fwrite($fh, $url);fclose($fh);  
         $i++;
    }
    return true;
}
$xmlurl='http://localhost/shared/ad-ref/ciol/29-oct/sitemap.xml'; //sitemap.xml system path
xmldata($xmlurl);
?>

Step #3 : Run this file on local server.

if you run this file on local server it will generate random URL .txt file in adurldq folder.


Each .txt file contains URL of your website.

Read More

Saturday, October 14, 2017

Anil kr Prajapati

Best Interview Questions And Answers For Experienced PHP Developer


Question #1: How to get the location of php.ini?

You can get the location of php.ini by using <?php phpinfo(); ?> code.

Question #2: How to POST Data using CURL in PHP?

you can execute POST data by using CURL as below :


$data = array('name' => 'Ross', 'php_master' => true);
$url = 'http://domain.com/abc.php';
// You can POST a file by prefixing with an @ (for <input type="file"> fields)

$handle = curl_init($url);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
curl_exec($handle);
curl_close($handle);

Question #3: How to get duplicate values from array?

you can get duplicate values from an array by using array_diff_assoc($arr, $arr_unique); for an example :


<php 
         $arr = ('anil','anil','sonia','monica','sunita','sunita','raj');
         $arr_unique = array_unique($arr);
         $arr_duplicates = array_diff_assoc($arr, $arr_unique);
         print_r($arr_duplicates);
?>

It will return :
Array(
                          [1] => anil
                          [2] => sunita
)

Question #4: How to identify server IP address in PHP?

you can identify server IP address by using $_SERVER['SERVER_ADDR']; 

Question #5: What is the difference between explode() and split() functions?


Split function splits string into array by regular expression. Explode splits a string into array by string.
Both function are used to breaks a string into an array, the difference is that Split() function breaks split string into an array by regular expression and explode() splits a string into an array by string. explode() is faster than split() because it does not match the string based on regular expression.  
Question #6: What is difference between require_once(), require() and include() function ?

require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page). So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don't include the file more times and you will not get the "function re-declared" error.
Question #7: What is use of header() function in PHP ?

Header() function is mostly used to Redirect from one page to another -

<?php header("Location:page.php"); ?>

Question #8: What type of inheritance does not support by PHP ?

Only Multiple Inheritance does not support by PHP.

Question #9: What is PEAR?

PEAR stands for PHP Extension and Application Repository. PEAR is a framework and repository for re-usable PHP components.

Question #10: What are different types of errors in PHP ?

  1. E_WARNING: It is a run-time warning that does not cause script termination.
  2. E_ERROR: It is a fatal error that causes script termination.
  3. E_NOTICE: It is a run time notice caused due to error in code.
  4. E_CORE_WARNING: Warnings that occur during PHP's initial startup.
  5. E_PARSE: Compile time parse error.
  6. E_CORE_ERROR: It is a fatal errors that occur during PHP's initial startup
  7. E_COMPILE_ERROR: Fatal compile-time errors indication problem with script.
  8. E_USER_WARNING: It is a user-generated warning message.
  9. E_USER_NOTICE: User-generated notice message.
  10. E_USER_ERROR: User-generated error message.
  11. E_STRICT: Run-time notices.
  12. E_RECOVERABLE_ERROR: It is a catchable fatal error indicating a dangerous error 
  13. E_ALL: Catches all errors and warnings 

Question #11 - Write down the code for save an uploaded file in php.


if ($_FILES["file"]["error"] == 0) {
move_uploaded_file($_FILES["file"]["tmp_name"],       "upload/" . $_FILES["file"]["name"]);       echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; }

Question #12 - How to create a text file in php?


$filename = "/home/user/guest/newfile.txt"; $file = fopen( $filename, "w" ); if( $file == false ) { echo ( "Error in opening new file" ); exit(); } fwrite( $file, "This is a simple test\n" ); fclose( $file );
Read More

Thursday, October 12, 2017

Anil kr Prajapati

How To Insert Records Using Stored Procedure in MySql with PHP ?

If you want to insert large records in a table so it is great to do that by using of Stored Procedure. There are number of benefits to insert record with the use of Stored Procedure

  • Stored procedure cached on server so the speed is more fast.
  •  A Stored Procedures will be in one place so that there’s no confusion of having business rules spread over potentially disparate code files in the project.
  • More secure because there is no direct access with tables in database.
I am describing the process of inserting records in database by using Stored Procedure as below.

Step #1 : Create a Stored Procedure in your database.
                
you can create a Stored Procedure by two way.

1. Create a stored procedure by using of phpMyAdmin.

2. Create a Stored Procedure by using MySql query.

you can use below query to create a stored procedure to insert data.

DELIMITER $$
CREATE  PROCEDURE `insert_records`(IN `name` VARCHAR(50))
BEGIN
insert into r (name) values (name);
END$$
DELIMITER ;

Step #2 : Now Create table in which we want to insert data.

create table by using below query -

CREATE TABLE `insert_records`(`name` VARCHAR(100))


Step #3 : Call Stored Procedure by PHP script to insert names.

you can call a stored procedure by using below query to insert data -

<?php 
     $name = array('anil','raj','sonia','monica','sivani');
    foreach($name  as $key=>$val){ 
$data = implode("','",$val);
echo '===== Standard data insertion start ===== <br/>'.$data.'<br/>';
$query = "CALL insert_records('".$data."')";
try{
            $success = $conn->query($query);
            if($success){
                echo "inserted succesfully";             
            }
            else{
                    echo "Data not successfully Inserted.";
            }
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>

When you run the script it will insert the all data in the table and if there is any error it will show exception.

you can easily insert data into database by using this process.
Read More

Wednesday, October 11, 2017

Anil kr Prajapati

How to Get Title, Description, and Keywords of a Website in PHP ?

I found most of the people asking for a way to get meta data of a website, so I thought to share the logic with a very easy PHP script that will retrieve a website page title, keywords and description. You can also get the sitemap of a website url. Here I am describing it with proper UI and with output. So follow these steps.



Step #1 : First design a page where you can input website URL.


Copy index.php Code :-

<form action="show.php" method="POST">
    <table cellspacing="0" height="38%" width="57%" style="border:1px solid;">
            <tr><td width="27%">Enter URL:</td><td width="50%"><input class="input" type="text" id="url" name="url"></td></tr>                     
                        <tr> <td></td><td><input type="submit" name="submit" value="submit" /></td></tr>
      </table>
  </form>


Step #2 : Now add below code in new page show.php.

if(isset($_REQUEST['submit'])){
 //$weburl variable to store url
 $weburl=$_REQUEST['url']; 
    $html = file_get_contents_curl("$weburl");
    //parsing begins here:
    $doc = new DOMDocument();
    @$doc->loadHTML($html);
   $nodes = $doc->getElementsByTagName('title');
   //get and display data:
   $title = $nodes->item(0)->nodeValue;
   $metas = $doc->getElementsByTagName('meta');
   for ($i = 0; $i < $metas->length; $i++)
   {
    $meta = $metas->item($i);
    if($meta->getAttribute('name') == 'description')
        $description = $meta->getAttribute('content');
    if($meta->getAttribute('name') == 'keywords')
        $keywords = $meta->getAttribute('content');
    }
     echo "Title: $title". '<br/><br/>';
     echo "Description: $description". '<br/><br/>';
     echo "Keywords: $keywords".'<br/><br/>';
     $regex='|<a.*?href="(.*?)"|';
        preg_match_all($regex,$html,$parts);
        $links=$parts[1];
       foreach($links as $link){
         echo "Internal and External Links".": ". $link."<br>";
       }
    echo '<br/>';
    echo "ip address of your webstie:",gethostbyname($weburl). '<br/><br/>'; 
    $start=0;
    $time = microtime();
    $time = explode(' ', $time);
    $time = $time[1] + $time[0];
    $finish = $time;
    $total_time = round(($finish - $start), 4);
   echo'Load time:Page generated in ' . $total_time . ' seconds.';
   echo '<br/><br/>';
  
   $ch = curl_init($weburl);
   curl_setopt($ch, CURLOPT_HEADER, true);    // we want headers
   curl_setopt($ch, CURLOPT_NOBODY, true);    // we don't need body
   curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
   curl_setopt($ch, CURLOPT_TIMEOUT,10);
   $output = curl_exec($ch);
   $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);

  echo 'HTTP code: ' . $httpcode;
  }
?> 


 Step #3 : If submit URL the output will be as below.


So now you can see we have the all meta data of a URL that submit by us. 

You can also do this with helping of video as below..


Read More

Saturday, October 7, 2017

Anil kr Prajapati

How to Answer for the Tell Me About Yourself Interview Question ?

Commonly interviewer start an interview with some simple question like "Tell me about yourself" . The purpose of asking this question in the first is to make you feel more comfortable during the interview process. It is also a way for the interviewer to judge your personality to help determine if you are best fit for the job.

This question is seems like so simple that is why most of the people neglect to prepare for it, but it's crucial. so to prepare the answer for this question you should write down the things on paper to perform more confidently. Here I am gonna tell you, what things you are to speak at the front of interviewer.

First of all break down your answer in four points as like.

  • About yourself (your name & address)
  • Educational background
  • Family background 
  • Your skills 
  • Your achievements
Now you are to speak at the front of interviewer according to these points for an example:-

 My self Anil Kumar and I am from Rajasthan. here I am living at delhi.

About my qualification 

         I have done B-tech from Laxmi Devi Institute Of Engineering & Technology in 2013 and secured aggregate of 85% marks and I have done my intermediate and high school from Oswal Jain Senior Secondary School, alwar with 80% and 78% in 2007 and 2009 respectively.

About my family background

          We are five member in my family. My father is a farmer and my mother is a house wife. I have two sibling. my younger brother is pursuing BSC and my younger sister is in 10th standard.

About my skills and achievements / professional experience (if any)   

(if Fresher)
          I have done certification in advance java programming language in June 2013 and also certified with android technology December 2012. I have successfully completed two web project with title Musical Website and Mobile Cellular Store in my training duration. 

(if has experience) - 
                 I have total 5 years of experience as a PHP Developer and currently I am working in Cyber Media India Ltd.  I have worked around most of the CMS like wordpress, joomla, magneto and elgg related to PHP. I also worked on 2 framework, Codeignitor and Laravel 5.4.  
Note : if you want to perform more confidently at the front of interviewer, do prepare for this question accordingly.
Read More
Anil kr Prajapati

Most important 35 PHP interview questions and answers for freshers


 I am an experienced PHP developer so here I am sharing my own personal interview experience. I had given around 40 interview's that time and I got selected in my last 5 interviews.

So in this article I am sharing 35 basic PHP programming interview questions with answers that will surely helpful for freshers to get a job. All questions are related to php, mysql, javascript, html, css and jquery.

Question #1 - What is PHP?


PHP is an open source server side scripting language mostly used for web applications. Its easy to learn compare to other programming language. PHP also a object oriented programming language like java, .net and c++.
Question #2 - What is the use of "echo" in php?


Mainly "echo" used to print a data on screen, for an Example: <?php echo 'This is my first website'; ?> , if we run it on browser, it will print the text on the screen.
Question #3 - How to include a file to a php page?


We include a file using "include('filepath.php') " or "require('filepath.php')" function with file path as its parameter.
Question #4 - What's the difference between include and require?


If the file is not found by require(), it will cause a fatal error and stop the execution of the script. If the file is not found by include(), a warning will be generate, but execution will continue.
Question #5 - require_once(), require(), include().What is difference between them?


require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page). So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don't include the file more times and you will not get the "function re-declared" error.
Question #6 - Differences between GET and POST methods ?


We can only send 1024 bytes through GET method but by POST method can transfer large amount of data and POST is also a secure method than GET method .
Question #7 - How to declare an array in php?

we can declare array in PHP as below.
                     var $arr = array('apple', 'grape', 'lemon');
Question #8 - What is the use of 'print' in php?


Print commonly used to print text on screen like echo but print has a return type.  you can use with out parentheses with its argument list.
Example 
print('50 PHP Interview questions'); print 'Job Interview questions ');

Question #9 - What is use of count() function in php ?


count() function return total number of elements in an array or something in an object.
Question #10 - What is the difference between Session and Cookie?

Both are used to store user information on server. The main difference between sessions and cookies is that sessions are stored on the server, and cookies are stored on the user's computers in the text file format. Cookies can't hold multiple variable while session can hold multiple variables..We can set expiry for a cookie,The session only remains active as long as the browser is open.Users do not have access to the data you stored in Session,Since it is stored in the server.Session is mainly used for login/logout purpose while cookies using for user activity tracking
Question #11 - How to set cookies in PHP?


We can set cookies like Setcookie("user", "ram", time()+3600);
Question #12 - How to Retrieve a Cookie Value?


We can retrieve a cookie value like - echo $_COOKIE["user"];
Question #13 - How to create a session? How to set a value in session ? How to Remove data from a session?


Create session : session_start();
Set value into session : $_SESSION['USER_ID']=1;
Remove data from a session : unset($_SESSION['USER_ID'];
Question #14 - How to create a mysql connection?

we can create connection by using function mysql_connect(hostname,username,password,database);

Question #15 - How to select a database?


we can select database by using mysql_select_db($db_name); function and we can also select a database by using function mysql_query('use databaseName'); 
Question #16 - How to execute an sql query? How to fetch its result ?

$query = mysql_query("SELECT * FROM `employee` WHERE `u_id`='1'; ");
$result = mysql_fetch_array($query);
echo $result['phone_number'];
Question #17 - Write a program using while loop


$query = mysql_query("SELECT * FROM `employee` WHERE `u_id`='1'; ");
while($result = mysql_fetch_array($query))
{
echo $result['phone_number'.]."<br/>";
}
Question #18 - How we can retrieve the data in the result set of MySQL using PHP?


  • mysql_fetch_row()
  • mysql_fetch_array()
  • mysql_fetch_object()
  • mysql_fetch_assoc()

Question #19 - What is the use of explode() function ?


This function is used to split a string into an array. Syntax : array explode( string $delimiter , string $string [, int $limit ] ); 
Question #20 - What is the difference between explode() and split() functions?


Split function splits string into array by regular expression. Explode splits a string into array by string.
Both function are used to breaks a string into an array, the difference is that Split() function breaks split string into an array by regular expression and explode() splits a string into an array by string. explode() is faster than split() because it does not match the string based on regular expression.  
Question #21 - What is the use of mysql_real_escape_string() function?


mysql_real_escape_string() function mainly used to escapes special characters in a string for use in an SQL statement
Question #22 - Write down the code for save an uploaded file in php.


if ($_FILES["file"]["error"] == 0)
{
move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
Question #23 - How to create a text file in php?


$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false )
{
echo ( "Error in opening new file" ); exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );
Question #24 - How to strip whitespace (or other characters) from the beginning and end of a string ?


We can use trim() function to remove whitespaces or other predefined characters from both sides of a string.
Question #25 - What is the use of header() function in php ?


The header() function sends a raw HTTP header to a client browser.Remember that this function must be called before sending the actual out put.For example, You do not print any HTML element before using this function.
Question #26 - How to redirect a page in php?


we can redirect a page by using header("Location:index.php"); function.
Question #27 - How stop the execution of a php scrip ?


We mostly use exit() function to stop the execution of a page
Question #28 - How to set a page as a home page in a php based site ?


The default name of the home page is index.php in php based websites
Question #29 - How to find the length of a string?


we can use strlen() function to find the length of a string
Question #30 - what is the use of isset() in php?


isset() function is used to ensure if a variable is set and is not NULL
Question #31 - What is the difference between mysql_fetch_array() and mysql_fetch_assoc() ?


mysql_fetch_assoc() function Fetch data as an associative array, While mysql_fetch_array() fetches data as an associative array, a numeric array, or both
Question #32 - How to delete a file from the system


we can delete a file by using Unlink() function in php.
Question #33 - what is the difference between javascript and PHP ?

Commonly JavaScript known as Client side scripting language while PHP is a server side scripting language.
Question #34 - What is CSS?


CSS known as cascading Style Sheet. It is a best technique to style and present HTML.
Question #35 - What are the differences between ID and class in CSS? 

ID is used to identify one element , while a class is used to identify more than one element.
Read More