filename and contenttype of upload image - image

how to get the name of the file and the content type of the image which we uploaded in mvc application please tell me its urgent
thanks
ritz

May be below code will be helpful..
//index..
<?php
require_once("include/DBConnect.php");
include_once('header.php');
?>
<div align="center">
<h1 style="color:red">Welcome </h1>
<br/>
<form action="upload.php" method="post" enctype="multipart/form-data" id="UploadForm">
<input name="ImageFile" type="file" />
<input type="submit" id="SubmitButton" value="Upload" />
</form>
</div>
<?php include_once('footer.php');?>
//upload
<?php
require_once("include/DBConnect.php");
require_once("include/FunctionGeneral.php");
include_once('header.php');
if(isset($_POST))
{
$ThumbSquareSize = 200; //Thumbnail will be 200x200
$BigImageMaxSize = 500; //Image Maximum height or width
$ThumbPrefix = "thumb_"; //Normal thumb Prefix
$DestinationDirectory = 'uploads/'; //Upload Directory ends with / (slash)
$Quality = 90;
// check $_FILES['ImageFile'] array is not empty
if(!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name']))
{
die('Something went wrong with Upload!'); // output error .
}
// Random number for both file, will be added after image name
$RandomNumber = rand(0, 9999999999);
// Elements (values) of $_FILES['ImageFile'] array
//let's access these values by using their index position
$ImageName = str_replace(' ','-',strtolower($_FILES['ImageFile']['name']));
$ImageSize = $_FILES['ImageFile']['size']; // Obtain original image size
$TempSrc = $_FILES['ImageFile']['tmp_name']; // Tmp name of image file stored in PHP tmp folder
$ImageType = $_FILES['ImageFile']['type']; //Obtain file type, returns "image/png", image/jpeg, text/plain etc.
switch(strtolower($ImageType))
{
case 'image/png':
$CreatedImage = imagecreatefrompng($_FILES['ImageFile']['tmp_name']);
break;
case 'image/gif':
$CreatedImage = imagecreatefromgif($_FILES['ImageFile']['tmp_name']);
break;
case 'image/jpeg':
case 'image/pjpeg':
$CreatedImage = imagecreatefromjpeg($_FILES['ImageFile']['tmp_name']);
break;
default:
die('Unsupported File!'); //output error and exit
}
//PHP getimagesize() function returns height-width from image file stored in PHP tmp folder.
list($CurWidth,$CurHeight)=getimagesize($TempSrc);
//Get file extension from Image name, this will be re-added after random name
$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt = str_replace('.','',$ImageExt);
//remove extension from filename
$ImageName = preg_replace("/\\.[^.\\s]{3,4}$/", "", $ImageName);
//Construct a new image name (with random number added) for our new image.
$NewImageName = $ImageName.'-'.$RandomNumber.'.'.$ImageExt;
//set the Destination Image
$thumb_DestRandImageName = $DestinationDirectory.'thumbnail/'.$ThumbPrefix.$NewImageName; //Thumb name
$DestRandImageName = $DestinationDirectory.$NewImageName; //Name for Big Image
//Resize image to our Specified Size by calling resizeImage function.
if(resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType))
{
//Create a square Thumbnail right after, this time we are using cropImage() function
if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType))
{
echo 'Error Creating thumbnail';
}
/*
At this point we have succesfully resized and created thumbnail image
We can render image to user's browser or store information in the database
For demo, we are going to output results on browser.
*/
echo '<div id="output">';
echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
echo '<tr>';
echo '<td align="center"><img src="'.$thumb_DestRandImageName.'" alt="Thumbnail"></td>';
echo '</tr><tr>';
echo '<td align="center"><img src="'.$DestRandImageName.'" alt="Resized Image"></td>';
echo '</tr>';
echo '</table>';
echo '</div>';
/*
// Insert info into database table!
mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath)
VALUES ($DestRandImageName, $thumb_DestRandImageName, 'uploads/')");
*/
$added = getCurDate();
$title = "test";//$dbObj->escape_special_char($_POST['title']);
session_start();
$_SESSION['user_id'] = "rakhi";
$user_id = $_SESSION['user_id'];
$fields = "`photo_title` ,`createuser` ,`image_name` ,`added`";
$values = "'$title','$user_id','$NewImageName','$added'";
}else{
die('Resize Error'); //output error
}
}
include_once('footer.php');
?>

