Showing posts with label PHP header. Show all posts
Showing posts with label PHP header. Show all posts

Monday, 20 July 2015

PHP: Ajax PHP Login Page with bootstrap design

Database
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(100) NOT NULL,
  `password` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
)

Bootstrap code
Add below code in index file <head></head> tag
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>

Html
Bootstrap form i have take sample bootstrap form in bootstrap website.
<body>
  <div class="modal-dialog">
    <div class="modal-content col-md-8">
      <div class="modal-header">
        <h4 class="modal-title"><i class="icon-paragraph-justify2"></i> User Login</h4>
      </div>
      <form method="post" id="login_form">
        <div class="modal-body with-padding">
          <div class="form-group">
            <div class="row">
              <div class="col-sm-10">
                <label>Username *</label>
                <input type="text" id="username" name="username" class="form-control required">
              </div>
            </div>
          </div>
          <div class="form-group">
            <div class="row">
              <div class="col-sm-10">
                <label>Password *</label>
                <input type="password" id="password" name="password" class="form-control required" value="">
              </div>
            </div>
          </div>
        </div>
        <div class="error" id="logerror"></div>
        <!-- end Add popup  --> 
        <div class="modal-footer">
          <input type="hidden" name="id" value="" id="id">
          <button type="submit" id="btn-login" class="btn btn-primary">Submit</button>             
        </div>
      </form>
    </div>
  </div>
</body>

Html & ajax code
Above form we seialize() data to pass ajax.php file. if post data (username,password) available page redirect to profile php. Add below code under the above form.
$('#login_form').validate(); - Validate to login form.
<script> 
$(document).ready(function(){
  $('#login_form').validate();  
  $(document).on('click','#btn-login',function(){
    var url = "login.php";      
    if($('#login_form').valid()){
      $('#logerror').html('<img src="ajax.gif" align="absmiddle"> Please wait...'); 
      $.ajax({
      type: "POST",
      url: url,
      data: $("#login_form").serialize(), // serializes the form's elements.
      success: function(data)
      {
        if(data==1) {              
              window.location.href = "profile.php";
        }
        else {  $('#logerror').html('The email or password you entered is incorrect.');
              $('#logerror').addClass("error"); }
        }
        });
    }
    return false;
  });
});
</script>

login.php
extract($_POST); it will convert serialize data to array data.
mysqli_real_escape() string -  check post data special characters.
$db - Database config
<?php
$db = new mysqli('localhost', 'root', '', 'mostlikers');
session_start();
    if($_POST['username']!="" && $_POST['password']!=""):
        extract($_POST);
        $username=mysqli_real_escape_string($db,$_POST['username']);
        $pass_encrypt=md5(mysqli_real_escape_string($db,$_POST['password']));
        $fetch=$db->query("SELECT * FROM `users` WHERE username='$username' AND `password` = '$pass_encrypt'");
        $count=mysqli_num_rows($fetch);
        if($count=="1") :
           $row=mysqli_fetch_array($fetch);
           $_SESSION['login_username']=$row['username'];   
           echo 1; 
        else :
          echo 0;
        endif;
    else :
        header("Location:index.php");
    endif;
?>


profile.php
If user session value is empty, this will redirect to index page.
<?php
session_start();
$check=$_SESSION['login_username'];
if(!isset($check))
{
    header("Location:index.php");
}
?>
<h3 align="center"> Hellow <?php echo $_SESSION['login_username']; ?></h3>
<h2 align="center" >Welcome to mostlikers</h2>
<h4 align="center">  click here to <a href="logout.php">LogOut</a>
</h4>

logout.php
It clear all session data after data clean redirect to login page.
<?php
session_start();
if(session_destroy())
{
header("Location: index.php");
}
?>

Monday, 13 July 2015

PHP redirect – go back to previous page

To go back to the previous page the superglobal variable $_SERVER can be used.
$_SERVER['HTTP_REFERER'] has the link to the previous page.
So to redirect simply :

