abc

Share This blog with your friends, so that we can improve more & more . our aim is to easy & simple way of learning.
Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

12/15/2020

How to send attachment email using PHP

1) use basic mail function available in PHP 

2) get file type using application/octet-stream

3) form must  enctype="multipart/form-data"

4) sure to use MD5 encryption & chunk_split(base64_encode)

5) to upload file use move_uploaded_file



<?php

$from = $_REQUEST["from"];

$emaila = $_REQUEST["emaila"];

$filea = $_REQUEST["filea"];


if ($filea)

{

function mail_attachment ($from , $to, $subject, $message, $attachment)

{

$fileattachis = $attachment; // Path to the file

$fileattachis_type = "application/octet-stream"; // File Type 

$start = strrpos($attachment, '/') == -1 ? strrpos($attachment, '//') : strrpos($attachment, '/')+1;

$fileattachis_name = substr($attachment, $start, strlen($attachment));

$email_from = $from; //email from

$subject = "New Attachment Message";

$email_subject =  $subject;

$email_txt = $message;

$email_to = $to;

$headers = "From: ".$email_from;

$file = fopen($fileattachis,'rb'); 

$data = fread($file,filesize($fileattachis)); 

fclose($file); 

$msg_txt="\n\n You have recieved a new attachment email from $from";

$semi_rand = md5(time()); 

$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 

$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . "

boundary=\"{$mime_boundary}\"";

$email_txt .= $msg_txt;

$email_message .= "This is a multi-part message in MIME format.\n\n" . 

"--{$mime_boundary}\n" . "Content-Type:text/html; 

charset = \"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . 

$email_txt . "\n\n";

$data = chunk_split(base64_encode($data));

$email_message .= "--{$mime_boundary}\n" . "Content-Type: {$fileattachis_type};\n" .

" name = \"{$fileattachis_name}\"\n" . //"Content-Disposition: attachment;\n" . 

//" filename = \"{$fileattachis_name}\"\n" . "Content-Transfer-Encoding: 

base64\n\n" . $data . "\n\n" . "--{$mime_boundary}--\n";

$ok = mail($email_to, $email_subject, $email_message, $headers);

if($ok)

{

echo "File Sent Successfully.";

unlink($attachment); // delete a file after attachment sent.

}

else

{

die("Sorry email not sent. Please try again!");

}

}

move_uploaded_file($_FILES["filea"]["tmp_name"], 'temp/'.basename($_FILES['filea']['name']));


mail_attachment("$from", "youremailaddress@gmail.com", "subject", "message", ("temp/".$_FILES["filea"]["name"]));

}

?>


<html>

<head>


<script type = "text/javascript">

function checkfile() {

with(document.filepost) {

if(filea.value ! = "") {

document.getElementById('textis').innerText = "Attaching File ... Please Wait";

}

}

}

</script>


</head>

<body>


 

<form name= "filepost" method="post" action="file.php" enctype="multipart/form-data" id = "file">

<table width = "300" border = "0" cellspacing = "0" cellpadding = "0">

<tr valign = "bottom">

<td height = "20">Name:</td>

</tr>

<tr>

<td>

<input name = "from" type = "text" id = "from" size = "30">

</td>

</tr>

<tr valign = "bottom">

<td height = "20">Email Address:</td>

</tr>

<tr>

<td class = "frmtxt2">

<input name = "emaila" type = "text" id = "emaila" size = "30">

</td>

</tr>

<tr>

<td height = "20" valign = "bottom">Attachment:</td>

</tr>

<tr valign = "bottom">

<td valign = "bottom">

<input name = "filea" type = "file" id = "filea" size = "16">

</td>

</tr>

<tr>

<td height = "40" valign = "middle">

<input name = "Reset2" type = "reset" id = "Reset2" value = "Reset">

<input name = "Submit2" type = "submit" value = "Submit" onClick = "return checkfile()">

</td>

</tr>

</table>


</form>


<div id="textis"></div>


</body>

</html>


Encryption and Decryption in PHP

Encryption means convert to such form which is not easy to understand .

base64_encode which encrypt current string or data , also helpful to store secure data.

base64_decode which decrypt encrypted data. 


<?php


$var1 = 'test'; 


echo base64_encode($var1); 


//dGVzdA==


echo '<p>'.base64_decode('dGVzdA');

?>


md5 encryption - which cannot decode - one way encryption


<?php

