Wednesday, 20 November 2013

Make Entry Form in Zend Framwork 2

 
Zend Framework 2 uses a module system and you organise your main application-specific code within each module. The Application module provided by the skeleton is used to provide bootstrapping, routing and error configuration to the whole application. It is usually used to provide application level controllers for, the home page of an application.
 

1.Set a New Module like :

 zf2-tutorial/
     /module
         /UserView
             /config
             /src
                 /UserView
                     /Controller
                     /Form
                     /Model
             /view
                 /user-view
                     /user-view
 
 
 2.Open application/application-config.php, add new module "UserView"

    'modules' => array(
        'Application',
        'UserView',     
    ),

3.Create new table in your database which will define in global.php2

Create New Table :

CREATE TABLE IF NOT EXISTS `tbl_teambeachbody` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(100) NOT NULL,
  `password` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

4.Make UserView\Form\UserViewForm;

<?php

namespace UserView\Form;

use Zend\Form\Form;

class UserSignupForm extends Form {
    public function __construct($name = null) {
        // we want to ignore the name passed
        parent::__construct('UserSignUp');
        $this->setAttribute('method', 'post');
       
     $this->add(array(
            'name' => 'email',
            'type' => 'Email',
            'options' => array(
                'label' => 'Email',
            ),
        ));
    
      $this->add(array(
            'name' => 'password',
            'type' => 'password',
            'options' => array(
                'label' => 'Password',
            ),
        ));
    
      $this->add(array(
            'name' => 'cpassword',
            'type' => 'password',
            'options' => array(
                'label' => 'Confirm Password',
            ),
        ));
      $this->add(array(
            'name' => 'signup',
            'type' => 'submit',
            'options' => array(
                'label' => 'Sign up',
            ),
        ));
     
    }
}
?>

5.Make view/user-view/user-view/signup.phtml

<?php
// module/UserView/view/userview/userview/edit.phtml:

$title = 'SIGNUP';
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>

<?php
$form = $this->form;
//var_dump($form);die;
$form->setAttribute('action', $this->url(
                'userview', array(
            'action' => 'signup',
                )
));
$form->prepare();
?>
<?php
echo $this->form()->openTag($form);
?>
<table class="table-bordered">

    <tr class="row">
        <td><?php echo $this->formRow($form->get('email')); ?></td>
    </tr>
    <tr class="row">
        <td><?php echo $this->formRow($form->get('password')); ?></td>
    </tr>

    <tr class="row">
        <td><?php echo $this->formRow($form->get('cpassword')); ?></td>
    </tr>
    <tr class="row">
        <td><?php echo $this->formRow($form->get('signup')) ?></td>
    </tr>

</table>
<?php
echo $this->form()->closeTag($form);
?>

6. Make UserView/Model/UserSignUp.php 

<?php

namespace UserView\Model;

// Add these import statements
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
use Zend\Db\Adapter\Adapter;

class UserSignUp implements InputFilterAwareInterface {

    public $id;
    public $email;
    public $password;
  
    protected $inputFilter;

    public function __construct() {
       
    }

        public function exchangeArray($data) {
        $this->id = (isset($data['id'])) ? $data['id'] : null;
        $this->email = (isset($data['email'])) ? $data['email'] : null;
        $this->password = (isset($data['password'])) ? $data['password'] : null;
    }

    public function getArrayCopy() {
        return get_object_vars($this);
    }

    // Add content to these methods:
    public function setInputFilter(InputFilterInterface $inputFilter) {
        throw new \Exception("Not used");
    }