#Method to go to previous page


function goback(){
    header("Location: {$_SERVER['HTTP_REFERER']}");
    exit;
}
goback();

Friday, 5 June 2015

PHP: Cool GD effect

<?php
$img_disp = imagecreate(1000,1000);
$backcolor = imagecolorallocate($img_disp,0,0,0);
imagefill($img_disp,0,0,$backcolor);
$textcolor = imagecolorallocate($img_disp,255,0,0);
$x1 = 0;
$y1 = 0;
$x2 = 0;
$y2 = 1000;
for(;;){
$y1 = $y1 + 20;
$x2 = $x2 + 20;
imageline($img_disp,$x1,$y1,$x2,$y2,$textcolor);
if ($y1 == 1000){
break;
}
}
header("Content-type: image/png");
imagepng($img_disp); // Draw the image
imagedestroy($img_disp); // Delete the image from the server's memory
?>

Thursday, 4 June 2015

PHP: Shows the current time as a PNG-image

<?php
    //
    // clock.php3 -- shows the current time as a PNG-image

    //
    function set_4pixel($r, $g, $b, $x, $y)
    {
    global $sx, $sy, $pixels;

    $ofs = 3 * ($sx * $y + $x);
    $pixels[$ofs] = chr($r);
    $pixels[$ofs + 1] = chr($g);
    $pixels[$ofs + 2] = chr($b);
    $pixels[$ofs + 3] = chr($r);
    $pixels[$ofs + 4] = chr($g);
    $pixels[$ofs + 5] = chr($b);
    $ofs += 3 * $sx;
    $pixels[$ofs] = chr($r);
    $pixels[$ofs + 1] = chr($g);
    $pixels[$ofs + 2] = chr($b);
    $pixels[$ofs + 3] = chr($r);
    $pixels[$ofs + 4] = chr($g);
    $pixels[$ofs + 5] = chr($b);
    }

    function draw2digits($x, $y, $number)
    {
    draw_digit($x, $y, (int) ($number / 10));
    draw_digit($x + 11, $y, $number % 10);
    }
        
    function draw_digit($x, $y, $digit)
    {
    global $sx, $sy, $pixels, $digits, $lines;
            
    $digit = $digits[$digit];
    $m = 8;
    for ($b = 1, $i = 0; $i < 7; $i++, $b *= 2) {
        if (($b & $digit) == $b) {
        $j = $i * 4;
        $x0 = $lines[$j] * $m + $x;
        $y0 = $lines[$j + 1] * $m + $y;
        $x1 = $lines[$j + 2] * $m + $x;
        $y1 = $lines[$j + 3] * $m + $y;
        if ($x0 == $x1) {
            $ofs = 3 * ($sx * $y0 + $x0);
            for ($h = $y0; $h <= $y1; $h++, $ofs += 3 * $sx) {
            $pixels[$ofs] = chr(0);
            $pixels[$ofs + 1] = chr(0);
            $pixels[$ofs + 2] = chr(0);
            }
        } else {
            $ofs = 3 * ($sx * $y0 + $x0);
            for ($w = $x0; $w <= $x1; $w++) {
            $pixels[$ofs++] = chr(0);
            $pixels[$ofs++] = chr(0);
            $pixels[$ofs++] = chr(0);
            }
        }
        }
    }
    }
        
    // create a chunk with the bytes in $data and the specified
    // type and add it to $result
    function add_chunk($type)
    {
    global $result, $data, $chunk, $crc_table;

    // chunk layout:
    // length: 4 bytes: counting chunk data only
    // chunk type: 4 bytes
    // chunk data: length bytes
    // CRC: 4 bytes: CRC-32 checksum of the type and the data
        
    // copy data and create CRC checksum
    $len = strlen($data);
    $chunk = pack("c*", ($len >> 24) & 255,
        ($len >> 16) & 255,
        ($len >> 8) & 255,
        $len & 255);
    $chunk .= $type;
    $chunk .= $data;

    // calculate a CRC checksum with the bytes chunk[4..len-1]
    $z = 16777215;
    $z |= 255 << 24;
    $c = $z;
    for ($n = 4; $n < strlen($chunk); $n++) {
        $c8 = ($c >> 8) & 0xffffff;
        $c = $crc_table[($c ^ ord($chunk[$n])) & 0xff] ^ $c8;
    }
    $crc = $c ^ $z;

    $chunk .= chr(($crc >> 24) & 255);
    $chunk .= chr(($crc >> 16) & 255);
    $chunk .= chr(($crc >> 8) & 255);
    $chunk .= chr($crc & 255);

    // add it to the result
    $result .= $chunk;
    }


    // ============
    // main program
    // ============

    $sx = 80;
    $sy = 21;
    $pixels = "";
            
    // create filling
    for ($h = 0; $h < $sy; $h++) {
    for ($w = 0; $w < $sx; $w++) {
        $r = 100 / $sx * $w + 155;
        $g = 100 / $sy * $h + 155;
        $b = 255 - (100 / ($sx + $sy) * ($w + $h));
        $pixels .= chr($r);
        $pixels .= chr($g);
        $pixels .= chr($b);
    }
    }
        
    $date = getdate();
    $s = $date["seconds"];
    $m = $date["minutes"];
    $h = $date["hours"];
    $digits = array(95, 5, 118, 117, 45, 121, 123, 69, 127, 125);
    $lines = array(1, 1, 1, 2, 0, 1, 0, 2, 1, 0, 1, 1, 0, 0, 0, 1, 0, 2, 1, 2, 0, 1, 1, 1, 0, 0, 1, 0);
        
    draw2digits(4, 2, $h);
    draw2digits(30, 2, $m);
    draw2digits(56, 2, $s);
    set_4pixel(0, 0, 0, 26, 7);
    set_4pixel(0, 0, 0, 26, 13);
    set_4pixel(0, 0, 0, 52, 7);
    set_4pixel(0, 0, 0, 52, 13);

    // create crc-table
    $z = -306674912;  // = 0xedb88320
    for ($n = 0; $n < 256; $n++) {
        $c = $n;
        for ($k = 0; $k < 8; $k++) {
            $c2 = ($c >> 1) & 0x7fffffff;
            if ($c & 1) $c = $z ^ ($c2); else $c = $c2;
        }
        $crc_table[$n] = $c;
    }

    // PNG file signature
    $result = pack("c*", 137,80,78,71,13,10,26,10);
        
    // IHDR chunk data:
    //   width:              4 bytes
    //   height:             4 bytes
    //   bit depth:          1 byte (8 bits per RGB value)
    //   color type:         1 byte (2 = RGB)
    //   compression method: 1 byte (0 = deflate/inflate)
    //   filter method:      1 byte (0 = adaptive filtering)
    //   interlace method:   1 byte (0 = no interlace)
    $data = pack("c*", ($sx >> 24) & 255,
    ($sx >> 16) & 255,
    ($sx >> 8) & 255,
    $sx & 255,
    ($sy >> 24) & 255,
    ($sy >> 16) & 255,
    ($sy >> 8) & 255,
    $sy & 255,
    8,
    2,
    0,
    0,
    0);
    add_chunk("IHDR");

    // IDAT: image data:
    //    scanline:
    //        filter byte: 0 = none
    //        RGB bytes for the line
    //    the scanline is compressed with "zlib", method 8 (RFC-1950):
    //        compression method/flags code: 1 byte ($78 = method 8, 32k window)
    //        additional flags/check bits:   1 byte ($01: FCHECK = 1, FDICT = 0, FLEVEL = 0)
    //        compressed data blocks:        n bytes
    //            one block (RFC-1951):
    //                bit 0: BFINAL: 1 for the last block
    //                bit 1 and 2: BTYPE: 0 for no compression
    //                next 2 bytes: LEN (LSB first)
    //                next 2 bytes: one's complement of LEN
    //                LEN bytes uncompressed data
    //        check value:  4 bytes (Adler-32 checksum of the uncompressed data)
    //
    $len = ($sx * 3 + 1) * $sy;
    $data = pack("c*", 0x78, 0x01,
        1,
    $len & 255,
    ($len >> 8) & 255,
    255 - ($len & 255),
    255 - (($len >> 8) & 255));
    $start = strlen($data);
    $i2 = 0;
    for ($h = 0; $h < $sy; $h++) {
    $data .= chr(0);
    for ($w = 0; $w < $sx * 3; $w++) {
        $data .= $pixels[$i2++];
    }
    }


    // calculate a Adler32 checksum with the bytes data[start..len-1]
    $s1 = 1;
    $s2 = 0;
    for ($n = $start; $n < strlen($data); $n++) {
    $s1 = ($s1 + ord($data[$n])) % 65521;
    $s2 = ($s2 + $s1) % 65521;
    }
    $adler = ($s2 << 16) | $s1;

    $data .= chr(($adler >> 24) & 255);
    $data .= chr(($adler >> 16) & 255);
    $data .= chr(($adler >> 8) & 255);
    $data .= chr($adler & 255);
    add_chunk("IDAT");

    // IEND: marks the end of the PNG-file
    $data = "";
    add_chunk("IEND");

    // print the image
    header("Content-type: image/png");
    print($result);
