.

Saturday, 23 August 2014

Upload and Download files in php

Upload and Download files in php

Hey  this  is upload and download in  files in php. it's simple coding to  download  all files to download any files ex:images,excel,ppt,pdf and  this code more  highly used for images download .u can upload and download very easily. u need files folder in  folder.  u can upload   files  moves to  files folder u can need files folder in folder. u needed database to store the upload  file name  and download  to click a file name to  download automatically . i'm bring  to  link to download.php  file this is automatically download files. u no need to change the download files ...,


   
  1. 1st  create a database   database name - demo
  2. 2nd create table  table name - upload and create  column  id and name.
  3. finally run  this file and upload and download a  files and images  
    

Source Code:

Index.php


<?php
$conn=mysql_connect("localhost","root","") or die(mysql_error());
$sdb=mysql_select_db("demo",$conn) or die(mysql_error());
if(isset($_POST['submit'])!=""){
$name=$_FILES['photo']['name'];
$size=$_FILES['photo']['size'];
$type=$_FILES['photo']['type'];
$temp=$_FILES['photo']['tmp_name'];
$caption1=$_POST['caption'];
$link=$_POST['link'];
move_uploaded_file($temp,"files/".$name);
$insert=mysql_query("insert into upload(name)values('$name')");
if($insert){
header("location:index.php");
}
else{
die(mysql_error());
}
}
?>
<html>
<head>
<title>Upload and Download</title>
</head>
<style>
body{ font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;}
a{color:#666;}
#table{margin:0 auto;background:#333;box-shadow: 5px 5px 5px #888888;border-radius:10px;color:#CCC;padding:10px;}
#table1{margin:0 auto;}
</style>
<body>
<h2><a href="http://crackerworld.blogspot.in/">Cracker World</a></h2>
<h3><p align="center">Files Upload And Download</p></h3>
<form enctype="multipart/form-data" action="" name="form" method="post">
<table border="0" cellspacing="0" cellpadding="5" id="table">
<tr>
<th >Chosse Files</th>
<td ><label for="photo"></label><input type="file" name="photo" id="photo" /></td>
</tr>
<tr>
<th colspan="2" scope="row"><input type="submit" name="submit" id="submit" value="Submit" /></th>
</tr>
</table>
</form>
<br />
<br />
<table border="1" align="center" id="table1" cellpadding="0" cellspacing="0">
<tr><td align="center">Click to Download</td></tr>
<?php
$select=mysql_query("select * from upload order by id desc");
while($row1=mysql_fetch_array($select)){
$name=$row1['name'];
?>
<tr>
<td width="300">
<img src="tick.png" width="14" height="14"><a href="download.php?filename=<?php echo $name;?>"><?php echo $name ;?></a>
</td>
</tr>
<?php }?>
</table>
</body>
</html>

Download.php


<?php
function output_file($file, $name, $mime_type='')
{
if(!is_readable($file)) die('File not found or inaccessible!');

$size = filesize($file);
$name = rawurldecode($name);
$known_mime_types=array(
"pdf" => "application/pdf",
"txt" => "text/plain",
"html" => "text/html",
"htm" => "text/html",
"exe" => "application/octet-stream",
"zip" => "application/zip",
"doc" => "application/msword",
"xls" => "application/vnd.ms-excel",
"ppt" => "application/vnd.ms-powerpoint",
"gif" => "image/gif",
"png" => "image/png",
"jpeg"=> "image/jpg",
"jpg" => "image/jpg",
"php" => "text/plain"
);
if($mime_type==''){
$file_extension = strtolower(substr(strrchr($file,"."),1));
if(array_key_exists($file_extension, $known_mime_types)){
$mime_type=$known_mime_types[$file_extension];
} else {
$mime_type="application/force-download";
};
};

@ob_end_clean();


if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
header('Content-Type: ' . $mime_type);
header('Content-Disposition: attachment; filename="'.$name.'"');
header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');
header("Cache-control: private");
header('Pragma: private');
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
if(isset($_SERVER['HTTP_RANGE']))
{
list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
list($range) = explode(",",$range,2);
list($range, $range_end) = explode("-", $range);
$range=intval($range);
if(!$range_end) {
$range_end=$size-1;
} else {
$range_end=intval($range_end);
}
$new_length = $range_end-$range+1;
header("HTTP/1.1 206 Partial Content");
header("Content-Length: $new_length");
header("Content-Range: bytes $range-$range_end/$size");
} else {
$new_length=$size;
header("Content-Length: ".$size);
}
$chunksize = 1*(1024*1024);
$bytes_send = 0;
if ($file = fopen($file, 'r'))
{
if(isset($_SERVER['HTTP_RANGE']))
fseek($file, $range);

while(!feof($file) &&
(!connection_aborted()) &&
($bytes_send<$new_length)
)
{
$buffer = fread($file, $chunksize);
print($buffer);
flush();
$bytes_send += strlen($buffer);
}
fclose($file);
} else

die('Error - can not open file.');
die();
}
set_time_limit(0);
$file_path='files/'.$_REQUEST['filename'];
output_file($file_path, ''.$_REQUEST['filename'].'', 'text/plain');
?>

TribeHR WebHooks to auto-approve vacation requests

<?php
// EXAMPLE: AUTO-APPROVE TIME OFF REQUESTS
//
// This code example illustrates how to listen for newly created requests for time off, then
// automatically approve them (this is great for organizations that have a more flexible time
// off policy). This script listens for a WebHook event, then connects to the site via the REST
// API to get the details and modify the details of the request.
//
// More on WebHooks: http://developers.tribehr.com/api/webhook-event-notification/
// More on the REST Api: http://developers.tribehr.com/api/api-introduction/
//
// PHP API Wrapper: https://github.com/TribeHR/TribeHR-PHP-Client
// Set your TribeHR credentials
define('SUBDOMAIN', ''); // Your TribeHR Sub Domain
define('USER', ''); // The username of an Administrator
define('KEY', ''); // The API KEY of the administrator above
// Include the API Wrapper
require('./TribeHR-PHP-Client/TribeHR.php');
// Let's only process the payload if we're going to actually be getting
// a LeaveRequest. Note - this logic can be easily extende to create a script that
// can handle multiple different WebHook types.
if(isset($_POST['object_id']) && isset($_POST['object']) && $_POST['object'] == 'LeaveRequest')
{
// Create my connection to the site using the API Wrapper
$TribeHRConnection = new TribeHRConnector(SUBDOMAIN, USER, KEY);
// Get the specific Leave Request, as specified by the WebHook data
$id = intval($_POST['object_id']);
$tc = $TribeHRConnection->sendRequest('/leave_requests/'.$id.'.xml', 'GET');
// Create the new request data, based on the old request. Some interesting constraints
// caused by the current API version:
// - date_start and date_end exped m/d/Y format, but the API returns Y-m-d
// - the API requires a complete data object, so all fields must be specified
// - the status APPROVED == 1
$old_request = simplexml_load_string($tc->response);
$new_request = array(
'id' => (string) $old_request->leave_request['id'],
'comments' => (string) $old_request->leave_request['comments'] . "\nAuto-Approved",
'date_start' => date('m/d/Y', strtotime($old_request->leave_request['date_start'])),
'date_end' => date('m/d/Y', strtotime($old_request->leave_request['date_end'])),
'days' => (string) $old_request->leave_request['days'],
'leave_type_id' => (string) $old_request->leave_request['leave_type_id'],
'user_id' => (string) $old_request->leave_request['user_id'],
'status' => 1,
);
// Submit the new data
$tc = $TribeHRConnection->sendRequest('/leave_requests/'.$id.'.xml', 'PUT', $new_request);
// Let's echo our the response for good measure
echo htmlentities($tc->response);
}
else
{
// Since there wasn't a valid payload, let's echo a message out
echo 'This script listens for TribeHR WebHooks to auto-approve vacation requests';
}
?>

Thursday, 21 August 2014

PHP Login Script with Session

User Login Interface

First, we need to create login interface to allow user to submit authentication information. The HTML and CSS code are,
Login Form HTML
<html>
<head>
<title>User Login</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<form name="frmUser" method="post" action="">
<div class="message"><?php if($message!="") { echo $message; } ?></div>
<table border="0" cellpadding="10" cellspacing="1" width="500" align="center">
<tr class="tableheader">
<td align="center" colspan="2">Enter Login Details</td>
</tr>
<tr class="tablerow">
<td align="right">Username</td>
<td><input type="text" name="userName"></td>
</tr>
<tr class="tablerow">
<td align="right">Password</td>
<td><input type="password" name="password"></td>
</tr>
<tr class="tableheader">
<td align="center" colspan="2"><input type="submit" name="submit" value="Submit"></td>
</tr>
</table>
</form>
</body></html>
styles.css
.tableheader {
background
-color: #95BEE6;
color
:white;
font
-weight:bold;
}
.tablerow {
background
-color: #A7D6F1;
color
:white;
}
.message {
color
: #FF0000;
font
-weight: bold;
text
-align: center;
width
: 100%;
}
Login Screen
user_login_screen

PHP Login Script

After creating user login interface, we need to write PHP script. This script will authenticate user and PHP header() to redirectredirect them to their private page on successful login.

User Authentication

In this step we have to,
  • get user login details sent via PHP request methods GET/POST
  • compare user input with database to authenticate
  • add valid authenticated user data into session

Login Ridirect

Once users logged in successfully, then they will be redirected to the user dashboard or profile page or anything. In this example, we have an dashboard page showing Welcome message with logout link. The code for PHP login is,
<?php
session_start();
$message="";
if(count($_POST)>0) {
$conn = mysql_connect("localhost","root","");
mysql_select_db("phppot_examples",$conn);
$result = mysql_query("SELECT * FROM users WHERE user_name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$row  = mysql_fetch_array($result);
if(is_array($row)) {
$_SESSION["user_id"] = $row[user_id];
$_SESSION["user_name"] = $row[user_name];
} else {
$message = "Invalid Username or Password!";
}
}
if(isset($_SESSION["user_id"])) {
header("Location:user_dashboard.php");
}
?>
We can add this code above HTML which will be executed automatically on form submit.
Otherwise, we can save it as individual file with .php extension, for example, login.php. And then, we need to specify this file for form action.

User Dashboard

The code for dashboard page is,
<?php
session_start
();
?>
<html>
<head>
<title>User Login</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<table border="0" cellpadding="10" cellspacing="1" width="500" align="center">
<tr class="tableheader">
<td align="center">User Dashboard</td>
</tr>
<tr class="tablerow">
<td>
<?php
if($_SESSION["user_name"]) {
?>
Welcome
<?php echo $_SESSION["user_name"]; ?>. Click here to <a href="logout.php" tite="Logout">Logout.
<?php
}
?>
</td>
</tr>
</body>
</html>
Welcome message in this page addresses the logged in user by their name. Link logout redirects user to logout.php and clear user login session.
Dashboard Screen
user_dashboad
logout.php
<?php
session_start
();
unset
($_SESSION["user_id"]);
unset
($_SESSION["user_name"]);
header
("Location:user_login_session.php");
?>

Simple Login logout system using php

Simple Login logout system using php

Login and logout system is the most important thing for the user management, session management is one important thing for manage the user for the whole time of login time. for that we have to use session for this. it should have 5 files for this. we have to fetch the same value for the user and check the session and register the session value. and make destroy for logout. let see it detail,
Login logout system

DOWNLOAD             LIVE DEMO
it should need 5 files for this login-logout system, they are
  1. login/index page
  2. datafetch/usercheck page
  3. session/check page
  4. welcome/profile page
  5. logout page

the above files must me needed for this. we can named it as our wish. let see what i done here. and the database file is needed, if you have any doubt about insert coding check here for insert code 

database name --> 2mylogin
table name --> login

DB.PHP

<?php 
$conn=mysql_connect('localhost','root','');
$db=mysql_select_db('2my4edge',$conn);
?>

INDEX.PHP

<?php
session_start();
?>
<
form method="post" name="login" action="login.php">
<
label for="name" class="labelname"> Username </label>
<
input type="text" name="username" id="userid" required="required" /><br />
<
label for="name" class="labelname"> Password </label>
<
input type="password" name="password" id="passid" required="required" /><br />
<
input type="submit" name="submit" id="submit" value="Login" />
</
form>
in the index page we have to start the session, as the above mentioned. action is performed in login.php page.

LOGIN.PHP

<?php 
include('db.php');
session_start();
{
$user=mysql_real_escape_string($_POST['username']);
$pass=mysql_real_escape_string($_POST['password']);
$fetch=mysql_query("SELECT id FROM `login` WHERE 
                         username='$user' and password='$pass'");
$count=mysql_num_rows($fetch);
if($count!="")
{
session_register("sessionusername");
$_SESSION['login_username']=$user;
header("Location:profile.php");
}
else
{
header('Location:index.php');
}

}
?>
if the session is registered then go to check the profile.php page there session.php file is included so the session is checked.

SESSION.PHP

<?php
include('db.php');
session_start();
$check=$_SESSION['login_username'];
$session=mysql_query("SELECT username FROM `login` WHERE username='$check' ");
$row=mysql_fetch_array($session);
$login_session=$row['username'];
if(!isset($login_session))
{
header("Location:index.php");
}
?>
check the session value is correct or not. if the session is value is not set, then again redirect to index.php page.

PROFILE.PHP

<?php
include("session.php");
?>

<h3 align="center"> Hellow <?php echo $login_session; ?></h3>
<h2 align="center" >Welcome to login system</h2>

<h4 align="center"> click here to <a href="logout.php">LogOut</a> </h4>

assign the logout.php page in the profile.php page.

LOGOUT.PHP

<?php
session_start();
if(session_destroy())
{
header("Location: index.php");
}
?>
in the logout.php page, we should unset or destroy the session value as the above you seen. then locate to index.php page.
and we should have to start the session in all the page.

Thursday, 14 August 2014

Image Slideshow Using PHP and simple Jquery

Step 1:Creating our style to beautify our slideshow

to create, open your php editor and paste the code bellow and save it as "slideshow.php."


  1. <html lang="en">



  2. <head>



  3. <title>Simplest jQuery Slideshow</title>



  4.  



  5. <style>



  6. body {font-family:Arial, Helvetica, sans-serif; font-size:12px;}



  7.  



  8. .fadein {



  9. position:relative; height:332px; width:500px; margin:0 auto;



  10. background: url("slideshow-bg.png") repeat-x scroll left top transparent;



  11. padding: 10px;



  12. }



  13. .fadein img { position:absolute; left:10px; top:10px; }



  14. </style>



Step 2: Creating and linking our jquery

To create, copy and paste the code below after the style tag in the file "slideshow.php".


  1. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>



  2. <script>



  3. $(function(){



  4. $('.fadein img:gt(0)').hide();



  5. setInterval(function(){$('.fadein :first-child').fadeOut().next('img').fadeIn().end().appendTo('.fadein');}, 3000);



  6. });



  7. </script>



Step 3: Creating the div tag where the images display

Copy and paste the code below after the script tag of "slideshow.php".


  1. </head>



  2. <body>



  3. <div class="fadein">



  4. <img src="http://chictraveler.wpengine.netdna-cdn.com/wp-content/uploads/2010/09/Picture-91-500x332.png">



  5. <img src="http://sevillespain.info/wp-content/uploads/2012/02/Casa-De-Carmona-Hotel-Seville-casa_de_carmona_galeria_mr_1200-500x332.jpg">



  6. <img src="http://hereelsewhere.com/wp-content/uploads/2012/06/Chambre22-500x332.jpeg">



  7. <img src="http://www.worlddesignhotels.com/wp-content/uploads/407/X%20Ordinary%20Room-500x332.jpg">



  8. <img src="http://armywife101.com/wp-content/uploads/2012/09/DoubleTree-Suites-by-Hilton-exterior-photo-Downtown-Disney-Resort-Area-Hotels-500x332.jpg">



  9. </div>



  10. </body>



  11. </html>



the summarize code will look like the code below


  1. <html lang="en">



  2. <head>



  3. <title>Simplest jQuery Slideshow</title>



  4.  



  5. <style>



  6. body {font-family:Arial, Helvetica, sans-serif; font-size:12px;}



  7.  



  8. .fadein {



  9. position:relative; height:332px; width:500px; margin:0 auto;



  10. background: url("slideshow-bg.png") repeat-x scroll left top transparent;



  11. padding: 10px;



  12. }



  13. .fadein img { position:absolute; left:10px; top:10px; }



  14. </style>



  15.  



  16. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>



  17. <script>



  18. $(function(){



  19. $('.fadein img:gt(0)').hide();



  20. setInterval(function(){$('.fadein :first-child').fadeOut().next('img').fadeIn().end().appendTo('.fadein');}, 3000);



  21. });



  22. </script>



  23.  



  24. </head>



  25. <body>



  26. <div class="fadein">



  27. <img src="http://chictraveler.wpengine.netdna-cdn.com/wp-content/uploads/2010/09/Picture-91-500x332.png">



  28. <img src="http://sevillespain.info/wp-content/uploads/2012/02/Casa-De-Carmona-Hotel-Seville-casa_de_carmona_galeria_mr_1200-500x332.jpg">



  29. <img src="http://hereelsewhere.com/wp-content/uploads/2012/06/Chambre22-500x332.jpeg">



  30. <img src="http://www.worlddesignhotels.com/wp-content/uploads/407/X%20Ordinary%20Room-500x332.jpg">



  31. <img src="http://armywife101.com/wp-content/uploads/2012/09/DoubleTree-Suites-by-Hilton-exterior-photo-Downtown-Disney-Resort-Area-Hotels-500x332.jpg">



  32. </div>



  33. </body>



  34. </html>



Congratulation, you've been successfully created your image slideshow with a very few lines of code.
I also included the file in this tutorial. you can download the file and run it on your computer.
Hope this code helps you.

Difference : Margin & Padding

Set the margin in an element

An element has four sides: right, left, top and bottom. The margin is the distance from each side to the neighboring element (or the borders of the document).
As the first example, we will look at how you define margins for the document itself i.e. for the element <body>. The illustration below shows how we want the margins in our pages to be.
Examples of margins
The CSS code for this would look as follow:
 
body {
margin-top: 100px;
margin-right: 40px;
margin-bottom: 10px;
margin-left: 70px;
}

Or you could choose a more elegant compilation:
 
body {
margin: 100px 40px 10px 70px;
}

You can set the margins in the same way on almost every element. For example, we can choose to define margins for all of our text paragraphs marked with <p>:
 
body {
margin: 100px 40px 10px 70px;
}

p {
margin: 5px 50px 5px 50px;
}


Set padding in an element

Padding can also be understood as "filling". This makes sense as padding does not affect the distance of the element to other elements but only defines the inner distance between the border and the content of the element.
The usage of padding can be illustrated by looking at a simple example where all headlines have background colors:
 
h1 {
background: yellow;
}

h2 {
background: orange;
}

By defining padding for the headlines, you change how much filling there will be around the text in each headline:
 
h1 {
background: yellow;
padding: 20px 20px 20px 80px;
}

h2 {
background: orange;
padding-left:120px;
}

PHP Connect to the MySQL Server

PHP Connect to the MySQL Server


Use the PHP mysqli_connect() function to open a new connection to the MySQL server.

Open a Connection to the MySQL Server

Before we can access data in a database, we must open a connection to the MySQL server.
In PHP, this is done with the mysqli_connect() function.

Syntax

mysqli_connect(host,username,password,dbname);

Parameter Description
host Optional. Either a host name or an IP address
username Optional. The MySQL user name
password Optional. The password to log in with
dbname Optional. The default database to be used when performing queries
Note: There are more available parameters, but the ones listed above are the most important.
In the following example we store the connection in a variable ($con) for later use in the script:
<?php
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>


Close a Connection

The connection will be closed automatically when the script ends. To close the connection before, use the mysqli_close() function:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_close($con);
?>

.

Popular Posts

Powered by Blogger.