Welcome to my Blog

I am Nelson Desai. I complete computer engineering.

This is my personal blog. Here I share some post, which can helpful for me, my friends and you.

Some post may be illegal to share like some crack and keys. but, i think.. which things put online then it's not be secure any more whatever company try.

So, I requested you pls download and use it at your risk. and don't upload it again online.

Thank You for peeping my blog.. Have a Good Day!

Showing posts with label MySQL. Show all posts
Showing posts with label MySQL. Show all posts

Download images from url php



First Select link from database or from any...
$url = "SELECT link FROM tablename";

Now second step is check image is available on url or not..
we can check it by so many step i give hint at end of this post....

// check url available using get_header method...
$url_head = get_headers($url)


if($url_head == FALSE) 
{
         echo "URL or HEAD Unavailable.....";
}


else
{
         // now check url image hav not 404 error to download...
         $head_chk = strpos ($url_head[0], '404 Not Found');


 if($head_chk === FALSE) 
 {

       $image_data = file_get_contents($url);   // get content from url..
       $image_name = basename($url);   // for save same name which in url.
       $image__save_location = "/path/images_folder";   // Save location or path..
        
       if(!$image_data)
       {
         // write some another image url like default image save if not available....
         $no_image_data = "some default image url... if some image not available on url"


         // now save image using file_put_contents function with same name which in url.
         file_put_contents($image__save_location."/".$image_name,  $no_image_data);
      }
       else
       {
          file_put_contents($image__save_location."/".$image_name,  $image_data);
       }
}
else
{
      echo "404 and Image Not Available.......";
}
}

-----------------------------------------------------
-----------------------------------------------------
You also check some other condition like image avilabel or not in php
1. getimagesize($url);
2. get_headers($url);
3. file_get_contents($url);

--
Thank You
Nelson Desai







login check in php



  // For shot icon on tab//




include("config.php"); //connection file
include("lock.php"); //session check file
//include("logout.php");

if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$myemail=addslashes($_POST['email']);
$mypassword=addslashes($_POST['password']);

$sql="SELECT id FROM userdetails WHERE email='$myemail' and password='$mypassword'";

$result=mysql_query($sql);
$count=mysql_num_rows($result);
$row=mysql_fetch_array($result);
$active=$row['active'];



// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
session_register("myemail");
$_SESSION['login_user']=$myemail;

header("location:../home.php");
}
else
{
?>


}
}


?>
   

     

Email Id :
       
       
     


     

Password :
       
     


     
     


       
        Remember me on this computer


     

       
     
   

   
 



session destroy or unset in php



session_start();
if(isset($_POST['logout'])){
session_destroy();
session_unset();
header("Location:../login");
}
?>

session check in php



include('config.php'); //connection file
session_start();
$user_check=$_SESSION['login_user'];
$ses_sql=mysql_query("select email from userdetails where email='$user_check' ");
$row=mysql_fetch_array($ses_sql);
$login_session=$row['email'];
$sesp_sql=mysql_query("select fname from userdetails where email='$user_check' ");
$rows=mysql_fetch_array($sesp_sql);
$login_session1=$rows['fname'];
if(!isset($login_session))
{

}
else
{
header("Location:../home.php");
}
?>

Connection in php


$mysql_hostname = "locahost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "table name[userdetails]";
$con = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die("Opps some thing went wrong or not connect to databse");
mysql_select_db("database name", $con) or die("Opps some thing or not selected db ....");
?>

Most Common php + mysql interview questions



These are some of the PHP and MySQL question that you cannot avoid.
All questions i got from this site CLICK HERE




1 ) What will you use to initialize a string ? ie with single quotes or double quotes ?
Ans: 
Unlike the double-quoted syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
As in single quoted strings, escaping any other character will result in the backslash being printed too. Before PHP 5.1.1, the backslash in \{$var}had not been printed.
The most important feature of double-quoted strings is the fact that variable names will be expanded.

2 ) You have a string “hi all, I said hello” . You want to replace the occourence of hi with hello and hello with hi . What will you do ?
Ans: 
 $rawstring= "hi all, I said hello";