?>

PHP: PHP4 AND MySQL Authentication

<?php
require ("auth.php");
if(!isset($PHP_AUTH_USER))  {
   Header("WWW-Authenticate: Basic realm=\"User Login\"");
   Header( "HTTP/1.0 401 Unauthorized");
    echo "You failed to provide the correct password....\n";
   exit;
}
   else {
   $con = mysql_pconnect ("$host", "$user", "$pass")  or die("Error: " . mysql_error());
   mysql_select_db ("$db");
   $user_id = strtolower($PHP_AUTH_USER);
   $result = mysql_query("SELECT password FROM signup " . "Where username = '$user_id'");
   $row = mysql_fetch_array($result);
if ($PHP_AUTH_PW != $row["password"])  {
   Header( "WWW-Authenticate: Basic realm=\"Login failed please try again!\"");
   Header( "HTTP/1.0 401 Unauthorized");
    echo "You failed to provide the correct password....\n";
   exit;
  }
}
?>

Tuesday, 2 June 2015

Mysql: create a simple input / update query to mysql

<?php 
  session_start
(); 
  if (!
ob_start("ob_gzhandler")) 
      
ob_start(); 
  
header("Expires: Mon, 26 Jul 1997 03:00:00 GMT"); 
  
header("Cache-Control: no-cache"); 
  
