jump to navigation

Compress image October 15, 2010

Posted by ashwinisingh in PHP.
Tags: ,
add a comment
<?php

foreach (glob(“here is your path/*.jpg”) as $filename) {
$file = $filename;
$contents = file($file);
$img = imagecreatefromjpeg($file);
header(“Content-Type: image/jpeg”);
imagejpeg($img, $file, 60);
}
?>

php code for resize image November 11, 2009

Posted by ashwinisingh in PHP.
Tags: ,
add a comment

Here $newname will be full path including image name

example https://ashwinisingh.wordpress.com/emages/test.jpg

list($width, $height) = getimagesize($newname) ;
$modwidth = 215;
$modheight=67;
$tn = imagecreatetruecolor($modwidth, $modheight) ;
$image = imagecreatefromjpeg($newname) ;
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;
imagejpeg($tn, $newname,100) ;

Allow direct file download November 9, 2009

Posted by ashwinisingh in PHP.
Tags: , ,
add a comment

Add this code where you want to show download link

<a href=”download.php?f=<? echo $filename; ?>”><img src=”images/down.gif” border=”0″ alt=”Download”></a>

Make file name download.php, copy and paste below mention code

<?php

define(‘ALLOWED_REFERRER’, ”);

// Download folder, i.e. folder where you keep all files for download.
// MUST end with slash (i.e. “/” )
define(‘BASE_DIR’,’../Songs/’);// change according your need

// log downloads?  true/false
define(‘LOG_DOWNLOADS’,true);

// log file name
define(‘LOG_FILE’,’downloads.log’);

// installed on server.
$allowed_ext = array (

// archives
‘zip’ => ‘application/zip’,

// documents
‘pdf’ => ‘application/pdf’,
‘doc’ => ‘application/msword’,
‘xls’ => ‘application/vnd.ms-excel’,
‘ppt’ => ‘application/vnd.ms-powerpoint’,

// executables
‘exe’ => ‘application/octet-stream’,

// images
‘gif’ => ‘image/gif’,
‘png’ => ‘image/png’,
‘jpg’ => ‘image/jpeg’,
‘jpeg’ => ‘image/jpeg’,

// audio
‘mp3’ => ‘audio/mpeg’,
‘wav’ => ‘audio/x-wav’,

// video
‘mpeg’ => ‘video/mpeg’,
‘mpg’ => ‘video/mpeg’,
‘mpe’ => ‘video/mpeg’,
‘mov’ => ‘video/quicktime’,
‘avi’ => ‘video/x-msvideo’
);

####################################################################
###  DO NOT CHANGE BELOW
####################################################################

// If hotlinking not allowed then make hackers think there are some server problems
if (ALLOWED_REFERRER !== ”
&& (!isset($_SERVER[‘HTTP_REFERER’]) || strpos(strtoupper($_SERVER[‘HTTP_REFERER’]),strtoupper(ALLOWED_REFERRER)) === false)
) {
die(“Internal server error. Please contact system administrator.”);
}

// Make sure program execution doesn’t time out
// Set maximum script execution time in seconds (0 means no limit)
set_time_limit(0);

if (!isset($_GET[‘f’]) || empty($_GET[‘f’])) {
die(“Please specify file name for download.”);
}

// Get real file name.
// Remove any path info to avoid hacking by adding relative path, etc.
$fname = basename($_GET[‘f’]);

// Check if the file exists
// Check in subfolders too
function find_file ($dirname, $fname, &$file_path) {

$dir = opendir($dirname);

while ($file = readdir($dir)) {
if (empty($file_path) && $file != ‘.’ && $file != ‘..’) {
if (is_dir($dirname.’/’.$file)) {
find_file($dirname.’/’.$file, $fname, $file_path);
}
else {
if (file_exists($dirname.’/’.$fname)) {
$file_path = $dirname.’/’.$fname;
return;
}
}
}
}

} // find_file

// get full file path (including subfolders)
$file_path = ”;
find_file(BASE_DIR, $fname, $file_path);

if (!is_file($file_path)) {
die(“File does not exist. Make sure you specified correct file name.”);
}

// file size in bytes
$fsize = filesize($file_path);

// file extension
$fext = strtolower(substr(strrchr($fname,”.”),1));

// check if allowed extension
if (!array_key_exists($fext, $allowed_ext)) {
die(“Not allowed file type.”);
}

// get mime type
if ($allowed_ext[$fext] == ”) {
$mtype = ”;
// mime type is not set, get from server settings
if (function_exists(‘mime_content_type’)) {
$mtype = mime_content_type($file_path);
}
else if (function_exists(‘finfo_file’)) {
$finfo = finfo_open(FILEINFO_MIME); // return mime type
$mtype = finfo_file($finfo, $file_path);
finfo_close($finfo);
}
if ($mtype == ”) {
$mtype = “application/force-download”;
}
}
else {
// get mime type defined by admin
$mtype = $allowed_ext[$fext];
}

// Browser will try to save file with this filename, regardless original filename.
// You can override it if needed.

if (!isset($_GET[‘fc’]) || empty($_GET[‘fc’])) {
$asfname = $fname;
}
else {
// remove some bad chars
$asfname = str_replace(array(‘”‘,”‘”,’\\’,’/’), ”, $_GET[‘fc’]);
if ($asfname === ”) $asfname = ‘NoName’;
}

// set headers
header(“Pragma: public”);
header(“Expires: 0”);
header(“Cache-Control: must-revalidate, post-check=0, pre-check=0”);
header(“Cache-Control: public”);
header(“Content-Description: File Transfer”);
header(“Content-Type: $mtype”);
header(“Content-Disposition: attachment; filename=\”$asfname\””);
header(“Content-Transfer-Encoding: binary”);
header(“Content-Length: ” . $fsize);

// download
// @readfile($file_path);
$file = @fopen($file_path,”rb”);
if ($file) {
while(!feof($file)) {
print(fread($file, 1024*8));
flush();
if (connection_status()!=0) {
@fclose($file);
die();
}
}
@fclose($file);
}

// log downloads
if (!LOG_DOWNLOADS) die();

$f = @fopen(LOG_FILE, ‘a+’);
if ($f) {
@fputs($f, date(“m.d.Y g:ia”).”  “.$_SERVER[‘REMOTE_ADDR’].”  “.$fname.”\n”);
@fclose($f);
}

?>

Export table data in Excel or CSV November 9, 2009

Posted by ashwinisingh in PHP.
Tags:
add a comment

<form action=”export2.php” method=”post” enctype=”multipart/form-data” name=”form1″>
<select name=”export” id=”export”>
<option value=”MSEXCEL”>MS EXCEL</option>
<option value=”CSV”>CSV</option>
</select> <img name=”” src=”” width=”50″ height=”1″ alt=”” />
<input name=”Submit” type=”submit” value=” Export ” />
<img src=”” alt=”” name=”www” width=”20″ height=”1″ id=”www” />
<input name=”button” type=”button” onclick=”javascript:window.print()” value=”Print” />
<? //echo $row[‘Q8_Source_of_inquiry’] ;?>
</form>

 

$expt=$_REQUEST[‘export’];
if($expt==’MSEXCEL’)
{
$rand = rand(10000, 99999);
$n=5;
$random=rand(0, pow(10, $n));
$filename = “myExcelFile_”.$random.”.”.”xls”;

header(“Expires: Sat, 01 Jan 2000 00:00:00 GMT”);
header(“Last-Modified: “.gmdate(“D, d M Y H:i:s”).” GMT”);
header(“Pragma: public”);
header(“Expires: 0”);
header(“Cache-Control: must-revalidate, post-check=0, pre-check=0”);
header(“Cache-Control: public”);
header(“Content-Description: File Transfer”);
session_cache_limiter(“must-revalidate”);
header(“Content-Type: application/vnd.ms-excel”);
header(‘Content-Disposition: attachment; filename=”‘ . $filename .'”‘);

$select = $_SESSION[‘exp_export’]; //In this session will be your query example “select * from tablename”;
$export = mysql_query($select);
$fields = mysql_num_fields($export);

for ($i = 0; $i < $fields; $i++)
{
$header .= mysql_field_name($export, $i) . “\t”;
}

while($row = mysql_fetch_row($export)) {
$line = ”;
foreach($row as $value) {
if ((!isset($value)) OR ($value == “”)) {
$value = “\t”;
} else {
$value = str_replace(‘”‘, ‘””‘, $value);
$value = ‘”‘ . $value . ‘”‘ . “\t”;
}
$line .= $value;
}
$data .= trim($line).”\n”;
}
$data = str_replace(“\r”,””,$data);

if ($data == “”) {
$data = “\n(0) Records Found!\n”;
}

print “$header\n$data”;
$_SESSION[‘exp_export’]=”;
exit;
}
else
{
function getExcelData($data){
$retval = “”;
if (is_array($data)  && !empty($data))
{
$row = 0;
foreach(array_values($data) as $_data){
if (is_array($_data) && !empty($_data))
{
if ($row == 0)
{
// write the column headers
$retval = implode(“,”,array_keys($_data));
$retval .= “\n”;
}
//create a line of values for this row…
if(array_keys($_data)==”images”)
{
$retval .= array_values($_data);
$retval .= “\n”;
exit();
}
else
{
$retval .= implode(“,”,array_values($_data));
$retval .= “\n”;
//increment the row so we don’t create headers all over again
$row++;
}
}
}
}
return $retval;
}
//feed the final array to our formatting function…
$contents = getExcelData($_SESSION[‘exp’]);

$filename = “myExcelFile.csv”;

//prepare to give the user a Save/Open dialog…
header (“Content-type: application/octet-stream”);
header (“Content-Disposition: attachment; filename=”.$filename);

//setting the cache expiration to 30 seconds ahead of current time. an IE 8 issue when opening the data directly in the browser without first saving it to a file
$expiredate = time() + 30;
$expireheader = “Expires: “.gmdate(“D, d M Y G:i:s”,$expiredate).” GMT”;
header ($expireheader);

//output the contents
echo $contents;
$_SESSION[‘exp’]=”;
exit();
}

?>

fined ip address November 7, 2009

Posted by ashwinisingh in PHP.
Tags:
1 comment so far

<?php

include(“finedip.php”); // Must include this

// ip must be of the form “192.168.1.100”
// you may load this from a database
$ip = $_SERVER[“REMOTE_ADDR”];
echo “Your IP Address is: ” . $ip . “<br />”;

echo “Your Country is: “;
// returns country code by default
echo getCountryFromIP($ip);
echo “<br />\n”;

// optionally, you can specify the return type
// type can be “code” (default), “abbr”, “name”

echo “Your Country Code is: “;
echo getCountryFromIP($ip, “code”);
echo “<br />\n”;

// print country abbreviation – case insensitive
echo “Your Country Abbreviation is: “;
echo getCountryFromIP($ip, “AbBr”);
echo “<br />\n”;

// full name of country – spaces are trimmed
echo “Your Country Name is: “;
echo getCountryFromIP($ip, ” NamE “);
echo “<br />\n”;

echo $_SERVER[‘REMOTE_ADDR’] ;
?>

Download finedip.php

Before use plz rename  finedip.doc to finedip.php

ftp connection code November 7, 2009

Posted by ashwinisingh in PHP.
Tags:
1 comment so far

<?php
$ftp_server = “www.yoursite.com”;
$ftp_user_name = “username”;
$ftp_user_pass = “password”;
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
if ((!$conn_id) || (!$login_result)) {
echo “FTP connection has failed!”;
echo “Attempted to connect to $ftp_server for user $ftp_user_name”;
exit;
} else {
echo “Connected to $ftp_server, for user $ftp_user_name”;
}
$dir = “”;

function filecollect($dir,$filelist) {
global $conn_id; //Get our ftp
$files = ftp_nlist($conn_id,$dir); //get files in directory
foreach ($files as $file) {
//$isfile = ftp_size($conn_id, $file);
if($isfile == “-1”) { //Is a file or directory?
$filelist = filecollect($dir.’/’.$file,$filelist,$num); //If a folder, do a filecollect on it
}
else {
$filelist[(count($filelist)+1)] = $file; //If not, add it as a file to the file list
}
}
return $filelist;
}

$filelist = filecollect($dir,$filelist);

echo “<pre>”;
print_r($filelist);
echo “</pre>”;

$dir=”yoursite.com”;
$filelist = filecollect($dir,$filelist);

echo “<pre>”;
print_r($filelist);
echo “</pre>”;
$new=explode(“/”,$filelist[’73’]);
$myFile =$new[1];
//echo “$myFile”;
$fh = fopen($myFile, ‘r’) or die(“can’t open file”);
//$fh = fopen($myFile, ‘w’) or die(“can’t open file”);
//$stringData = “Ashwani\n”;
//fwrite($fh, $stringData);

$the = fread($fh, 1000000);
fclose($fh);

?>
<form action=”” method=”post” enctype=”multipart/form-data” name=”form”><table width=”100%” border=”0″>
<tr>
<td><? echo $new[1];  ?></td>
<td><textarea name=”textarea” cols=”40″ rows=”40″><? echo $the; ?></textarea></td>
</tr>
</table>
</form>

Import excel file into mysql data base November 7, 2009

Posted by ashwinisingh in PHP.
Tags:
add a comment

<?
i$db = mysql_connect(“localhost”, “root”, “”) or die(“Could not connect.”);

if(!$db)

die(“no db”);

if(!mysql_select_db(“test”,$db))

die(“No database selected.”);

if(isset($_POST[‘submit’]))

{

$filename=$_POST[‘filename’];

$handle = fopen(“$filename”, “r”);

while (($data = fgetcsv($handle, 1000, “,”)) !== FALSE)

{

$import=”INSERT into sample(name,email) values(‘$data[0]’,’$data[1]’)”;

mysql_query($import) or die(mysql_error());

}

fclose($handle);

print “Import done”;

}

else

{

print “<form action=’import.php’ method=’post’>”;

print “Type file name to import:<br>”;

print “<input type=’text’ name=’filename’ size=’20’><br>”;

print “<input type=’submit’ name=’submit’ value=’submit’></form>”;

}
?>

Page location tracker November 7, 2009

Posted by ashwinisingh in PHP.
Tags:
add a comment

<?
$domain = $_SERVER[‘HTTP_HOST’];
// find out the path to the current file:
$path = $_SERVER[‘SCRIPT_NAME’];
// find out the QueryString:
$queryString = $_SERVER[‘QUERY_STRING’];
// put it all together:

$pieces = explode(“/”, $path);

$count=count($pieces);

for($i=0;$i<= $count;$i++)
{
if($pieces[$i]==”courses.php”)
{

unset($pieces[$i]);
break;
}

}
$newurl = implode(“/”, $pieces);

?>
<form method=”post” action=<? echo “https://&#8221; . $domain . $newurl .”/test.php” ?> name=”frm”>

Delete image (uploaded throw ajax unlimited image) November 6, 2009

Posted by ashwinisingh in PHP.
Tags:
add a comment

require(‘../configuration/config.php’);

$id=$_REQUEST[‘id’];
//echo $id;
$ins=”SELECT * FROM  table  where id='”.$id.”‘ “;
$result=mysql_query($ins);
$row=mysql_fetch_array($result);
$image1=$row[‘images’];
$newimg=(explode(“,”,$image1));
$count=count($newimg);

$countnew=$count-1;

if(isset($_REQUEST[‘action’]))
{

$full=”../uploads/”;
$img=$_REQUEST[‘val’];
$id=$_REQUEST[‘id’];
for($i=0;$i<$countnew;$i++)
{
if($newimg[$i]==$img)
{

unset($newimg[$i]);
//echo found;
}
}
//print_r($newimg);
$updateimg=implode(“,”,$newimg);
$query=”update table  set images='”.$updateimg.”‘where id=’$id'”;
$result=mysql_query($query) or die(“select query not run”);
$path=$full.$img;
if(file_exists($path))
{
unlink($full.$img);
}