Post form method with already existing post in page - php

I have a post method in my php page that is called once the page is created. Now I have a form on this same page and when you click it it should "refresh" the page with an image that is cropped. I get weird text on my screen when I run this:
First post method:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if($_FILES['afbeelding']['error'] == 0) {
$imageinfo = getimagesize($_FILES['afbeelding']['tmp_name']);
if(filesize($_FILES['afbeelding']['tmp_name']) > 204800) {?> <script type="text/javascript"> alert("Maximale bestandsgrootte: 200KB"); window.location = "/inside.php"</script> <?php }
else{
move_uploaded_file($_FILES['afbeelding']['tmp_name'], 'images/' . $_FILES['afbeelding']['name']);}
The form:
<form method="post" action="?action=showCrop">
<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']['name']; ?>" />
<input type="submit" value="Verklein afbeelding!" name="submit"/>
</form>
<?php
echo '<img src="getimage.php?file=images/' . $_FILES['afbeelding']['name'] . '">';
And the method that should be called after submitting the form:
function showCrop(){
$targ_w = $_POST['w'];
$targ_h = $_POST['h'];
$jpeg_quality = 90;
$src = $_POST['image'];
$ext = end(explode(".", $_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);
exit;
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']);
//header('Content-type: image/png');
imagepng($dst_r,null,8);
exit;
break;
}
}

Related

Image resize, crop and upload to server and database

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

my cropped image is just a black colored box of 2KB?

Im using the following PHP code to save a cropped image from jcrop.
$targ_w = $targ_h = 150;
$jpeg_quality = 90;
$src = "../profiles/";
$src = $target . basename( $_FILES['userfile']['name']);
$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']);
imagejpeg($dst_r, "simple2.jpg", $jpeg_quality);
A simple2.jpg does get saved in the directory, but it is just a black colored square of size 2 KB. I want the cropped part to be saved. How to fix this?
Use this
index.php
<html lang="en" >
<head>
<meta charset="utf-8" />
<meta name="author" content="Script Tutorials" />
<title>HTML5 Image uploader with Jcrop | Script Tutorials</title>
<!-- add styles -->
<link href="css/main.css" rel="stylesheet" type="text/css" />
<link href="css/jquery.Jcrop.min.css" rel="stylesheet" type="text/css" />
<!-- add scripts -->
<script src="js/jquery.min.js"></script>
<script src="js/jquery.Jcrop.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<header>
<h2>HTML5 Image uploader with Jcrop </h2>
</header>
<div class="demo">
<div class="bheader"><h2>-- Image upload form --</h2></div>
<div class="bbody">
<!-- upload form -->
<form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php" onsubmit="return checkForm()">
<!-- hidden crop params -->
<input type="hidden" id="x1" name="x1" />
<input type="hidden" id="y1" name="y1" />
<input type="hidden" id="x2" name="x2" />
<input type="hidden" id="y2" name="y2" />
<h2>Step1: Please select image file</h2>
<div>
<input type="file" name="image_file" id="image_file" onchange="fileSelectHandler()" />
</div>
<div class="error"></div>
<div class="step2">
<h2>Step2: Please select a crop region</h2>
<img id="preview" />
<div class="info">
<label>File size</label>
<input type="text" id="filesize" name="filesize" />
<label>Type</label>
<input type="text" id="filetype" name="filetype" />
<label>Image dimension</label>
<input type="text" id="filedim" name="filedim" />
<label>W</label> <input type="text" id="w" name="w" />
<label>H</label> <input type="text" id="h" name="h" />
</div>
<input type="submit" value="Upload" />
</div>
</form>
</div>
</div>
</body>
</html>
upload.php
<?php
function uploadImageFile() { // Note: GD library is required for this function
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// $iWidth = $iHeight = 200; // desired image result dimensions
$iWidth=abs($_POST['x2']-$_POST['x1']);
$iHeight=abs($_POST['y2']-$_POST['y1']);
$iJpgQuality = 90;
if ($_FILES) {
// if no errors and size less than 250kb
if (! $_FILES['image_file']['error'] && $_FILES['image_file']['size'] < 250 * 1024) {
if (is_uploaded_file($_FILES['image_file']['tmp_name'])) {
// new unique filename
$sTempFileName = 'cache/' . md5(time().rand());
// mkdir("cache",0664,true);
chmod('cache', 0664);
//echo $url = $_SERVER['SERVER_NAME'] . dirname(__FILE__);
//echo '<br>';
$root=$_SERVER['DOCUMENT_ROOT'];
$newsTempFileName = $root.'/beta/nikhil/demo/jquery-images-direct-crop/'.$sTempFileName;
// move uploaded file into cache folder
move_uploaded_file($_FILES['image_file']['tmp_name'], $newsTempFileName);
// change file permission to 644
#chmod($sTempFileName, 0644);
if (file_exists($sTempFileName) && filesize($sTempFileName) > 0) {
$aSize = getimagesize($sTempFileName); // try to obtain image info
if (!$aSize) {
#unlink($sTempFileName);
return;
}
// check for image type
switch($aSize[2]) {
case IMAGETYPE_JPEG:
$sExt = '.jpg';
// create a new image from file
$vImg = #imagecreatefromjpeg($sTempFileName);
break;
case IMAGETYPE_PNG:
$sExt = '.png';
// create a new image from file
$vImg = #imagecreatefrompng($sTempFileName);
break;
default:
#unlink($sTempFileName);
return;
}
// create a new true color image
$vDstImg = #imagecreatetruecolor( $iWidth, $iHeight );
// copy and resize part of an image with resampling
imagecopyresampled($vDstImg, $vImg, 0, 0, (int)$_POST['x1'], (int)$_POST['y1'], $iWidth, $iHeight, (int)$_POST['w'], (int)$_POST['h']);
// define a result image filename
$sResultFileName = $sTempFileName . $sExt;
// output image to file
imagejpeg($vDstImg, $sResultFileName, $iJpgQuality);
#unlink($sTempFileName);
return $sResultFileName;
}
}
}
}
}
}
$sImage = uploadImageFile();
echo '<img src="'.$sImage.'" />';
?>
Live Demo : https://www.script-tutorials.com/demos/316/index.html
add jquery and css