header("Pragma: no-cache"); 

  
//  url to host 
  
$url "localhost"; 
  
// database user 
  
$dbuser "Your dbuser name"; 
  
//  database user's password 
  
$pwrd "dbuser password"; 

  
//  Show the information_schema 
  
$show_information_schema 1; 

  
$con mysql_connect($url$dbuser$pwrd) or die(mysql_error()); 
  
mysql_set_charset("utf8"$con); ?> 
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<script type="text/javascript">
function GetXmlHttpObject(handler)
{
var objXMLHttp=null
if (window.XMLHttpRequest)
{
     objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
     objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}

function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
         document.getElementById("txtResult").innerHTML= xmlHttp.responseText;
}
else {
         //alert(xmlHttp.status);
}
}

// Will populate data based on input
function htmlData(url, qStr)
{
if (url.length==0)
{
     document.getElementById("txtResult").innerHTML="";
     return;
}
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
     alert ('Please use a browser that support "HTTP Request"');
     return;
}

url=url+"?"+qStr;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true) ;
xmlHttp.send(null);
}
</script>
</head>
<body>
<?php 
  
//  ##############  # FUNCTION START  #  ############## 

  
function get_db($con) 
    { 
      
$i 0; 
      
$res = array(); 

      
$db_list mysql_list_dbs($con); 

      
$cnt mysql_num_rows($db_list); 
      while (
$i $cnt) 
        { 
          
array_push($resmysql_db_name($db_list$i)); 
          
$i++; 
        } 
      if (
count($res) >= 1) 
        { 
          
array_unshift($res"Select database"); 
          return 
$res; 
        } 
      else 
          return array(
" No tables :-( "); 
    } 
  