$placeholders = array('hi', 'hello'')
$malevals = array('hello', hi');
$malestr = str_replace($placeholders, $malevals, $rawstring);
echo  $malestr ;

SORRY this wrong answer that give problem in output because we replace first hello to hi then we find two times hi so, it's create problem.. 

True answer..
Replace With unique identifiers..
$replace = array( 
'hi' => '^', 
'hello' => '*',
'^' => 'hello',
'*' => 'hi'
); 

echo str_replace(array_keys($replace), array_values($replace), $rawstring);
---
ereg() - Regular expression match
eregi() - Case insensitive regular expression match
eregi_replace() - Replace regular expression case insensitive
str_replace() - Replace all occurrences of the search string with the replacement string
preg_match() - Perform a regular expression match
==============
more details: 

3 ) What’s the difference between PHP4 and PHP5 ?
Ans:
The new OOP features in PHP5 is probably the one thing that everyone knows for sure about. Out of all the new features, these are the ones that are talked about most!

1. Passed by Reference
2.  Visibility[public, protected, private]
3. Unified Constructors and Destructors
4. The __autoload Function
===========
more details:

4 ) What’s all added in PHP 5.3 ?
Ans:
PHP 5.3.0 offers a wide range of new features:
  • Support for namespaces has been added.
  • Support for Late Static Bindings has been added.
  • Support for jump labels (limited goto) has been added.
  • Support for native Closures (Lambda/Anonymous functions) has been added.
  • There are two new magic methods, __callStatic and __invoke.
  • Nowdoc syntax is now supported, similar to Heredoc syntax, but with single quotes.
  • It is now possible to use Heredocs to initialize static variables and class properties/constants.
  • Heredocs may now be declared using double quotes, complementing the Nowdoc syntax.
  • Constants can now be declared outside a class using the const keyword.
  • The ternary operator now has a shorthand form: ?:.
  • The HTTP stream wrapper now considers all status codes from 200 to 399 to be successful.
  • Dynamic access to static methods is now possible.
  • Exceptions can now be nested.
  • A garbage collector for circular references has been added, and is enabled by default.
  • The mail() function now supports logging of sent email.
========
more details:

5 ) What’s Name spacing ?
Ans:
In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions:
  1. Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
  2. Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.
PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants.

6 ) What are the types of inheritance PHP supports ?
Ans:
Similar to Java, PHP supports single inheritance. There is no multiple inheritance in php. Single inheritance means a class can extend only one parent class.

PHP also has interfaces which can be implemented if bunch of classes need to have similar functionality. An interface can be created containing methods with empty body. Implementing classes then must provide body to those methods.

When a class implements an interface, it is signing up a contract that it will provide implementation to methods declared in that interface.

7 ) What do you mean by an Abstract class and Interface ?
Ans:
Depending on the context, an interface class is either a class of the interface layer or a class whose purpose is to create a contract between a caller and an implementation (usually by providing only purely virtual functions).
An abstract class is a class that has at least one purely virtual function. Abstract classes can contain abstract and concrete methods. Abstract classes cannot be instantiated directly i.e. we cannot call the constructor of an abstract class directly nor we can create an instance of an abstract class
A static class is a class that has only static member variables and static member functions.
8 ) When a file is uploaded to the sever how can you check whether its uploaded or not ?
Ans:


(PHP 4 >= 4.0.3, PHP 5)
is_uploaded_file — Tells whether the file was uploaded via HTTP POST.
is_uploaded_file($_FILES['userfile']['tmp_name']);
Returns TRUE on success or FALSE on failure.

9 ) How will you move the uploaded file to another location of server ?
Ans:
move_uploaded_file — Moves an uploaded file to a new location.

This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). 
If the file is valid, it will be moved to the filename given by destination.

10 ) What are the things that need to be checked before uploading a file ?
Ans:
Check picture file type and size before file upload..
more details:

11 ) How will you connect mysql ?
Ans: Here u can get Click Here

12 ) Does PHP supports PDF creation ?
Ans:
The PDF functions in PHP can create PDF files using the PDFlib library which was initially created by Thomas Merz and is now maintained by » PDFlib GmbH.