    public function getInputFilter() {
        if (!$this->inputFilter) {
            $inputFilter = new InputFilter();
            $factory = new InputFactory();

            $inputFilter->add($factory->createInput(array(
                        'name' => 'id',
                        'required' => true,
                        'filters' => array(
                            array('name' => 'Int'),
                        ),
            )));
           
            $inputFilter->add($factory->createInput(array(
                        'name' => 'email',
                        'required' => true,
                        'filters' => array(
                            array('name' => 'StripTags'),
                            array('name' => 'StringTrim'),
                        ),
                        'validators' => array(
                            array(
                                'name' => 'StringLength',
                                'options' => array(
                                    'encoding' => 'UTF-8',
                                    'min' => 1,
                                    'max' => 100,
                                ),
                            ),
                        ),
            )));

            $inputFilter->add($factory->createInput(array(
                        'name' => 'password',
                        'required' => true,
                        'filters' => array(
                            array('name' => 'StripTags'),
                            array('name' => 'StringTrim'),
                        ),
                        'validators' => array(
                            array(
                                'name' => 'StringLength',
                                'options' => array(
                                    'encoding' => 'UTF-8',
                                    'min' => 1,
                                    'max' => 15,
                                ),
                            ),
                        ),
            )));
     
            $this->inputFilter = $inputFilter;
        }

        return $this->inputFilter;
    }

}

 7. Make UserView/Model/UserSignUpTable.php 

<?php

namespace UserView\Model;

use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Adapter\Adapter;

class UserSignUpTable {

    protected $tableGateway;

    public function __construct(TableGateway $tableGateway) {
       
        $params = array('host'      =>'localhost',
                      'username'  =>'root',
                      'password'  =>'',
                      'dbname'    =>'mdc'
                     );
          
        $this->tableGateway = new Zend_Db_Adapter_Pdo_Mysql($params);
    }


    public function saveUserView(UserView $userview) {
        $data = array(
            'email' => $userview->email,
            'password' => $userview->password
        );
       
       
            $this->tableGateway->insert('tbl_teambeachbody',$data);
       
    }


}

8. Make UserView/Controller/UserViewController.php 

<?php

namespace UserView\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel      

use UserView\Form\UserSignupForm;   // <-- Add this importuse UserView\Model\UserSignUp;   // <-- Add this importuse Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Sql;

class UserViewController extends AbstractActionController {

    public function signupAction() {

        $form = new UserSignupForm();

        $form->get('signup')->setValue('Sign Up');

        $request = $this->getRequest();
        if ($request->isPost()) {

            $signup = new UserSignUp();
            $form->setInputFilter($signup->getInputFilter());

            $form->setData($request->getPost());


            if ($request->getPost('email') != "" && $request->getPost('password') != "" && $request->getPost('password') == $request->getPost('cpassword')) {


                $sm = $this->getServiceLocator();
                $dbAdapter1 = $sm->get('Zend\Db\Adapter\Adapter');
                $sql = new Sql($dbAdapter1);
                $insert = $sql->insert('tbl_teambeachbody');
                       
                $data = array(
                    'email' => $request->getPost('email'),
                    'password' => $request->getPost('password')
                );
                $insert->values($data);
                $statement = $sql->prepareStatementForSqlObject($insert);
                $result = $statement->execute();
                //print_R($result);
                return $this->redirect()->toRoute('userview', array(
                            'action' => 'edit'
                ));
            }
        }

       return array('form' => $form);
    }

}




Monday, 18 November 2013

Check Page Rank Of Google in PHP