$sampl = 'sample text here';


echo md5($sampl);


?>


What is and How to create PHP array

 array - store multiple value into single variable -

three types of array -  index, associative, Multidimensional array.


1) index array - store value into variable in curley and quoted form.


for example - 


$name = {'drip','pipe','sprinkler'};

echo $name[0] . '  '.$name[2];


2) Associative array - associate some value 


let us see example, 

$price = array("mobile"=>"8500","fan"=>"4500","light"=>"300"); 

echo $price['light'];


3) Multidimensional array - multiple checkup done


for example we have two for loop which check in $emp array and get respective value


echo $emp[0][0] ouput is 1,"sonoo",400000

<?php    

$emp = array  

  (  

  array(1,"sonu",4000),  

  array(2,"monu",5000),  

  array(3,"pinu",7000)  

  );  

  

for ($row = 0; $row < 3; $row++) {  

  for ($col = 0; $col < 3; $col++) {  

    echo $emp[$row][$col]."  ";  

  }  

  echo "<br/>";  

}  

?>   


PHP Function call by value and call by reference

 <?php  

function increment($i)  

{  

    $i++;  

}  

$i = 10;  

increment($i);  

echo $i;  

?>


above function output is 10 



Call by Reference - 


<?php  

function adder(&$str2)  

{  

    $str2 .= 'Call By Reference';  

}  

$str = 'This is ';  

adder($str);  

echo $str;  

?>


above returns output is 'this is call by reference'

use & (ampersand) symbol with formal arguments. The & represents reference of the variable.


What is PHP PDO, how it's work

 PDO refers to PHP Data Object, which is a PHP extension that defines a quick access database. 

Each database driver can expose database-specific features as a regular extension function that implements the PDO interface.

pdo connect to various database like sqlite, mysql, oracle


example of connect to database using PDO


<?php  

    $dbHost="localhost";  

    $dbName="myDB";  

    $dbUser="root"; 

    $dbPassword=""; 

    try{  

        $dbConn= new PDO("mysql:host=$dbHost;dbname=$dbName",$dbUser,$dbPassword);  

        Echo "Successfully connected with myDB database";  

    } catch(Exception $e){  

    Echo "Connection failed" . $e->getMessage();  

    }  

?> 


//above code short as $dbconn = new PDO("localhost","root","","myDB"); no need first five lines.


PDO is good as compare to mysqli , because, it connect with any database, mysqli only connect phpmyadmin mysql.


this PDO  connection short and quick connect. 


** PLEASE LIKE - SHARE - COMMENT **

What are magic constant in PHP ?

 1) __LINE__ it returns current line number 


example

<?php

 echo 'current line'.__LINE__;

?> 


2) __FILE__ - get full path of current file 


example -  echo __FILE__ . "<br><br>";  


3) __DIR__  - get full directory path


    echo __DIR__ . "<br><br>";  

OR  

echo dirname(__FILE__) . "<br><br>";    


4) __FUNCTION__ - get function name where magic constant used.


<?php   

    echo "<h3>Example for __FUNCTION__</h3>";    

   

    function test(){    

         echo 'The function name is '. __FUNCTION__ . "<br><br>";   

    }    

    test();    

    

    echo  __FUNCTION__ . "<br><br>";  

?>  


5) __CLASS__ - get class name


below example output is 'base'

<?php   

    class base  

    {    

function test_first(){    

             echo __CLASS__;   

        }    

    }    

    class child extends base    

    {    

        public function __construct() {    

            ;    

        }    

    }    

    $t = new child;    

    $t->test_first();    

?>  


6) __TRAIT__  get trait name


for eg -

trait created_trait {    

        function jtp(){    

            echo __TRAIT__;  

        }    

    }   


7) __METHOD__ get method name



public function meth_fun(){    

            //print method::meth_fun    

                echo __METHOD__;   

        }    


8) __NAMESPACE__  current namespace


 class name {    

        public function __construct() {    

            echo 'This line will print on calling namespace.';     

        }     

    }    

    $class_name = __NAMESPACE__ . '\name';    

    $a = new class_name;   

9) ClassName::class  - full name of class


output of below example is Technical_Portal/javatpoint

namespace Technical_Portal;  

    echo "<h3>Example for CLASSNAME::CLASS </h3>";  

class javatpoint {    

}  

    echo javatpoint::class;