Starting with PHP 4.0.5, the PHP extension for PDFlib is officially supported by PDFlib GmbH. This means that all the functions described in the PDFlib Reference Manual are supported by PHP 4 with exactly the same meaning and the same parameters. 

13 ) What are the storage types in MySQL ?
Ans:
13.1. The MyISAM Storage Engine[default engine]
13.2. The InnoDB Storage Engine 
13.3. The MERGE Storage Engine 
13.4. The MEMORY (HEAP) Storage Engine
13.5. The BDB (BerkeleyDB) Storage Engine
13.6. The EXAMPLE Storage Engine
13.7. The FEDERATED Storage Engine
13.8. The ARCHIVE Storage Engine
13.9. The CSV Storage Engine
13.10. The BLACKHOLE Storage Engine

more details


14 ) What is the difference between InnoDb and MyISAM ?
Ans:
  • The big difference between MySQL Table Type MyISAM and InnoDB is that InnoDB supports transaction
  • InnoDB supports some newer features: Transactions, row-level locking, foreign keys
  • InnoDB is for high volume, high performance


15 ) Does MyISAM supports relations ?
Ans:  InnoDB has foreign keys and relationship contraints while MyISAM does not.

more details



16 ) What’s indexing ?
Ans:
database index is a data structure that improves the speed of data retrieval operations on a database table at the cost of slower writes and increased storage space.

17 ) MySQL is case sensitive or case insensitive ?
Ans:
 SQL itself isn't case sensitive, but it can be on searching data, all depends on the table collation settings.

MySQL syntax is not case sensitive, you can write
SELECT * FROM table WHERE ... 
or
select * from table where...
or
SeLEct * FroM table WHerE
or whatever else you want.

On select queries you can search for case sensitive fields values, in example if you want to find "text" inside a field but not "TEXT", "Text".... you can use

SELECT * FROM table WHERE binary(fieldname)='text';

18 ) You have a table say user with field name and data’s Lokam , loker , lover , Lough , Lost , Enough , Elephant etc . Write a query which gives all the terms Lokam , loker , lover , Lough and Lost .

Ans:  SELECT * FROM  `user` WHERE  `name` LIKE  'lo%' ;

any questions ask me in comments...

19 ) Now you want to select only the loker , lover . What will you add to get this result ?

Ans:   SELECT * FROM  `user` WHERE  `name` LIKE  'lo%er' ;

any questions ask me in comments...

20 ) Let there is table user with name and marks . How will you select the second largest number from this table ?  For eg let the data’s are
hari 23 , jenson 10 , ruby 20 , rijith 10 . You want to select 20 from this.

Ans: 
SELECT * FROM user WHERE marks = (SELECT MAX(marks) FROM user WHERE marks < (SELECT MAX(marks) FROM user)) ORDER BY marks DESC LIMIT 0,1 

any questions ask me in comments...

21 ) What are the different types of JOINS ?
Ans:
A join combines records from two or more tables in a relational database. In the Structured Query Language (SQL), there are two types of joins: "inner" and "outer". Outer joins are subdivided further into left outer joins, right outer joins, and full outer joins.

Inner join
This is the default join method if nothing else is specified. An inner join essentially finds the intersection between the two tables. The join  takes all the records from table A and finds the matching record(s) from table B. If no match is found, the record from A is not included in the results. If multiple results are found in B that match the predicate then one row will be returned for each (the values from A will be repeated).
Special care must be taken when joining tables on columns that can be NULL since NULL values will never match each other

Left outer join
A left outer join is very different from an inner join. Instead of limiting results to those in both tables, it limits results to those in the "left" table (A). This means that if the ON clause matches 0 records in B, a row in the result will still be returned—but with NULL values for each column from B.

Right outer join
A right outer join is much like a left outer join, except that the tables are reversed. Every record from the right side, B, will be returned, and NULL values will be returned for those that have no matching record in A.