1.Create Prclass.php : -
class PR {
public function get_google_pagerank($url) {
$query="http://toolbarqueries.google.com/tbr?client=navclient-auto&ch=".$this->CheckHash($this->HashURL($url)). "&features=Rank&q=info:".$url."&num=100&filter=0";
$data=file_get_contents($query);
$posstr = strpos($data, "Rank_");
if($posstr === false){} else{
$page_rank = substr($data, $posstr + 9);
return $page_rank;
}
}
public function StrToNum($Str, $Check, $Magic)
{
$Int32Unit = 4294967296; // 2^32
$lengthofstring = strlen($Str);
for ($i = 0; $i < $lengthofstring ; $i++) {
$Check *= $Magic;
if ($Check >= $Int32Unit) {
$Check = ($Check - $Int32Unit * (int) ($Check / $Int32Unit));
$Check = ($Check < -2147483648) ? ($Check + $Int32Unit) : $Check;
}
$Check += ord($Str{$i});
}
return $Check;
}
public function HashURL($String)
{
$Check1 = $this->StrToNum($String, 0x1505, 0x21);
$Check2 = $this->StrToNum($String, 0, 0x1003F);
$Check1 >>= 2;
$Check1 = (($Check1 >> 4) & 0x3FFFFC0 ) | ($Check1 & 0x3F);
$Check1 = (($Check1 >> 4) & 0x3FFC00 ) | ($Check1 & 0x3FF);
$Check1 = (($Check1 >> 4) & 0x3C000 ) | ($Check1 & 0x3FFF);
$T1 = (((($Check1 & 0x3C0) << 4) | ($Check1 & 0x3C)) <<2 ) | ($Check2 & 0xF0F );
$T2 = (((($Check1 & 0xFFFFC000) << 4) | ($Check1 & 0x3C00)) << 0xA) | ($Check2 & 0xF0F0000 );
return ($T1 | $T2);
}
public function CheckHash($Hashnum)
{
$CheckByte = 0;
$Flag = 0;
$HashStr = sprintf('%u', $Hashnum) ;
$length = strlen($HashStr);
for ($i = $length - 1; $i >= 0; $i --) {
$Re = $HashStr{$i};
if (1 === ($Flag % 2)) {
$Re += $Re;
$Re = (int)($Re / 10) + ($Re % 10);
}
$CheckByte += $Re;
$Flag ++;
}
$CheckByte %= 10;
if (0 !== $CheckByte) {
$CheckByte = 10 - $CheckByte;
if (1 === ($Flag % 2) ) {
if (1 === ($CheckByte % 2)) {
$CheckByte += 9;
}
$CheckByte >>= 1;
}
}
return '7'.$CheckByte.$HashStr;
} }
******************************************************************
2.Create Myfile.php :-
require("Prclass.php"); $url='Enter You URL ';
$pr = new PR(); echo "$url contain Google PageRank: ". $pr->get_google_pagerank($url) ;
********************************************************************** Enter Your Url in the place Of $url = " " Check Page Rank .

How to export DB in PHP


If your database is too large to import using phpMyAdmin or you do not have a package that allows SSH access, you can perform import/export actions using the PHP script. The process is the same whether you are importing or exporting. The only difference will be in the actual PHP script.
 
1.Create index.php :-
<a href="db_back.php">Export</a>
2.Create db_back.php :-
<?php
ob_start();
$username = "root";
$password = "";
$hostname = "localhost";
$dbname = "";
$command = "mysqldump.exe -p -u root demo";
if ($password)
$command.= "--password=". $password ." ";
$command.= $dbname;
system($command);
$dump = ob_get_contents();
ob_end_clean();
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($dbname . "_" .
date("Y-m-d_H-i-s").".sql"));
flush();
echo $dump;
exit();
?>

Upload File in PHP


FILE UPLOAD

Keep this Code in Your Project, create two file

1. index.php and 2. upload.php Create An index.php here :-

 <html> 
<body>
  <form enctype="multipart/form-data" action="upload.php" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
    Choose a file to upload: <input name="uploaded_file" type="file" />
    <input type="submit" value="Upload" />
  </form> 
</body> 
</html>

Create An upload.php here :-

<?php 
//Check that we have a file
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) 
{
 //Check if the file is JPEG image and it's size is less than 350Kb $filename = basename($_FILES['uploaded_file']['name']); 
 $ext = substr($filename, strrpos($filename, '.') + 1);
 if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && ($_FILES["uploaded_file"]["size"] < 350000)) 
 {
 //Determine the path to which we want to save this file
 $newname = dirname(__FILE__).'/upload/'.$filename; 
 //Check if the file with the same name is already exists on the server
 if (!file_exists($newname)) { 
 //Attempt to move the uploaded file to it's new place 
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { 
 echo "It's done! The file has been saved as: ".$newname; } 
 else { 
 echo "Error: A problem occurred during file upload!"; 
 } 
 } 
 else { 
 echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists"; } 
 }
 else
 { 
 echo "Error: Only .jpg images under 350Kb are accepted for upload"; 
 }
 }
 else { echo "Error: No file uploaded";}
 ?>