Related

Get img src within html file in Laravel

How can i get the image if I was given a URL with lots of img src? I am using Laravel 5.2.
This takes too long to load given that I have 6,000 links. Thanks in advance.
$url="$products->product_url";
$html = file_get_contents($url);
$doc = new DOMDocument();
#$doc->loadHTML($html);
$tags = $doc->getElementsByTagName('img');
foreach ($tags as $tag) {
echo $tag->getAttribute('src');
}
Firstable you need to find some kind of class of id of parent element that contain image that you need for example:
<body>
// bla-bla-bla
<div class="content">
<img src="img.png" />
</div>
</body>
You can do follow with ZendDomQuery:
$finder = new Zend_Dom_Query($html);
$node = $finder->query("div[class~='content'] img");

image src is not displaying the page in php

**I'm trying to upload the img path in database and show them in the slider, but the problem is the img src is not showing the page assigned. Can any body tell me why the image src is not loading the page.
my code is below slider.php slider has this image code :<img src='<?php echo "imagetest.php?id=$id" ?> width="200"> the image path couldn't display the page imagetest.php has following code: this page is not showing up in img src of the slider if (empty($_GET['id']) || !is_numeric($_GET['id'])) {
echo 'A valid image file id is required to display the image file.';
exit;
}
$imageId = $_GET['id'];
//connect to mysql database
if ($conn = mysqli_connect('localhost', 'root', 'root', 'test')) {
$content = mysqli_real_escape_string($conn, $content);
$sql = "SELECT type, content FROM images where id = {$imageId}";
if ($rs = mysqli_query($conn, $sql)) {
$imageData = mysqli_fetch_array($rs, MYSQLI_ASSOC);
mysqli_free_result($rs);
} else {
echo "Error: Could not get data from mysql database. Please try again.";
}
//close mysqli connection
mysqli_close($conn);
} else {
echo "Error: Could not connect to mysql database. Please try again.";
}
if (!empty($imageData)) {
// show the image.
header("Content-type: {$imageData['type']}");
echo $imageData['content'];
}
?>
Use file_get_contents
<img src="<?php echo file_get_contents('imagetest.php?id='. $id);?>" width="200"/>
and remove header(), u don't need it.
In php file
function track(){
header('Content-Type: image/gif');
$image = 'image.gif';
echo file_get_contents($image);
}
In view file
<img src="track.php" width="200"/>
Hope it's help ^^

Why this error comes as per i upload multiple images?

When i upload multiple images from my code, everything is uploaded to mysql database, but displays error with saying success :
I just don't want this error.[Error is :Notice: Undefined variable: user_id in C:\wamp\www\swaminarayant\multiple_file_up.php on line 13]
Can anyone help me out of this?
My code is:
<?php include 'connect.php';?>
<?php
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
$desired_dir="user_data";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==false){
move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
}else{ // rename the file if another one exist
$new_dir="$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
mysql_query($query);
}else{
print_r($errors);
}
}
if(empty($error)){
echo "Success";
}
}?
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" multiple/>
<input type="submit"/>
</form>
Look at your Code around Line 13:
$query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES
('$user_id','$file_name','$file_size','$file_type'); ";
Within the VALUES part you try to include a variable $user_id which was never defined above.
Youre setting the other values properly:
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_type=$_FILES['files']['type'][$key];
But you are missing a definition for $user_id. If you insert for example:
$user_id = "foo";
Or
$user_id = 1;
In case it must be a number you should be all good.

add submit to delete comment using ajax , php