How to show cropped image on same page

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">

Image not saving into directory after cropping

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.

Multiple Upload Forms

I have a number of upload file forms that need validating (shortened example):
<form>
<input type='file' name='file[]' class='file_upload_button'>
<input type='file' name='file[]' class='file_upload_button'>
<input type='file' name='file[]' class='file_upload_button'>
<input type='file' name='file[]' class='file_upload_button'>
<input type='submit' value='Save Draft' class='save_draft_button'>
</form>
And I want each upload input to be validated by file type, but I'm having a hard to understanding what needs to be done. This is the kind of thing I'm trying, but evidently it's not right!
if (! empty($_FILES['file']['name'][0])) {
// VALIDATION goes here
}
But I can't figure out how to select, for example, the first upload field - I've tried using $_FILES['file']['name'][0] but to no avail. Any hep would be appreciated!
By chance, I wrote the following script yesterday.
This is for resizing images, PNG or GIF or JPEG.
This requires './tmp' directory.
If you like, please refer to this.
<?php
$html = PHP_EOL;
if (!empty($_FILES['images'])) {
$finfo = new finfo(FILEINFO_MIME);
for ($i=0;;$i++) {
switch (true) {
case (!isset($_FILES['images']['tmp_name'][$i])):
break 2;
case (!is_uploaded_file($filename = $_FILES['images']['tmp_name'][$i])):
case (($type = $finfo->file($filename)) === false):
continue 2;
case ($type === 'image/png; charset=binary'):
$img = imagecreatefrompng($filename);
break;
case ($type === 'image/jpeg; charset=binary'):
$img = imagecreatefromjpeg($filename);
break;
case ($type === 'image/gif; charset=binary'):
$img = imagecreatefromgif($filename);
break;
default:
continue 2;
}
list($width, $height) = getimagesize($filename);
$new_width = 100;
$new_height = (int)($new_width * $height / $width);
$new_img = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled(
$new_img, $img,
0, 0, 0, 0,
$new_width, $new_height, $width, $height
);
switch (true) {
case ($type === 'image/png; charset=binary'):
imagepng($new_img, $filename);
break;
case ($type === 'image/jpeg; charset=binary'):
imagejpeg($new_img, $filename);
break;
default:
imagegif($new_img, $filename);
}
$new_filename = './tmp/'.basename($filename);
if (move_uploaded_file($filename,$new_filename))
$html .= sprintf('<p><img src="%s" /></p>'.PHP_EOL, $new_filename);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Resizer</title>
<style>
label { display: block; }
</style>
</head>
<body>
<fieldset>
<legend>Select Image File (PNG, JPEG, GIF available)</legend>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>">
<label><input type="file" name="images[]" /></label>
<label><input type="file" name="images[]" /></label>
<label><input type="file" name="images[]" /></label>
<label><input type="submit" value="Resize!" /></label>
</form>
</fieldset>
<fieldset>
<legend>Resized Images</legend><?php
echo $html;
?>
</fieldset>
</body>
</html>

Categories