How to Download File In Zip Format php

Create an zip.php:-

<?php

/**
 * Zip file creation class.
 * Makes zip files.
 */
class zipfile {

    var $datasec = array();
    var $ctrl_dir = array();
    var $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
    var $old_offset = 0;

    /**
     * Converts an Unix timestamp to a four byte DOS date and time format (date
     * in high two bytes, time in low two bytes allowing magnitude comparison).
     */
    function unix2DosTime($unixtime = 0) {
        $timearray = ($unixtime == 0) ? getdate() : getdate($unixtime);
        if ($timearray['year'] < 1980) {
            $timearray['year'] = 1980;
            $timearray['mon'] = 1;
            $timearray['mday'] = 1;
            $timearray['hours'] = 0;
            $timearray['minutes'] = 0;
            $timearray['seconds'] = 0;
        } // end if
        return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) |
                ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
    }

// end of the 'unix2DosTime()' method

    /**
     * Function to force the download of the archive as soon as it is created
     */
    public function forceDownload($archiveName) {
        if (ini_get('zlib.output_compression')) {
            ini_set('zlib.output_compression', 'Off');
        }
// Security checks
        if ($archiveName == "") {
            echo "<html><title>Public Photo Directory - Download </title><body><BR><B>ERROR:</B> The download file was NOT SPECIFIED.</body></html>";
            exit;
        } elseif (!file_exists($archiveName)) {
            echo "<html><title>Public Photo Directory - Download </title><body><BR><B>ERROR:</B> File not found.</body></html>";
            exit;
        }

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private", false);
        header("Content-Type: application/zip");
        header("Content-Disposition: attachment; filename=" . basename($archiveName) . ";");
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: " . filesize($archiveName));
        readfile("$archiveName");
    }

    /**
     * Adds "file" to archive
     */
    function addFile($data, $name, $time = 0) {
        $name = str_replace('\\', '/', $name);
        $dtime = dechex($this->unix2DosTime($time));
        $hexdtime = '\x' . $dtime[6] . $dtime[7]
                . '\x' . $dtime[4] . $dtime[5]
                . '\x' . $dtime[2] . $dtime[3]
                . '\x' . $dtime[0] . $dtime[1];

        eval('$hexdtime = "' . $hexdtime . '";');
        $fr = "\x50\x4b\x03\x04";
        $fr .= "\x14\x00"; // ver needed to extract
        $fr .= "\x00\x00"; // gen purpose bit flag
        $fr .= "\x08\x00"; // compression method
        $fr .= $hexdtime; // last mod time and date
// "local file header" segment
        $unc_len = strlen($data);
        $crc = crc32($data);
        $zdata = gzcompress($data);
        $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2); // fix crc bug
        $c_len = strlen($zdata);
        $fr .= pack('V', $crc); // crc32
        $fr .= pack('V', $c_len); // compressed filesize
        $fr .= pack('V', $unc_len); // uncompressed filesize
        $fr .= pack('v', strlen($name)); // length of filename
        $fr .= pack('v', 0); // extra field length
        $fr .= $name;

        // "file data" segment

        $fr .= $zdata;

// "data descriptor" segment (optional but necessary if archive is not
// served as file)
        $fr .= pack('V', $crc); // crc32
        $fr .= pack('V', $c_len); // compressed filesize
        $fr .= pack('V', $unc_len); // uncompressed filesize
// add this entry to array
        $this->datasec[] = $fr;