Full outer join
Full outer joins are the combination of left and right outer joins. These joins will show records from both tables, and fill in NULLs for missing matches on either side
23 ) Have you used Triggers ? What is it ?
Ans:
database trigger is procedural code that is automatically executed in response to certain events on a particular table or view in a database.
The trigger is mostly used for keeping the integrity of the information on the database. 
For example, when a new record (representing a new worker) is added to the employees table, new records should be created also in the tables of the taxes, vacations, and salaries.
24 ) What is Views in MySQL ?
Ans:
A database View is known as a "virtual table" which allows you to query the data in it. 
Understanding Database View and using it correctly is crucial.
MySQL views are essentially a way to package up SELECT statements into re-usable virtual tables whereby the data can be retrieved simply by referencing the view, rather than having to repeat the associated SELECT statement. 
26 ) How can you call a mysql procedure from PHP ?
Ans: Read all links of ans 25.
27 ) What is MVC ? ( If you are strong in any frameworks , then questions from that can also be hit, don’t make it a miss rate )
Ans: Here U can get details
http://www.jcorporate.com/expresso/doc/edg/edg_WhatIsMVC.html
http://whatis.techtarget.com/definition/model-view-controller-MVC
http://www.codinghorror.com/blog/2008/05/understanding-model-view-controller.html
28 ) Does PHP has an XML library ? Is it comming as default ?
Ans: Here U can get details. read all w3school PHP XML Links[Total:3].
http://www.w3schools.com/php/php_xml_simplexml.asp
http://www.php.net/manual/en/book.simplexml.php
29 ) What’s SOAP ?
Ans:
SOAP, originally defined as Simple Object Access Protocol, is a protocol specification for exchanging structured information in the implementation of Web Services in computer networks.

It relies on Extensible Markup Language (XML) for its message format, and usually relies on other Application Layer protocols, most notably Hypertext Transfer Protocol(HTTP) and Simple Mail Transfer Protocol (SMTP), for message negotiation and transmission. SOAP can form the foundation layer of a web services protocol stack, providing a basic messaging framework upon which web services can be built.
30 ) What’s is XSS attack ?
Ans:
Cross-site scripting (XSS) is a type of computer security vulnerability typically found in Web applications that enables attackers to inject client-side script into Web pages viewed by other users.
A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same origin policy.
32 ) What is Session and Cookie ?
Ans: If u want this ans then please forget about php.
http://www.allaboutcookies.org/cookies/session-cookies-used-for.html/
http://www.tuxradar.com/practicalphp/10/1/0

33 ) What’s the difference between session_register and $_SESSION ?
Ans:
The very first main and simple difference is that session_register function returns boolean value and $_SESSION returns string value. 
The second will be session_register function doesn't work if register_global is disabled. 
But whereas $_SESSION works in both case whether register_global is disabled or enabled. So using $_SESSION for session variable manipulation is more appropriate.

34 ) What is magic quotes ? Is it on or off by default in PHP 5 ?
Ans:
Magic Quotes is a process that automagically escapes incoming data to the PHP script. 
It's preferred to code with magic quotes off and to instead escape the data at runtime, as needed.
Magic Quotes are depreciated and going to be removed in PHP6.
35 ) What does __sleep and __wake do ?
Ans: Here Details
http://www.sunilb.com/php/php5-oops-tutorial-magic-methods-__sleep-and-__wakeup
http://www.phpinterviewquestion.com/php-questions/what%E2%80%99s-__sleep-and-__wakeup-in-php

36 ) Can you submit a form without a submit button ?
Ans:
You can submit a form without a submit button, but it relies on javascript, which is a bad thing. How will you keep your pages working for those without javascript enabled?

Anyway, to submit the first form on your page, you can use something like this:

on link  onclick="document.forms[0].submit();"

submit


37 ) How can you set a cookie to expire after 30 minutes or so ?
Ans:
30 minutes is 30 * 60 * 1000 miliseconds. Add that to the current date to specify an expiration date 30 minutes in the future.
 var date = new Date();
 date.setTime(date.getTime() + (30 * 60 * 1000));
 $.cookie("example", "foo", { expires: date });
and for session>>
if(isSet($_SESSION['started'])){
  if((mktime() - $_SESSION['started'] - 60*30) > 0){
    //logout, destroy session etc
  }
}else{
  $_SESSION['started'] = mktime();
}
--
Thank You
Nelson Desai

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by NDR Group | Bloggerized by Er. Nelson Desai | Love U My Friends