I am trying to save cropped image after cropping into a directory but when i click on crop button nothing happens. I am stuck in it from 2 days please someone help me out.
I am getting these errors
Warning: imagecreatefromjpeg(public/image/) [function.imagecreatefromjpeg]: failed to open stream: No such file or directory in C:\wamp\www\ModuleEx.com\application\modules\admin\controllers\IndexController.php on line 64
Warning: imagecreatefromjpeg(public/image/) [function.imagecreatefromjpeg]: failed to open stream: No such file or directory in C:\wamp\www\ModuleEx.com\application\modules\admin\controllers\IndexController.php on line 64
Warning: imagejpeg() [function.imagejpeg]: Unable to open 'public/image/crop' for writing: Permission denied in C:\wamp\www\ModuleEx.com\application\modules\admin\controllers\IndexController.php on line 71
Here is my controller code
if(isset($_FILES['file']['name'])){ //user upload file
$file_name = stripslashes($_FILES['file']['name']);
$ext_idx = strrpos($file_name,".");
if(!$ext_idx) //hide this if ur app can upload without ext
echo "File invalid.";
else{
$ext_length = strlen($file_name) - $ext_idx;
$extension = strtolower(substr($file_name,$ext_idx+1,$ext_length));
//allowed extension
$ext_list = array("pdf", "doc","jpg", "jpeg", "gif", "png");
if(!in_array($extension, $ext_list))
echo "System can't support your extension.";
else{
$size = (2500 * 1024); //2500 Kb
$file_size=filesize($_FILES['file']['tmp_name']);
if($file_size > $size)
echo "File is oversize. Max 2500 Kb.";
else{
//change name
$file_name = rand(10,1000).".".$extension;
$file_obj="public/image/".$file_name;
$copied = copy($_FILES['file']['tmp_name'], $file_obj);
if(!$copied)
echo "Failed.";
else
{
$file_data = array( 'file_name' => $file_name );
$this->view->file_obj=$file_obj;
}
}
}
}
}
Here is my phtml code.
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$targ_w = $targ_h = 150;
$jpeg_quality = 90;
$src = 'file_obj';
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
imagecopyresampled($dst_r,$img_r,0,0,(int)$_POST['x'],(int)$_POST['y'],
$targ_w,$targ_h,(int)$_POST['w'],(int)$_POST['h']);
//header('Content-type: image/jpeg');
imagejpeg($dst_r,'file_obj',$jpeg_quality);
}
?>
<html>
<head>
<script src="public/js/jquery.min.js"></script>
<script src="public/js/jquery.Jcrop.js"></script>
<script src="public/js/jquery.color.js"></script>
<script type="text/javascript">
$(function(){
$('#cropbox').Jcrop({
aspectRatio: 1,
onSelect: updateCoords
});
});
function updateCoords(c)
{
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
};
function checkCoords()
{
if (parseInt($('#w').val())) return true;
alert('Please select a crop region then press submit.');
return false;
};
</script>
<style type="text/css">
#target {
background-color: #ccc;
width: 500px;
height: 330px;
font-size: 24px;
display: block;
}
</style>
<?=$this->headLink()->appendStylesheet('/public/css/demos.css');?>
<?=$this->headLink()->appendStylesheet('/public/css/main.css');?>
<?=$this->headLink()->appendStylesheet('/public/css/jquery.Jcrop.min.css');?>
</head>
<body>
<form id="file_form" method="POST" enctype="multipart/form-data" action="" onsubmit="">
<input type="file" name="file" />
<input type="submit" name="submit" value="Upload"/><br/></br>
<img id="cropbox" src="<?php echo $this->file_obj?>" alt="Image" style="display: block; visibility: visible; width: 602px; height: 400px; border: medium none; opacity: 0.5;"/><br/>
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<input type="submit" value="Crop Image" class="btn btn-large btn-inverse" />
</form>
</body>
</html>
try this:
$names = $_FILES["img"]["name"];
$tmp = $_FILES["img"]["tmp_name"];
$upload_dir = './images';
$move=move_uploaded_file($tmp, "$upload_dir/$names");
$a="./images/".$names;
list($width, $height) = getimagesize($a);
$newwidth = "120";
$newheight = "100";
$thumb = imagecreatetruecolor($newwidth, $newheight);
if($_FILES["img"]["type"]=="image/jpeg"){
$source = imagecreatefromjpeg($a);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb, $a, 100);
}
Maybe this helps.
* Where specifically does your folder(public/image) or it's path stored? Does it also lies with the same directory with your IndexController.php?
This is my code in saving an image in a folder:
$path = "uploads/";
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysql_query("UPDATE lms_users SET userPic='$actual_image_name' WHERE userId='$_SESSION[email]'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
Hopes this helps.
Related
I am trying to make an avatar image upload for user, where they can crop the avatar too. At this moment I'm able to save the normal size of the image on my server, but when I am trying to crop that image it's like the coordinates are fixed, I think on the left top corner.
Here is my form in accounts.php:
<a href="#" data-toggle="modal" data-target="#change-profile">
<div id="profile-result">
<?php if (file_exists('accounts/images/' . $session_username . '.jpg')): ?>
<img src="<?php echo 'accounts/images/' . $session_username . '.jpg'; ?>" alt="" class="thumb-lg img-circle" style="width: 120px; height: 120px;">
<?php else: ?>
<img src="accounts/images/default.png" alt="" class="thumb-lg img-circle" style="width: 120px; height: 120px;">
<?php endif ?>
</div>
</a>
<div class="modal fade" id="change-profile">
<div class="modal-dialog">
<div class="" style="background: #fff; padding: 10px;">
<div class="ajax-response" id="loading"></div>
<h4 class="m-t-5 m-b-5 ellipsis">Change profile</h4>
<div class="image-full-div" style="width: 70%;">
<form action="crop.php" enctype="multipart/form-data" method="post" onsubmit="return checkCoords();">
<p>Image: <input name="image" id="fileInput" type="file" /></p>
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<input name="upload" type="submit" value="Upload" />
</form>
<p><img id="filePreview" style="display:none;"/></p>
</div>
</div>
</div>
</div>
This is my crop.php file for the upload:
<?php
//if upload form is submitted
if(isset($_POST["upload"])){
//get the file information
$error = '';
$fileName = basename($_FILES["image"]["name"]);
$fileTmp = $_FILES["image"]["tmp_name"];
$fileType = $_FILES["image"]["type"];
$fileSize = $_FILES["image"]["size"];
$fileExt = substr($fileName, strrpos($fileName, ".") + 1);
//specify image upload directory
$largeImageLoc = 'accounts/images/'.$fileName;
$thumbImageLoc = 'accounts/images/thumb/'.$fileName;
//check file extension
if((!empty($_FILES["image"])) && ($_FILES["image"]["error"] == 0)){
if($fileExt != "jpg" && $fileExt != "jpeg" && $fileExt != "png"){
$error = "Sorry, only JPG, JPEG & PNG files are allowed.";
}
}else{
$error = "Select a JPG, JPEG & PNG image to upload";
}
//if everything is ok, try to upload file
if(strlen($error) == 0 && !empty($fileName)){
if(move_uploaded_file($fileTmp, $largeImageLoc)){
//file permission
chmod ($largeImageLoc, 0777);
//get dimensions of the original image
list($width_org, $height_org) = getimagesize($largeImageLoc);
//get image coords
$x = (int) $_POST['x'];
$y = (int) $_POST['y'];
$width = (int) $_POST['w'];
$height = (int) $_POST['h'];
//define the final size of the cropped image
$width_new = $width;
$height_new = $height;
//crop and resize image
$newImage = imagecreatetruecolor($width_new,$height_new);
switch($fileType) {
case "image/gif":
$source = imagecreatefromgif($largeImageLoc);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
$source = imagecreatefromjpeg($largeImageLoc);
break;
case "image/png":
case "image/x-png":
$source = imagecreatefrompng($largeImageLoc);
break;
}
imagecopyresampled($newImage,$source,0,0,$x,$y,$width_new,$height_new,$width,$height);
switch($fileType) {
case "image/gif":
imagegif($newImage,$thumbImageLoc);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
imagejpeg($newImage,$thumbImageLoc,90);
break;
case "image/png":
case "image/x-png":
imagepng($newImage,$thumbImageLoc);
break;
}
imagedestroy($newImage);
//remove large image
//unlink($imageUploadLoc);
//display cropped image
echo 'CROP IMAGE:<br/><img src="'.$thumbImageLoc.'"/>';
}else{
$error = "Sorry, there was an error uploading your file.";
}
}else{
//display error
echo $error;
}
}
?>
And my Javascript file:
//set image coordinates
function updateCoords(im,obj){
$('#x').val(obj.x1);
$('#y').val(obj.y1);
$('#w').val(obj.width);
$('#h').val(obj.height);
}
//check coordinates
function checkCoords(){
if(parseInt($('#w').val())) return true;
alert('Please select a crop region then press submit.');
return false;
}
$(document).ready(function(){
//prepare instant image preview
var p = $("#filePreview");
$("#fileInput").change(function(){
//fadeOut or hide preview
p.fadeOut();
//prepare HTML5 FileReader
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("fileInput").files[0]);
oFReader.onload = function (oFREvent) {
p.attr('src', oFREvent.target.result).fadeIn();
};
});
//implement imgAreaSelect plugin
$('img#filePreview').imgAreaSelect({
// set crop ratio (optional)
//aspectRatio: '2:1',
onSelectEnd: updateCoords
});
});
This is my image with the coordinates but I'm not sure because the normal size of the image is 1920/1080
And this image is after I press upload button
I am trying to create a thumb image from an uploaded image and i want to make the thumbnail background color as white...When image uploaded the bg is black...how can i make it white?
HERE IS THE HTML
<!DOCTYPE HTML>
<html>
<head>
<title>PHP upload test</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="">
Select file:<input type="file" name="image" id="image" >
<p>
<input type="submit" value="Upload" name="submit">
</p>
</form>
</body>
</html>
Here is the php code:
<?php
$destination="C:/wamp/www/upload-images/images/";
$thumb_recipient ="C:/wamp/www/upload-images/images/thumbs/";
$thumb_size = 100;
$acceptedMIME= array('image/jpeg', 'image/pjpeg');
if (isset($_POST['submit'])) {
if (is_dir($destination) || is_writable($destination)) { // Check the recipient folder exist
$image = $_FILES['image']['tmp_name'];
$img_name = $_FILES['image']['name'];
$img_type = $_FILES['image']['type'];
if (is_file($image) && is_readable($image)) {
$details = getimagesize($image);
if (is_array($details)) {
$imgOriginalWidth = $details[0];
$imgOriginalHeigth = $details[1];
if ($imgOriginalWidth <= $thumb_size && $imgOriginalHeigth <= $thumb_size) {
$ratio =1;
}
elseif ($imgOriginalWidth > $imgOriginalHeigth) {
$ratio = $thumb_size / $imgOriginalWidth;
}
else
{
$ratio = $thumb_size / $imgOriginalHeigth;
}
$thumbHeigth = round($imgOriginalWidth * $ratio);
$thumbWidth = round($imgOriginalHeigth * $ratio);
$imageName = preg_replace($extensions, '', $img_name);
$ext = pathinfo($img_name, PATHINFO_EXTENSION);
$thumb = imagecreatetruecolor($thumbWidth, $thumbWidth);
if ($ext == 'jpg') {
$resource = imagecreatefromjpeg($image);
imagecopyresampled($thumb, $resource, 0, 0, 0, 0, $thumbWidth, $thumbHeigth, $imgOriginalWidth, $imgOriginalHeigth);
$imgthumbname = $imageName.'.jpeg';
$success = imagejpeg($thumb, $thumb_recipient . $imgthumbname, 100);
if ($success) {
echo "Successful";
}
imagedestroy($thumb);
}
}
else
{
echo "File is invalid..it is not an array";
}
}
else{
echo "Uploaded file cannot be open";
}
}
else
{
echo "The directory folder is not valid";
}
}
?>
You can use http://php.net/manual/en/function.imagefill.php starting at any point of background - probably 0,0 should be good. (If function is not found check if you have GD extension turned on.)
PROBLEM IS CLEAR THANKS FOR FEED BACK
I want to upload image at mysql after square crop using php and jcrop.
I have this type of code but it is not wroking plz help me...
HTML
<form name="upload.php" enctype="multipart/form-data" action="" method="post"class="frmImageUpload">
<label>Profile Picture:</label><br/>
<img id="blah" class="crop" src="pro.png" style="width:500px;maxwidth:500px;height:width;max-height:500px;" border="1" />
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<div class="file_button_container">
<input name="userImage" type="file" id="userImage" /></div>
<input type="submit" value="Upload" class="btnSubmit" />
</from>
Script
<script type='text/javascript' src="http://jcropcdn.tapmodo.com/v0.9.12/js/jquery.Jcrop.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://jcropcdn.tapmodo.com/v0.9.12/css/jquery.Jcrop.min.css">
<style type='text/css'>
#blah {
background-color: #000;
width: 500px;
font-size: 24px;
display: block;
}
</style>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
$('.crop').Jcrop({
onSelect: updateCoords,
bgOpacity: .4,
setSelect: [ 500, 10, 10, 10 ],
aspectRatio: 16 / 16
});
}
reader.readAsDataURL(input.files[0]);
}
}
$("#userImage").change(function(){
console.log(this);
readURL(this);
});
function updateCoords(c)
{
console.log(c);
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
};
});//]]>
</script>
Upload.PHP (I think, It is not work )
<?php
$max_file_size = 1000 * 1024;
if(count($_FILES) > 0) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
if (! $_FILES['image']['error'] && $_FILES['image']['size'] < $max_file_size) {
$conn = mysql_connect("LOCAL", "USERNAME", "PASSWORD");
mysql_select_db("DB NAME");
$nw = $nh = 200;
$x = (int) $_POST['x'];
$y = (int) $_POST['y'];
$w = (int) $_POST['w'] ? $_POST['w'] : $size[0];
$h = (int) $_POST['h'] ? $_POST['h'] : $size[1];
$data = addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
$vImg = imagecreatefromstring($data);
$dstImg = imagecreatetruecolor($nw, $nh);
$imgData = imagecopyresampled($dstImg, $vImg, 0, 0, $x, $y, $nw, $nh, $w, $h);
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
$imgt = $imageProperties['mime'];
$stet = $_POST['stet'];
$sql ="UPDATE users SET
imageType='$imgt',
imageData='$imgData',
stet='$stet'
WHERE id=" . $_SESSION['user']['id'];
$current_id = mysql_query($sql) or die("<b>Error:</b> Problem on Image Insert<br/>" . mysql_error());
if(isset($current_id)) {
header("Location: index.php");
}
}
else
{
echo 'file is too small or large';
}
}}
?>
What is problem in this code plz defind me quickly
I want to store image in MySQL BLOB after jcrop using php..
I want to be able to crop a file three time (so you have a big, medium and small image). The problem right now is that the JCrop is working. Uploading the file works, and you can actually "crop" the file. The problem is that the cropped file is not shown when pressed on the submit button.
As you can see in the code I use a function ShowCrop to keep things tidy, the function is called before the submit form begins. When I run the page I see nothing (no form, no image). Something obviously goes wrong that this function.
I am a beginning PHP scripter, and I am sure there are a lot of faults in this script. Please remind me of those so I can learn!
Here's the code:
<?php
//Original upload
if(isset($_POST['upload'])) {
$name = '_original';
$path_info = pathinfo($_FILES['afbeelding']['name']);
$file_extension = $path_info["extension"];
$newname = $path_info['filename'].$name.".".$file_extension;
move_uploaded_file($_FILES['afbeelding']['tmp_name'], 'images/' . $newname);}
?>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
<script type="text/javascript" src="http://www.noobtutorials.nl/voorbeelden/jquery.js"></script>
<script type="text/javascript" src="js/jquery.Jcrop.js"></script>
<script type="text/javascript">
$( function () {
$('img').Jcrop({
setSelect: [150, 150, 500, 500],
onSelect: function (c) {
$("input[name=x]").val(c.x);
$("input[name=y]").val(c.y);
$("input[name=w]").val(c.w);
$("input[name=h]").val(c.h);
}
});
});
</script>
<?php echo $newname ?>
Big format:
<form method="post" action="upload.php">
<input type="hidden" name="x" value="" />
<input type="hidden" name="y" value="" />
<input type="hidden" name="w" value="" />
<input type="hidden" name="h" value="" />
<input type="hidden" name="fextension" value="<?php echo $file_extension ?>" />
<input type="hidden" name="name" value=<?php echo $newname ?> />
<input type="hidden" name="image" value="images/<?php echo $_FILES['afbeelding'][$newname]; ?>" />
<input type="submit" value="Crop image!" />
</form>
<?php
echo '<img src="getimage.php?file=images/' . $newname . '">';
}
phpinfo();
}
else if(isset($_POST['x'])) //GROOT -> MIDDEL
{
?>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
<script type="text/javascript" src="http://www.noobtutorials.nl/voorbeelden/jquery.js"></script>
<script type="text/javascript" src="js/jquery.Jcrop.js"></script>
<script type="text/javascript">
$( function () {
$('img').Jcrop({
setSelect: [150, 150, 500, 500],
onSelect: function (c) {
$("input[name=x]").val(c.x);
$("input[name=y]").val(c.y);
$("input[name=w]").val(c.w);
$("input[name=h]").val(c.h);
}
});
});
</script>
<?php
echo $_POST['name'];
showCrop($_POST['fextension']);
//echo '<img src="getimage.php?file=images/' . $_POST['name'] . '">';
?> Middel formaat:
<form method="post" action="upload.php">
<input type="hidden" name="x" value="" />
<input type="hidden" name="y" value="" />
<input type="hidden" name="w" value="" />
<input type="hidden" name="h" value="" />
<input type="hidden" name="image" value="images/<?php echo $_FILES['afbeelding'][$newname]; ?>" />
<input type="submit" value="Crop image!" />
</form><?php
}
function showCrop($ext){
$targ_w = $_POST['w'];
$targ_h = $_POST['h'];
$jpeg_quality = 90;
$src = $_POST['image'];
switch($ext)
{
case 'jpg';
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);
//header('Content-type: image/jpeg');
imagejpeg($dst_r,null,$jpeg_quality);
break;
case 'png';
$img_r = imagecreatefrompng($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);
move_uploaded_file($dst_r, 'images/' ."test". $newname);
break;
exit;
}
}
?>
I've rewritten the logic of the code so it'll automatically reload the page until each size/crop has been completed.
This isn't pretty code and is lacking a lot of additional functions (database, security, etc), but it demonstrates how you can achieve what you need (hopefully).
<?php
// Resize image and return filename
function saveCrop($source, $destination) {
// Get extension
$ext = strtolower(pathinfo($source, PATHINFO_EXTENSION));
// Resize/Crop image
switch($ext)
{
case 'jpg';
$img_r = imagecreatefromjpeg($source);
$dst_r = ImageCreateTrueColor($_POST['w'], $_POST['h']);
imagecopyresampled($dst_r,$img_r, 0, 0, $_POST['x'], $_POST['y'], $_POST['w'], $_POST['h'], $_POST['w'], $_POST['h']);
imagejpeg($dst_r, $destination);
return true;
break;
case 'png';
$img_r = imagecreatefrompng($source);
$dst_r = ImageCreateTrueColor($_POST['w'], $_POST['h']);
imagecopyresampled($dst_r,$img_r, 0, 0, $_POST['x'], $_POST['y'], $_POST['w'], $_POST['h'], $_POST['w'], $_POST['h']);
imagepng($dst_r, $destination);
return true;
break;
default:
die('Invalid file extension: ' . $ext);
}
}
// Save uploaded file to web server for future processing
if ( isset($_FILES['uploaded-file']))
{
// Check for valid file type
$ext = strtolower(pathinfo($_FILES['uploaded-file']['name'], PATHINFO_EXTENSION));
if ( ! in_array($ext, array('jpg', 'png')))
{
die('Unsupported file type');
}
$source_file = 'images/original-' . $_FILES['uploaded-file']['name'];
if ( ! move_uploaded_file($_FILES['uploaded-file']['tmp_name'], $source_file))
{
die('Unable to move uploaded file (possibly due to write permissions)');
}
// Set target file
$target_file = 'images/large-' . $_FILES['uploaded-file']['name'];
}
// Process crop/resize requests
elseif (isset($_POST['x']))
{
$source_file = $_POST['source'];
$target_file = $_POST['target'];
saveCrop($source_file, $target_file);
// No more cropping is required after the small image
if (substr($target_file, 0, 12) == 'images/small')
{
header('Location: completed.php');
}
else
{
// Determine new source file
$source_file = $target_file;
// Determine new target file
$target_file = str_replace(
array('images/medium', 'images/large', 'images/original'),
array('images/small', 'images/medium', 'images/large'),
$target_file
);
}
}
?>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
<script type="text/javascript" src="http://www.noobtutorials.nl/voorbeelden/jquery.js"></script>
<script type="text/javascript" src="js/jquery.Jcrop.js"></script>
<script type="text/javascript">
$( function () {
$('img').Jcrop({
setSelect: [150, 150, 500, 500],
onSelect: function (c) {
$("input[name=x]").val(c.x);
$("input[name=y]").val(c.y);
$("input[name=w]").val(c.w);
$("input[name=h]").val(c.h);
}
});
});
</script>
<form method="post" action="">
<input type="text" name="x" value="" />
<input type="text" name="y" value="" />
<input type="text" name="w" value="" />
<input type="text" name="h" value="" />
<input type="text" name="source" value="<?php echo $source_file; ?>" />
<input type="text" name="target" value="<?php echo $target_file; ?>" />
<input type="submit" value="Crop" />
</form>
<img src="<?php echo $source_file; ?>" id="img">
I have some problem regarding to upload the file in PHP. In my coding user can upload only image jpeg/jpg only. I want user also can upload word (.doc , .txt) and image in (.png)
When I upload the image, the image not enter the database but enter the folder file name "upload". This is my code. Hope anyone can help me.Thank you.
<? include "conn.php";?>
<?php
error_reporting(0);
if(isset($_POST['submit']))
{
$target = "uploads/";
$allowedExts = array("jpg", "jpeg", "png", "doc");
$extension = end(explode(".", $_FILES["file_upload"]["name"]));
$target = $target . basename( $_FILES['file_upload']['name']);
$date = date("Y-m-d H:i:s");
//Function to generate image thumbnails
function make_thumb($src, $dest, $desired_width) {
/* read the source image */
$source_image = imagecreatefromjpeg($src);
$width = imagesx($source_image);
$height = imagesy($source_image);
/* find the "desired height" of this thumbnail, relative to the desired width */
$desired_height = floor($height * ($desired_width / $width));
/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
/* copy source image at a resized size */
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
/* create the physical thumbnail image to its destination with 100% quality*/
imagejpeg($virtual_image, $dest,100);
}
//check for allowed extensions
if (($_FILES["file_upload"]["type"] == "image/jpg")|| ($_FILES["file_upload"]["type"] == "image/jpeg") || ($_FILES["file_upload"]["type"] == "image/png")|| ($_FILES["file_upload"]["type"] == "word/doc")&& in_array($extension, $allowedExts))
{
$photoname = $_FILES["file_upload"]["name"];
if (file_exists("../uploads/" . $photoname))
{
die( '<div class="error">Maaf <b>'. $photoname . '</b> telah dimuatnaik sebelum ini</div>');
}
if(move_uploaded_file($_FILES['file_upload']['tmp_name'], $target))
{
$query = "INSERT INTO updown (nama_file,tkh_muatnaik) VALUES ('$photoname','$date')";
mysql_query($query);
$sql = "SELECT MAX(id_gambar) FROM updown";
$max = mysql_query($sql);
$row = mysql_fetch_array($max);
$maxId = $row['MAX(id_gambar)'];
$type = $_FILES["file_upload"]["type"];
switch($type)
{
case "image/jpeg":
$ext = ".jpeg";
break;
case "image/jpg";
$ext = ".jpg";
break;
case "image/png":
$ext = ".png";
break;
case "word/doc":
$ext = ".doc";
break;
}
//define arguments for the make_thumb function
$source = "uploads/".$photoname;
$destination = "thumbnails/thumb_". $maxId . $ext ."";
//specify your desired width for your thumbnails
$width = "282";
//Finally call the make_thumb function
make_thumb($source,$destination,$width);
$msg = '<div class="success">
<b>Muatnaik: </b>' . basename($photoname) . '<br />
<b>Format: </b>' . $_FILES["file_upload"]["type"] . '<br />
<b>Size: </b>' . ceil(($_FILES["file_upload"]["size"] / 1024)) . 'Kb<br />
</div>';
}
else
{
$msg = '<div class="error">Maaf, muatnaik file tidak berjaya</div>';
}
}
else
{
$msg = '<div class="error">Format file ini tidak diterima!</div>';
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" type="text/css" media="all" href="js/jsDatePick_ltr.min.css" />
<script type="text/javascript" src="js/jsDatePick.min.1.3.js"></script>
<script type="text/javascript">
function redirectpage(){
window.location = "daftar_majlis_1.php";
}
<!--
</script>
<link href="css/style_galeri.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table width="70%" align="center">
<tr>
<td colspan="2" class="header"></td>
</tr>
<tr>
<td width="79%"><? include "menu_admin.htm"; ?></td>
</tr>
<tr>
<td><H3 class="main_title">Muat Naik Gambar Disini</H3>(<a href="galeri_admin.php" >Lihat Galeri</a>)
<div id="upload">
<?php echo $msg; ?>
<form action="" method="post" enctype="multipart/form-data">
<label for="file">File:</label>
<input type="file" name="file_upload" id="upload_file" />
<input type="submit" name="submit" value="Upload" />
</form>
</div></td>
<td width="21%"> </td>
</tr>
</table>
</body>
</html>
First of all, in_array are case-sensitive. So try:
$allowedExts = array("jpg", "jpeg", "png", "doc", "txt", "JPG", "JPEG", "PNG", "DOC", "TXT");
Secondly, seems that correct MIME type for .doc document is 'application/msword'.
Try this:
//check for allowed extensions
if (($_FILES["file_upload"]["type"] == "image/jpg")|| ($_FILES["file_upload"]["type"] == "image/jpeg") || ($_FILES["file_upload"]["type"] == "image/png")|| ($_FILES["file_upload"]["type"] == "application/msword")&& in_array($extension, $allowedExts))
...
...
...
//inside the switch
case "application/msword":
$ext = ".doc";
break;
...
You also should make thumbs for image MIME types only.
if (!in_array($ext, array('.doc', '.txt'))) {
//define arguments for the make_thumb function
$source = "uploads/".$photoname;
$destination = "thumbnails/thumb_". $maxId . $ext ."";
//specify your desired width for your thumbnails
$width = "282";
//Finally call the make_thumb function
make_thumb($source,$destination,$width);
}