in short magic contstant in php returns the current elements like filename, filepath, classname, methodname, directory path.


12/14/2020

Simple Tricks of PHP OOPS (object oriented Programming)

 1) A class is a template for objects, and an object is an instance of class. 


for example - car is class, bmw, mercedes is object


2) Define function in class called method,

 define variable in class called properties.



three principle in OOPS

 

A) Encapsulation - Binding (or wrapping) code and data together into a single unit are known as encapsulation. 


For example, a capsule, it is wrapped with different medicines.


via the use of "get" and "set" methods etc.(hide implementation detail)

for example -


<?php

class Animal

{

    private $family;

    private $food;


}

?>



B) Inheritance - via the use of extends keyword   (inherit from parent to child)



C) Polymorphism - If one task is performed in different ways, it is known as polymorphism 

 for example -

i) draw shape like circle, triangle (draw task in different ways)

ii) speak something like a cat speaks meow, dog barks woof  (speak task in different ways)


for polymorphism use implements keyword .



Abstraction -  Hiding internal details and showing functionality is known as abstraction. For example phone call, we don't know the internal processing




class car

{

   public $color = 'red' //property


   // method create   

   public function useofthis()

   {

return $this->color;   //using this keyword get property within same class

   }

}


$bmw= new car(); //object create


echo $bmw->color  // get property not add $ for property when calling

echo $bmw->useofthis() //get method





3) A constructor allows you to initialize an object's properties upon creation of the object.


function __construct($name) { //double underscore before construct word

    $this->name = $name;

  }


4) If you create a __destruct() function, PHP will automatically call this function at the end of the script.


5) 

public - the property or method can be accessed from everywhere. This is default

protected - the property or method can be accessed within the class and by classes derived from that class

private - the property or method can ONLY be accessed within the class


6) Inheritance in OOP = When a class derives from another class.

-- child class has its all properties and method from parent class(main class) include its own property and method


7) We can access a constant from outside the class by using the class name followed by the scope resolution operator (::)


class Goodbye {

  const LEAVING_MESSAGE = "Thank you for visiting W3Schools.com!";

}


echo Goodbye::LEAVING_MESSAGE;


8) Abstract classes and methods are when the parent class has a named method, but need its child class(es) to fill out the tasks.



9) Interfaces allow you to specify what methods a class should implement.

define by interface keyword


10) Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).


11)Namespace -allow for better organization by grouping classes that work together to perform a task,

allow the same name to be used for more than one class


namespace ab;


What is PHP super global


predefined variables in PHP called "super global", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.



Below are Super global,

1) $GLOBALS

2) $_SERVER

3) $_REQUEST

4) $_POST

5) $_GET

6) $_FILES

7) $_ENV

8) $_COOKIE

9) $_SESSION


1) $GLOBALS - means accessible variables outside of function , for example - $GLOBALS['z'] this variable also accessible outside function 'addition'


<?php 

$x = 75;

$y = 25; 


function addition() {

  $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];

}


addition();

echo $z;

?>


2) $_SERVER - 


$_SERVER['PHP_SELF'] - current PHP file name

$_SERVER['GATEWAY_INTERFACE'] - version of the Common Gateway Interface (CGI) currently using

$_SERVER['SERVER_ADDR'] - Host server IP address

$_SERVER['SERVER_NAME'] - name of the host server (such as infyleaf.tech)

$_SERVER['REQUEST_METHOD'] request method used to access the page (such as POST)

$_SERVER['QUERY_STRING'] query string if the page is accessed via a query string

$_SERVER['HTTP_ACCEPT'] Accept header from the current request

$_SERVER['HTTP_ACCEPT_CHARSET'] Accept Charset header from the current request

$_SERVER['HTTP_HOST'] Host header from the current request

$_SERVER['HTTP_REFERER'] complete URL of the current page (not reliable because not all user-agents support it)

$_SERVER['HTTPS'] Is the script queried through a secure HTTP protocol

$_SERVER['REMOTE_ADDR'] IP address from where the user is viewing the current page

$_SERVER['REMOTE_HOST'] Host name from where the user is viewing the current page

$_SERVER['REMOTE_PORT'] port being used on the user's machine to communicate with the web server

$_SERVER['SCRIPT_FILENAME'] absolute pathname of the currently executing script

$_SERVER['PATH_TRANSLATED'] file system based path to the current script

$_SERVER['SCRIPT_NAME'] path of the current script