//  --------------  - 

  
function desc_table($use_table$con) 
    { 
      
$sql "desc $use_table"; 
      
$result mysql_query($sql$con); 

      if (!
is_object($result) && !$result == false) 
        { 
          
$array = array(); 
          while (
$ar mysql_fetch_assoc($result)) 
            { 
              
$tmp[0] = $ar['Field']; 
              
$tmp[1] = $ar['Type']; 
              
array_push($array$tmp); 
            } 
        } 
      return 
$array; 
    } 

  
//  --------------  - 
  
function sql_insert($array$use_table) 
    { 
      
$sql_value ""; 
      
$sql_str "\$sql_query = \"INSERT INTO " $use_table " ("; 

      foreach (
$array as $key => $value) 
        { 
          
$sql_str .= $value[0] . ", "; 
        } 

      
$sql_str substr_replace($sql_str"", -2) . " )VALUES ("; 

      foreach (
$array as $key => $value) 
        { 
          switch (
substr($value[1], 04)) 
            { 
              case 
"char": 
                  
$sql_value .= ' "$' $value[0] . '" ,'; 
                  break; 
              case 
"date": 
                  
$sql_value .= ' "$' $value[0] . '" ,'; 
                  break; 
              case 
"int(": 
                  
$sql_value .= ' $' $value[0] . ' ,'; 
                  break; 
              case 
"text": 
                  
$sql_value .= ' "$' $value[0] . '" ,'; 
                  break; 
              case 
"date": 
                  
$sql_value .= ' "$' $value[0] . '" ,'; 
                  break; 
              case 
"tiny": 
                  
$sql_value .= ' $' $value[0] . ' ,'; 
                  break; 
              case 
"varc": 
                  
$sql_value .= ' "$' $value[0] . '" ,'; 
                  break; 
            } 
        } 

      
$sql_str .= substr_replace($sql_value"", -2) . " )"; 

      return 
$sql_str '";'; 
    } 

  
//  --------------  - 

  
function sql_update($array$use_table) 
    { 
      
$sql_str "\$sql_query = 'UPDATE " $use_table " SET "; 

      foreach (
$array as $key => $value) 
        { 
          switch (
substr($value[1], 04)) 
            { 
              case 
"char": 
                  
$sql_str .= $value[0] . ' = "\'.$' $value[0] . '.\'" ,'; 
                  break; 
              case 
"date": 
                  
$sql_str .= $value[0] . ' = \'.$' $value[0] . '.\', '; 
                  break; 
              case 
"int(": 
                  
$sql_str .= $value[0] . ' = \'.$' $value[0] . '.\', '; 
                  break; 
              case 
"text": 
                  
$sql_str .= $value[0] . ' = "\'.$' $value[0] . '.\'", '; 
                  break; 
              case 
"time": 
                  
$sql_str .= $value[0] . ' = \'.$' $value[0] . '.\', '; 
                  break; 
              case 
"tiny": 
                  
$sql_str .= $value[0] . ' = \'.$' $value[0] . '.\', '; 
                  break; 
              case 
"varc": 
                  
$sql_str .= $value[0] . ' = "\'.$' $value[0] . '.\'", '; 
                  break; 
            } 
        } 

      return 
substr_replace($sql_str"", -2) . " WHERE "; 
    } 

  