Hi, I use a php code to view the all comments to any post from my sql and I want to add a submit button to every comment in order to delete it without refreshing the page, I mean using AJAX i don't know how to write that codes and connect it with html codes i want add submit like this :
<form>
<input type="submit" id="deletecomment">
</form>
and connected it with AJAX and delete.php page to delete the comment (ajax,delete.php)???????
this is my codes
$result = mysql_query ("select * from post_comments WHERE link ='$getlink' order by link asc");
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$link = $row['link'];
$time = $row['time'];
$content = nl2br($row['content']);
$name = ($row['link'] != '') ? '<h3 style="color:blue">'.$row['name'].'</h3>' : $row['name'];
$imge = $row['imge'];
echo '
<div class="commentuserbackground">
<img src="'.$imge.'" width="30px" height="30px">
<div id="comment-'.$id.'" class="username1">'.$name.'</div>
<div class="username2">'.$content.'</div><div class="commenttime"><h4 style="color:#5a5a5a">'.$time.'</h4>
</div></div>';
}
If you already have the jquery lib included in your html, you could do something like this:
# html page
<button data-id="1" class="delete_comment" /> # no need to wrap in form
# At the bottom of the body tag
$(".delete_comment").click(function(e){
e.preventDefault();
var $button = $(this), $comment = $button.parent(), id = $button.data("id");
$.ajax({
type: 'DELETE',
url: "/path/to/comment/" + id,
success: function(){ $comment.remove(); }
});
});

Joomla custom component adding browse button