$_SERVER['SCRIPT_URI'] URI of the current page


3) $_REQUEST - get requested name  $name = $_REQUEST['fname']; when form is post


4) $_POST - when post form get value of input for eg -

 $_POST['firstname'], $_POST['mobile']

 

<form action="" method="post">

<input type="text" name="mobile"/>

<input type="submit" value="save"/>

</form>


5) $_GET - get value from url , but should remember not pass secure value like password to this variable.


6)$_FILES - to get value from files when post input type file

basename($_FILES["fileToUpload"]["name"]);


for example 


if ($_FILES["fileToUpload"]["size"] > 2000000) {

  echo "Sorry, your file is too large.";

  $uploadOk = 0;

}


7)$_ENV - get environment variables

<?php

$arr=getenv();

foreach ($arr as $key=>$val)

echo "$key=>$val

";

?>



8) $_COOKIE - get cookie value 


in below example checking if cookie name set or not

<?php

$cookie_name = "user";

$cookie_value = "Mayur";

setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day

?>

<html>

<body>


<?php

if(!isset($_COOKIE[$cookie_name])) {

  echo "Cookie named '" . $cookie_name . "' is not set!";

} else {

  echo "Cookie '" . $cookie_name . "' is set!<br>";

  echo "Value is: " . $_COOKIE[$cookie_name];

}

?>


9) $_SESSION - store value in session , temporary storage over multiple page. 


first line should be session_start();


$_SESSION["favcolor"] = "green";


in case any query please comment


12/11/2020

How to create automatic result showing page with students name on HTML?

 in this blog shows how to get auto value into html


suppose we want maintain student data


step 1) create database it may mysql or sqlite

<?php

$servername = "localhost";

$username = "username";

$password = "password";


// Create connection

$conn = new mysqli($servername, $username, $password);

// Check connection

if ($conn->connect_error) {

  die("Connection failed: " . $conn->connect_error);

}


// Create database

$sql = "CREATE DATABASE myDB";

if ($conn->query($sql) === TRUE) {

  echo "Database created";

} else {

  echo "Error creating database: " . $conn->error;

}


$conn->close();

?>


step 2) write html to get value from above created database


<html>

<body>

<div>

<?php

$servername = "localhost";

$username = "username";

$password = "password";

$dbname = "myDB";


// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error) {

  die("Connection failed: " . $conn->connect_error);

}


$sql = "SELECT id, firstname, lastname FROM student";

$result = $conn->query($sql);

if ($result->num_rows > 0) { // output data of each row

  

  while($row = $result->fetch_assoc()) {

echo "<p>id: " . $row["id"]. "</p> - <p>Name: " . $row["firstname"]. "</p> " . $row["lastname"]. "<br>";

  }

} else {

  echo "0 results";

}

$conn->close();

?>

</div>

</body>

</html>

from above code we get data from mysql table which shows student first name and last name, 

important note - always add id & set it to primary key, into table because it is unique value in case referenece required id value is good to compare. 


please comment your query,remarks.

2/24/2019

SQL INJECTION

SQL INJECTION is user(hacker or attacker) get information or all data or simplly delete all data

$a = "SELECT * FROM users WHERE name = '" + USERID + "';"
This SQL code is designed to pull up the records of the specified username from its table of users. However, if the "USERID" variable is assign some value by malicious user, the SQL statement may get all data . For example,

' OR '1'='1   use this in $a above statement

above you can write like this

' OR '1'='1' --
' OR '1'='1' {
' OR '1'='1' /*
if hacker use this as below

SELECT * FROM users WHERE name = '' OR '1'='1';
SELECT * FROM users WHERE name = '' OR '1'='1' -- ';

 from above get all information instead of checking to specific id
This input renders the final SQL statement as follows and specified:

SELECT * FROM users WHERE name = 'a';DROP TABLE users; SELECT * FROM userinfo WHERE 't' = 't';

suppose above example will simply & delete from table.


MYSQL SELECT UPDATE QUERY & php connect

1) MYSQL Select : - is query use for getting data from  mysql database.
eg: select * FROM abc;  


above statement  get all value from table

using where statement :
select nam, addre from abc where nam ='mayur abc'


above statement use and, or case for conditional statement writing.

select using when statement

SELECT `nam``addre``mobile``city` FROM `abc` WHERE nam  IN ('mayur','mayur kumar')


similarly use update

use update statement