//  --------------  - 

  
function get_tables($con$dbname) 
    { 
      
$sql "SHOW TABLES FROM $dbname"; 
      
$result mysql_query($sql); 
      
$res = array(); 
      if (!
$result) 
        { 
          echo 
"DB Error, could not list tables\n"; 
          echo 
'MySQL Error: ' mysql_error(); 
          die; 
        } 

      while (
$row mysql_fetch_row($result)) 
        { 
          
array_push($res$row[0]); 
        } 
      
array_unshift($res"Select table"); 
      return 
$res; 
    } 

  
//  --------------  - 

  
function create_post_var($ar) 
    { 
      foreach (
$ar as $k => $v) 
        { 
          echo 
'$' $v[0] . ' = mysql_real_escape_string($_POST[' "'$v[0]'" ']);<br>'; 
        } 
    } 

  
//  --------------  - 

  
function create_get_var($ar) 
    { 
      foreach (
$ar as $k => $v) 
        { 
          echo 
'$' $v[0] . ' = mysql_real_escape_string($_GET[' "'$v[0]'" ']);<br>'; 
        } 
    } 

  
//  ##############  # FUNCTION END  #  ############## 

  
if (isset($_GET['db'])) 
    { 
      if (
$_GET['db'] == 'Select database') 
          die; 
      
$_SESSION['database'] = $_GET['db']; 
      
$dbname mysql_real_escape_string($_GET['db']); 
      
$table_list get_tables($con$dbname); ?> 

<p></p>
<select value="lopper" name="table_list"
onchange="htmlData(m_insert.php, table=+this.value)" />
<?php 
      
foreach ($table_list as $k => $v) 
        { 
          echo 
'<option>' $v '</option>'; 
        } 
      echo 
'</select></p>'; 

      die; 
    } 

  if (isset(
$_GET['table'])) 
    { 
      
$db_selected mysql_select_db($_SESSION['database'], $con); 

      
$table mysql_real_escape_string($_GET['table']); 

      
$table_array desc_table($table$con); 

      
$sql_str sql_insert($table_array$table); 

      
$sql_update sql_update($table_array$table); 

      echo 
'<p>Table: ' $table '</p>'; 

      echo 
'<p>' $sql_str '</p>'; 

      echo 
'<p>' $sql_update '</p><br>'; 

      echo 
'<p>$_POST to variable</p>'; 
      
create_post_var($table_array); 

      echo 
'<p>$_GET to variable</p>'; 
      
create_get_var($table_array); 
    } 
  else 
    { 
      
$dbs get_db($con); 

      if (
$show_information_schema) 
        { 
          
//  remove information_schema from database list 
          
$res array_search('information_schema'$dbs); 
          unset(
$dbs[$res]); 
        } 
?> 

<select name="db_list"
onchange="htmlData(m_insert.php, db=+this.value)" />
    
 <?php 
      
foreach ($dbs as $k => $v) 
        { 
          echo 
'<option>' $v '</option>'; 
        } 
      echo 
'</select>'; 

      echo 
'<div id="txtResult"> </div>'; 
      die; 
    } 
?>

Friday, 3 October 2014

readfile in PHP

readfile — Outputs a file
Syntax:int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )

Reads a file and writes it to the output buffer.

Parameters :

filename:The filename being read.

use_include_path:You can use the optional second parameter and set it to TRUE, if you want to search for the file in theinclude_path, too.

context:A context stream resource.

Return Values : Returns the number of bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readfile(), an error message is printed.

Example #1 Forcing a download using readfile()

<?php

$file = 'monkey.gif';

if (file_exists($file)) {

header('Content-Description: File Transfer');

header('Content-Type: application/octet-stream');

header('Content-Disposition: attachment; filename='.basename($file));

header('Expires: 0');

header('Cache-Control: must-revalidate');

header('Pragma: public');

header('Content-Length: ' . filesize($file));

readfile($file);

exit;

}

?>

The above example will output something similar to:

Open / Save dialogue
Note:
readfile() will not present any memory issues, even when sending large files, on its own. If you encounter an out of memory error ensure that output buffering is off with ob_get_level().
Tip
A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen()for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.
Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.