I am developing a component in J! 2.5 and want to add a browse button on the backend so the user can pick a file they have previously uploaded. How would I go about this?
This is what I have come up with, if someone can make it more robust and reusable, that would be great. I may do it myself later, but for now I have an impossible deadline.
loadDir.php:
<?php
if(isset($_GET['dir'])) {
//Get array of valid extensions
if(isset($_GET['ext'])) {
if($_GET['ext'] == 'pdf') $validext = array("pdf");
else $validext = array("jpg", "jpeg", "png", "gif");
} else {
$validext = array("pdf", "jpg", "jpeg", "png", "gif");
}
$root = dirname(dirname(dirname(getcwd()))) . "/";
$directory = $root . $_GET['dir'];
$files = scandir($directory);
$thumb_count = 1;
//make sure we haven't gone too high (should never be called)
if(strpos($directory, 'images') == false) $directory = $root . "images";
//TODO: sort array with dirs in front
foreach($files as $file) {
if ($file == '.') continue; //Remove current directory from loop
//If in the images folder, don't let them go higher
if ($file == '..' & $_GET['dir'] == 'images') continue;
$path = $_GET['dir'];
if($file == '..') {
$path = dirname($path);
} else {
$path .= "/".$file;
}
if(is_dir($directory."/".$file)) {
echo "[DIR]".$file."".PHP_EOL;
} else {
//Check to see it's a valid extension
$ext = pathinfo($file, PATHINFO_EXTENSION);
$num = rand(0,100);
if(in_array($ext, $validext)) echo "[FILE]".$file."".PHP_EOL;
}
if(($thumb_count % 5) == 0) echo "<br/>";
$thumb_count++;
}
} else {
echo "Error loading: Directory not available";
}
?>
administrator/components/com_XXX/views/XXX/tmpl/form.php:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
selected_file = "";
function select(id, file) {
$('#' + id).css('background-color', 'red');
selected_file = file;
}
function loadDir(div, path, ext) {
$('#'+div+'Window').load('<?php echo JURI::root();?>administrator/components/com_lot/loadDir.php?div='+div+'&ext='+ext+'&dir='+path);
}
$(document).ready(function() {
$('#floorOpen').on("click", function(){
loadDir('floor', 'images', 'pdf');
$('#floorDialog').show();
});
$('#floorClose').on("click", function(){
$('#floorDialog').hide();
if(selected_file != "") $('#floor_plan').val(selected_file);
selected_file = "";
});
$('#floorCancel').on("click", function(){
$('#floorDialog').hide();
selected_file = "";
});
$('#mainOpen').on("click", function(){
loadDir('main', 'images', 'img');
$('#mainDialog').show();
});
$('#mainClose').on("click", function(){
$('#mainDialog').hide();
if(selected_file != "") $('#main_image').val(selected_file);
selected_file = "";
});
$('#mainCancel').on("click", function(){
$('#mainDialog').hide();
selected_file = "";
});
});
</script>
......
<div id="floorDialog" style="position:absolute;display:none;width:400px;height:300px;border:1px solid #c0c0c0;background-color:#f0f0f0;top:800px;left:400px;">
<div id="floorWindow" style="position:relative;width: 390px;height: 250px;margin: 4px;border: 1px solid #c0c0c0;">
</div>
CancelOK
</div>
<div id="mainDialog" style="position:absolute;display:none;width:400px;height:300px;border:1px solid #c0c0c0;background-color:#f0f0f0;top:800px;left:400px;">
<div id="mainWindow" style="position:relative;width: 390px;height: 250px;margin: 4px;border: 1px solid #c0c0c0;">
</div>
CancelOK
</div>
....
<tr>
<td width="100" align="right" class="key">
<label for="main_image">
<?php echo JText::_( 'Main Image' ); ?>:
</label>
</td>
<td>
<input class="text_area" type="text" name="main_image" id="main_image" size="32" maxlength="250" value="<?php echo $this->lotdata->main_image;?>" />Browse
</td>
</tr>
<tr>
<td width="100" align="right" class="key">
<label for="floor_plan">
<?php echo JText::_( 'Floor Plan' ); ?>:
</label>
</td>
<td>
<input class="text_area" type="text" name="floor_plan" id="floor_plan" size="32" maxlength="250" value="<?php echo $this->lotdata->floor_plan;?>" />Browse
</td>
</tr>
Basically I use AJAX to get a formatted list of files/directories. Then, using javascript we select the file we want and output the path on dialog close.
I think you can use the built in Joomla! form field filelist for this
<field name="myfile" type="filelist" default="" label="Select a file" description="" directory="administrator" filter="" exclude="" stripext="" />
Full options are:
The filelist form field type provides a drop down list of files from a specified directory. If the field has a saved value this is selected when the page is first loaded. If not, the default value (if any) is selected.
Params.filelist.jpg
By default, the first item on the list is '- Do not use -' (which is translatable) and is given the value '-1' and this is followed by '- Use default -' (also translatable) given the value '0'.
type (mandatory) must be filelist.
name (mandatory) is the unique name of the field.
label (mandatory) (translatable) is the
descriptive title of the field. directory (optional) is the
filesystem path to the directory containing the files to be listed.
If omitted the directory given by JPATH_ROOT is assumed.
default (optional) is the default file name.
description (optional)
(translatable) is text that will be shown as a tooltip when the user
moves the mouse over the drop-down box.
filter (optional) is a
regular expression string which is used to filter the list of files
selected for inclusion in the drop-down list. If omitted, all files
in the directory are included. The filter argument expression is
applied before the exclude argument expression. For information on
constructing regular expressions see Regular expressions in parameter
arguments.
exclude (optional) is a regular expression string which is
used to exclude files from the list. The exclude argument expression
is applied after the filter argument expression. For information on
constructing regular expressions see Regular expressions in parameter
arguments.
stripext (optional) is a Boolean argument. If true then
file name extensions will be stripped from the file names listed.
Also note that the file name will be saved without the extension too.
hide_none (optional) is a Boolean argument. If true, the '- Do not
use -' item is omitted from the drop-down list.
hide_default
(optional) is a Boolean argument. If true, the '- Use default -' item
is omitted from the drop-down list.
Here's where I got the list, I'm aware I'm not supposed to just link so I copied/pasted but I'll provide the original link in case the docs get updated.
https://docs.joomla.org/Filelist_form_field_type

Resources