// now add to central directory record
        $cdrec = "\x50\x4b\x01\x02";
        $cdrec .= "\x00\x00"; // version made by
        $cdrec .= "\x14\x00"; // version needed to extract
        $cdrec .= "\x00\x00"; // gen purpose bit flag
        $cdrec .= "\x08\x00"; // compression method
        $cdrec .= $hexdtime; // last mod time & date
        $cdrec .= pack('V', $crc); // crc32
        $cdrec .= pack('V', $c_len); // compressed filesize
        $cdrec .= pack('V', $unc_len); // uncompressed filesize
        $cdrec .= pack('v', strlen($name)); // length of filename
        $cdrec .= pack('v', 0); // extra field length
        $cdrec .= pack('v', 0); // file comment length
        $cdrec .= pack('v', 0); // disk number start
        $cdrec .= pack('v', 0); // internal file attributes
        $cdrec .= pack('V', 32); // external file attributes - 'archive' bit set
        $cdrec .= pack('V', $this->old_offset); // relative offset of local header

        $this->old_offset += strlen($fr);
        $cdrec .= $name;
        $this->ctrl_dir[] = $cdrec;
    }

    function file() {
        $data = implode('', $this->datasec);
        $ctrldir = implode('', $this->ctrl_dir);
        return $data .
                $ctrldir .
                $this->eof_ctrl_dir .
                pack('v', sizeof($this->ctrl_dir)) . // total # of entries "on this disk"
                pack('v', sizeof($this->ctrl_dir)) . // total # of entries overall
                pack('V', strlen($ctrldir)) . // size of central dir
                pack('V', strlen($data)) . // offset to start of central dir
                "\x00\x00"; // .zip file comment length
    }

    function addFiles($files /* Only Pass Array */) {
        foreach ($files as $file) {
            if (is_file($file)) { //directory check
                $data = implode("", file($file));
                $new_file = $this->prefix_name . end(explode('/', $file));
                $this->addFile($data, $new_file);
            }
        }
    }

    function output($file) {
        $fp = fopen($file, "w");
        fwrite($fp, $this->file());
        fclose($fp);
    }

}
?>

Create an myfile.php:-

include_once('./../vendors/zip/zip.php');
$zip_file = 'ask2link_php.zip'; // name for downloaded zip file
$ziper = new zipfile();
$ziper->prefix_name = 'folder/'; // here you create folder which will contain downloaded files
$ziper->addFile(/* Add Your File Here */); // array of files
$ziper->output($zip_file);
$ziper->forceDownload($zip_file);
@unlink($zip_file);

Sunday, 17 November 2013

Make Virtual Hosts Using Wamp Server

Apply Few Steps : 

1. Go to "C:/Windows/System32/drivers/etc" and open the "hosts" file in Notepad.









when You open the hosts file,
It Will Appear like :

# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
#   127.0.0.1       localhost
#   ::1             localhost


At the bottom of the hosts file, below all the other text, add a new line with the following:

127.0.0.1   myproject.com    
2. Open "C:/wamp/bin/apache/Apache2.2.21/conf/" (your Apache version number may be different)
Just to edit in one file-
 one called
  •  "httpd.conf",
Add caption










 Open the file  and
At line 467, under "# Virtual hosts", uncomment (remove the hashtag [#]) before the line "Include conf/extra/httpd-vhosts.conf":

# Virtual hosts
Include conf/extra/httpd-vhosts.conf



3.Go to "C:/wamp/bin/apache/Apache2.2.21/conf/extra"












and open the file "httpd.vhosts.conf". It should look like this:
#
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.

#
# Use name-based virtual hosting.
#
NameVirtualHost *:80

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ServerName or ServerAlias in any <VirtualHost> block.
#
add this in last end of the file
<VirtualHost *:80>
    ServerAdmin webmaster@dummy-host2.example.com
    DocumentRoot "D:\wamp\www\mydemoproject"
    ServerName  
myproject.com
    ErrorLog "logs/dummy-host2.example.com-error.log"
    CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

4. Click on the green WAMP icon in your toolbar and select "Restart all Services", then wait for the icon to turn back to green.



5. Open your browser and navigate to "myproject.com",