to update one column multiple row use when  statement


PHP CONNECT & INSERT

let us see below example : -
<?php
$con = mysqli_connect('$host','$id','$pass','$database');

if(!$con)
{
echo 'NOT connected';
}
else
{
$q ='insert into abc ('name','address')values('$name','$useaddress')';
$comnd = mysqli_query($con,$q);
if($comnd)
{
echo 'Data sucessfully inserted';
}

}
?>



5/23/2018

How PHP & MYSQL Related


Today we are going to learn  
1. about mqsql ,
2. how is related to php ,
3.  way of define mysql,
4.  connect & redirect data from mysql database.
Mysql is query language in which pass query & get result.
Eg: select *from student;  in this example get student table data.
As PHP is server side language & also use to handle mysql .
Let us see how to connected with mysql.
$conn = mysql_conn($host, $username, $password,  $database)
In case above example not use database then call it by mysql_db();
NOTE : MQSQLI is improved version & mysql is previous one version.
Eg: get employee information from company data
<?php
$conn = mysqli_conn(abc, kumar, welcome, company);
$q = ‘select employee name, address , age, birthdate from employee’;
$ab = mysqli_query($q, $conn) or die(‘error’);
While ($row = $mysqli_fetch_row[$ab])
{
echo $row[‘name’];
echo $row[‘address’];
echo $row[‘age’];
}
?>
Above example get all employee name , address, age. In which I use mysql_conn to connect to database & query to pass query & get result. We will see more in next session
Thanks for viewing blog send comment in case any query.

5/22/2018

How to define PHP variable & use in html


Hi,
PHP how to define variable in PHP
Generally use $ symbol to variable some cases const or global is use for global use of variable within file.
What is variable : variable is entity or say object where user can store information or use for such as number, character, string.
Eg:
$ab =100;  this is number or constant form of variable .
$ab = ‘hi’ set of character get string.
$ab =’10.256’ storing float number.
$ab =’<div><p>HI Hello how are you</p></div>’;
Above html code pass into variable so that it can easily call html or reference to number of pages.
  Eg: in one file pass php code & you need this variable to another pages , then call php
By <?php include ‘ab.php’; ?>
& <html>
<body>
<?php echo $sqrt; ?>
</body>
</html>
In above case pass variable in html code & result is in ab.php file $sqrt variable.
Suppose you are connecting to mysql database for getting data. Then call connection & get value in one variable of php file & call it in any number of file i.e. reference passing.
Simple addition program of Variable .
<?php
$a = 10 ;
$b = 50;
$c = $a +$b;
echo $c;
 ?>
In above code output is 60 a & b variable pass to c variable & echo output result.
Note: Semicolon is necessary for each line.
Thanks for viewing blog send comment in case any query.

PHP session, cookie creation & use .



Question : - How create define session variable & what is cookies how to set cookies.
Session are temporary storage variable, by using session you can get variable value in another file .
Session_start();
Session[‘ab’] = ‘hello’;
Session_close();

PHP session is easily started by call it session_start() function. this function first checks if a session is already started and if none is started then it starts one. It is recommended to put the call to session_start() at the beginning of the page.
Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session.
<?php
   session_start();
   if( isset( $_SESSION['ab'] ) ) {
      $_SESSION['ab'] -= 1;
   }else {
      $_SESSION['ab'] = 1;
   }
       
   $msg = "value of ab is ".  $_SESSION['ab'];
   $msg .= "in this session.";
?>

  <html>
   <head>
      <title>define session</title>
   </head>
    <body>
      <?php  echo ( $msg ); ?>
   </body>
   </html>
Similarly use session_destroy() destroy current session.
& session_close() use to close started session.
Let us see cookies , as similar to session cookies are text file to store user information.
An alert or popup message most of site are uses, eg : we are using your cookies to store information for better performance.
<?php
   setcookie("name", "mayor abc", time()+1600, "/","", 0);
   setcookie("age", "34", time()+1600, "/", "",  0);
?>
   <html>
   <head>
   <title>how to define Cookies with PHP</title>
   </head>
   <body>
      <?php echo "hi setting cookies"?>
   </body>
   </html>
In next session we see more detail.
Thanks for viewing blog send comment in case any query.

An Introduction to the Laravel Framework: What It Is and Why You Should Use It

  If you're a PHP developer looking for a modern, efficient, and powerful framework to build web applications, look no further than Lara...