Image uploader to use incremental image names - php

I am using a php multiple image uploader fine - the code is below. I am trying to modify it to assign incremental image names to the batch of images eg. Image1.jpg, Image2.jpg, Image3.jpg etc rather than a random name. I have tried changing the random code to a variable but no luck. Can anyone please help.
$ThumbSquareSize = 125; //Thumbnail will be 200x200
$BigImageMaxSize = 600; //Image Maximum height or width
$ThumbPrefix = "thumb_"; //Normal thumb Prefix
$Reference_No = $_POST['Reference_No'];
$DestinationDirectory = 'properties/'.$Reference_No.'/'; //Upload Directory ends with / (slash)
$Quality = 75;
//ini_set('memory_limit', '-1'); // maximum memory!
foreach($_FILES as $file)
{
// some information about image we need later.
$ImageName = $file['name'];
$ImageSize = $file['size'];
$TempSrc = $file['tmp_name'];
$ImageType = $file['type'];
if (is_array($ImageName))
{
$c = count($ImageName);
echo '<ul>';
for ($i=0; $i < $c; $i++)
{
$processImage = true;
$RandomNumber = rand(0, 9999999999); // We need same random name for both files.
if(!isset($ImageName[$i]) || !is_uploaded_file($TempSrc[$i]))
{
echo '<div class="error">Error occurred while trying to process <strong>'.$ImageName[$i].'</strong>, may be file too big!</div>'; //output error
}
else
{
//Validate file + create image from uploaded file.
switch(strtolower($ImageType[$i]))
{
case 'image/png':
$CreatedImage = imagecreatefrompng($TempSrc[$i]);
break;
case 'image/gif':
$CreatedImage = imagecreatefromgif($TempSrc[$i]);
break;
case 'image/jpeg':
case 'image/pjpeg':
$CreatedImage = imagecreatefromjpeg($TempSrc[$i]);
break;
default:
$processImage = false; //image format is not supported!
}
//get Image Size
list($CurWidth,$CurHeight)=getimagesize($TempSrc[$i]);
//Get file extension from Image name, this will be re-added after random name
$ImageExt = substr($ImageName[$i], strrpos($ImageName[$i], '.'));
$ImageExt = str_replace('.','',$ImageExt);
//Construct a new image name (with random number added) for our new image.
$NewImageName = $RandomNumber.'.'.$ImageExt;
//Set the Destination Image path with Random Name
$thumb_DestRandImageName = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumb name
$DestRandImageName = $DestinationDirectory.$NewImageName; //Name for Big Image
//Resize image to our Specified Size by calling resizeImage function.
if($processImage && resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType[$i]))
{
//Create a square Thumbnail right after, this time we are using cropImage() function
if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType[$i]))
{
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.
*/
//Get New Image Size
list($ResizedWidth,$ResizedHeight)=getimagesize($DestRandImageName);
$DestinationDirectory = 'properties/'.$Reference_No;
echo '<li><table width="100%" border="0" cellpadding="4" cellspacing="0">';
echo '<tr>';
echo '<td align="center"><img src="'.$DestinationDirectory.$ThumbPrefix.$NewImageName.'" alt="Thumbnail" height="'.$ThumbSquareSize.'" width="'.$ThumbSquareSize.'"></td>';
echo '</tr><tr>';
echo '<td align="center"><img src="'.$DestinationDirectory.$NewImageName.'" alt="Resized Image" height="'.$ResizedHeight.'" width="'.$ResizedWidth.'"></td>';
echo '</tr>';
echo '</table></li>';
/*
// Insert info into database table!
mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath)
VALUES ($DestRandImageName, $thumb_DestRandImageName, 'uploads/')");
*/
}else{
echo '<div class="error">Error occurred while trying to process <strong>'.$ImageName[$i].'</strong>! Please check if file is supported</div>'; //output error
}
}
}
echo '</ul>';
}
}

you have 2 options
save the number to a file and read the file next time and add to it
keep a list of files in database table and get the last files index and add to it

You already have a for loop incrementing the integer variable $i, so change this:
//Construct a new image name (with random number added) for our new image.
$NewImageName = $RandomNumber.'.'.$ImageExt;
to the following code:
//Construct a new image name (with random number added) for our new image.
$NewImageName = 'Image'.$i.'.'.$ImageExt;

Related

delete uploaded image, upload new image and change database reference

<?php
$image = $_FILES['image'];
//name of new file selected
$imagename = $image['name'];
//name of file in database
$filename = $row['filename'];
//folder to move image
$TARGET_PATH = "../$university/img/users/$category/$username/";
//if imagename in DB is different to image just selected
if ($filename <> $imagename) {
// *** Include the class
include("resize-class.php");
//if the filename in DB different from filename chosen
//delete old image
unlink("../$university/img/users/$oldcategory/$username/$filename");
//create random number and add that to the beginning of new imagename
$uniqueID = uniqid();
$imagetitle = $imagename;
$fileunique = $uniqueID;
$fileunique .= $imagetitle;
$filename = $fileunique;
//upload new selected file
$oldpath = $_FILES['image']['tmp_name'];
// Lets attempt to move the file from its temporary directory to its new home
if (move_uploaded_file($oldpath, $TARGET_PATH)) {
// NOTE: This is where a lot of people make mistakes.
// We are *not* putting the image into the database; we are putting a reference to the file's location on the server
$imagename = $fileunique;
$path = "../$university/img/users/$category/$usernameid/$imagename";
// *** 1) Initialise / load image
$resizeObj = new resize($path);
if (exif_imagetype($path) == IMAGETYPE_JPEG) {
$exif = exif_read_data($path);
$ort = $exif['IFD0']['Orientation'];
switch ($ort) {
case 1: // nothing
break;
case 2: // horizontal flip
$resizeObj->flipImage($public, 1);
break;
case 3: // 180 rotate left
$resizeObj->rotateImage($public, 180);
break;
case 4: // vertical flip
$resizeObj->flipImage($public, 2);
break;
case 5: // vertical flip + 90 rotate right
$resizeObj->flipImage($public, 2);
$resizeObj->rotateImage($public, -90);
break;
case 6: // 90 rotate right
$resizeObj->rotateImage($public, -90);
break;
case 7: // horizontal flip + 90 rotate right
$resizeObj->flipImage($public, 1);
$resizeObj->rotateImage($public, -90);
break;
case 8: // 90 rotate left
$resizeObj->rotateImage($public, 90);
break;
}
}
if (($resizeObj->width > 600) || ($resizeObj->height > 600)) {
// *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
$resizeObj->resizeImage(400, 400, 'crop');
// *** 3) Save image
$resizeObj->saveImage($path, 95);
}
//change filename in database
$query = "UPDATE people SET filename=? WHERE id=? AND username=?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $filename);
$stmt->bindParam(2, $id);
$stmt->bindParam(3, $username);
$stmt->execute();
}
}
?>
I am trying to create a form where users can change an image that they have previously uploaded.
I have posted my code above, it gets as far as 'unlinking' the old image but doesn't seem to do anything after that with no errors.
I am trying to get the code to:
Check the newly selected image name against the name stored in the database
if they are different delete the old image in the folder
upload the new image with random number at the beginning of image name
update the database with the new filename
Any ideas where I'm going wrong? Thanks for your help
Here are some thoughts about code:
as suggested by Aditya use something like sprintf('%s%s', uniqid(), $imagename)
check $_FILES for any error (maybe file is too big)
you are saving image ONLY if it has width or height more then 600 px(not sure if rotating will automatically save the image)
check if you have enough rights to write into directory(maybe you need to create folders first)

Image resize in php?

How can i resize proportionaly image in php without "squishing" ? I need some solution, i was searching here, but i could't find anything what i need.
What i have:
<?php
if (isset($_SESSION['username'])) {
if (isset($_POST['upload'])) {
$allowed_filetypes = array('.jpg', '.jpeg', '.png', '.gif');
$max_filesize = 10485760;
$upload_path = 'gallery/';
$filename = $_FILES['userfile']['name'];
$ext = substr($filename, strpos($filename, '.'), strlen($filename) - 1);
if (!in_array($ext, $allowed_filetypes)) {
die('The file you attempted to upload is not allowed.');
}
if (filesize($_FILES['userfile']['tmp_name']) > $max_filesize) {
die('The file you attempted to upload is too large.');
}
if (!is_writable($upload_path)) {
die('You cannot upload to the specified directory, please CHMOD it to 777.');
}
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path.$filename)) {
$q = mysqli_query($connection, "UPDATE users SET avatar='".$_FILES['userfile']['name']."' WHERE username ='".$_SESSION['username']."'");
echo "<font color='#5cb85c'>Браво, успешно си качил/а профилна снимка!</font>";
} else {
echo 'There was an error during the file upload. Please try again.';
}
}
echo ' <form action="images.php" method="post" enctype="multipart/form-data"> ';
echo ' <input type="file" name="userfile"/>';
echo ' <input type="submit" name="upload" value="Качи">';
echo ' </form>';
} else {
echo "<font color='#ec3f8c'>Съжелявам! За да качиш снимка във профила си, <a href='login.php'><font color='#ec3f8c'><b> трябва да се логнеш</b> </font></a></font>";
}
?>
I want to add something like this:Click here
how i call images?
echo '<a href="profiles.php?id='.$rowtwo['id'].'">';
echo"<img src='gallery/".$rowtwo['avatar']."' width='170px' height='217px'/>";
echo'</a>';
I save my image of avatar in DB in users as avatar.
It's much easier to use JS. It also works better because you're letting the client do the slow work of manipulation vs using your finite server resources for that task.
Here's a sample:
//This is the URL to your original image
var linkUrl = "http://www.mywebsite.com/myimage.png";
//This is a div that is necessary to trick JS into letting you manipulate sizing
//Just make sure it exists and is hidden
var img = $('#HiddenDivForImg');
//This is a call to the function
image_GetResizedImage(img, linkUrl);
//This function does the magic
function image_GetResizedImage(img, linkUrl) {
//Set your max height or width dimension (either, not both)
var maxDim = 330;
//Define the equalizer to 1 to avoid errors if incorrect URL is given
var dimEq = 1;
//This determines if the larger dimension is the images height or width.
//Then, it divides that dimension by the maxDim to get a decimal number for size reduction
if (img.height() > maxDim || img.width() > maxDim) {
if (img.height() > img.width()) {
dimEq = maxDim / img.height();
} else {
dimEq = maxDim / img.width();
}
}
var imageOutput = "<a href='" + linkUrl + "' target='_blank'>View Larger</a><br /><a href='" + result +
"' target='_blank'><img src='" + linkUrl + "' style='width: " + img.width() * dimEq
+ "px; height: " + img.height() * dimEq + "px' /></a>";
//This returns a URL for the image with height and width tags of the resized (non-squished) image.
return imageOutput;
}
For image manipulation in PHP you can use Imagemagick.
http://www.imagemagick.org/
It's the scale command you are looking for.
Here I have created a function with your reference link, you can use it like this
Call it
//Resize uploaded image
resize_image($_FILES['userfile'], 100, 200);
//Or if you want to save image with diffrent name
$filename = $upload_path.$_SESSION['username'].'-avatar.jpg';
resize_image($_FILES['userfile'], 100, 200, $newfilename);
//if (move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path.$filename)) {
$q = mysqli_query($connection, "UPDATE users SET avatar='".$filename."' WHERE username ='".$_SESSION['username']."'");
echo "<font color='#5cb85c'>Браво, успешно си качил/а профилна снимка!</font>";
} else {
echo 'There was an error during the file upload. Please try again.';
}
Function
function resize_image($image_src, $w = 100, $h = 100, $save_as = null) {
// Create image from file
switch(strtolower($image_src['type']))
{
case 'image/jpeg':
$image = imagecreatefromjpeg($image_src['tmp_name']);
break;
case 'image/png':
$image = imagecreatefrompng($image_src['tmp_name']);
break;
case 'image/gif':
$image = imagecreatefromgif($image_src['tmp_name']);
break;
default:
exit('Unsupported type: '.$image_src['type']);
}
// Target dimensions
$max_width = $w;
$max_height = $h;
// Get current dimensions
$old_width = imagesx($image);
$old_height = imagesy($image);
// Calculate the scaling we need to do to fit the image inside our frame
$scale = min($max_width/$old_width, $max_height/$old_height);
// Get the new dimensions
$new_width = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);
// Create new empty image
$new = imagecreatetruecolor($new_width, $new_height);
// Resize old image into new
imagecopyresampled($new, $image,
0, 0, 0, 0,
$new_width, $new_height, $old_width, $old_height);
if($save_as) {
//Save as new file
imagejpeg($new, $save_as, 90);
}else{
//Overwrite image
imagejpeg($new, $image_src['tmp_name'], 90);
}
// Destroy resources
imagedestroy($image);
imagedestroy($new);
}
I use http://image.intervention.io/. You can scale, cache, store, convert and do various image manipulation tasks.
Very easy to use.
// load the image
$img = Image::make('public/foo.jpg');
// resize the width of the image to 300 pixels and constrain proportions.
$img->resize(300, null, true);
// save file as png with 60% quality
$img->save('public/bar.png', 60);

PHP how to change/add image title

I am new to php and I've downloaded a free source code for image gallery. It has admin account and you can upload image on it. Now when I upload image it generates random image title like numbers '4849404'. I want it to assign a specific title per image. How can I do that? I think here is the line for the image title if I'm not mistaken:
$RandomNumber = rand(0, 9999999999); // We need same random name for both files.
// some information about image we need later.
$ImageName = strtolower($_FILES['ImageFile']['name']);
$ImageSize = $_FILES['ImageFile']['size'];
$TempSrc = $_FILES['ImageFile']['tmp_name'];
$ImageType = $_FILES['ImageFile']['type'];
$process = true;
//Validate file + create image from uploaded file.
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':
$CreatedImage = imagecreatefromjpeg($_FILES['ImageFile']['tmp_name']);
break;
default:
die('Unsupported File!'); //output error
}
//get Image Size
list($CurWidth,$CurHeight)=getimagesize($TempSrc);
//get file extension, this will be added after random name
$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt = str_replace('.','',$ImageExt);
$BigImageMaxWidth = $CurWidth;
$BigImageMaxHeight = $CurHeight;
//Set the Destination Image path with Random Name
$thumb_DestRandImageName = $Thumb.$RandomNumber.'.'.$ImageExt; //Thumb name
$DestRandImageName = $DestinationDirectory.$RandomNumber.'.'.$ImageExt; //Name for Big Image
//Resize image to our Specified Size by calling our resizeImage function.
if(resizeImage($CurWidth,$CurHeight,$BigImageMaxWidth,$BigImageMaxHeight,$DestRandImageName,$CreatedImage))
{
//Create Thumbnail for the Image
resizeImage($CurWidth,$CurHeight,$ThumbMaxWidth,$ThumbMaxHeight,$thumb_DestRandImageName,$CreatedImage);
//respond with our images
echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">
<tr><td align="center"><img src="gallery/'.$RandomNumber.'.'.$ImageExt.'" alt="Resized Image"></td></tr></table>';
}else{
die('Resize Error'); //output error
}
}
It is adding a random number for the title on the following lines:
$DestRandImageName = $DestinationDirectory.$RandomNumber.'.'.$ImageExt;
and
$DestRandImageName = $DestinationDirectory.$RandomNumber.'.'.$ImageExt;
Were it says $RandomNumber you could add the ability to set a name here e.g. put the above code into a method and pass through a variable that sets the name or you could retrieve the existing image name from the following variable:
$ImageName
The code snippet you've posted seems to be creating and naming thumbnails, as we can notice from the comments and variable names:
//Set the Destination Image path with Random Name
$thumb_DestRandImageName = $Thumb.$RandomNumber.'.'.$ImageExt; //Thumb name
and confirmed from its usage a few lines below in:
//Create Thumbnail for the Image
resizeImage($CurWidth,$CurHeight,$ThumbMaxWidth,$ThumbMaxHeight,$thumb_DestRandImageName,$CreatedImage);
Read about the contents of $_FILES array - name, type, size, tmp_name and error to understand the details available. E.g. in the above code snippet,
$ImageName = strtolower($_FILES['ImageFile']['name']);
gets the original file name in lower case (because of strtolower) which we can use as we see fit e.g. using it as such, or after adding some random string for the primary name. Also, as you might have noticed, file extension will also have to be managed separately.
Finally, if you are looking to rename the originally uploaded files, which is possibly using move_uploaded_file, dig around the code and test in similar fashion.
$thumb_DestRandImageName = $Thumb.$RandomNumber.'.'.$ImageExt; //Thumb name
$DestRandImageName = $DestinationDirectory.$RandomNumber.'.'.$ImageExt;
this line is where you can add specific title.
$RandomNumber="title";

Renaming Files by adding a Suffix

Can i change the name of the file, say an image for example which has name like '0124.jpg',
before sending it to the server?
<input id="f1" style="margin-bottom: 5px;" type="file" name="f1" onchange="javascript:readURL_f1(this);"/>
<input id="f2" style="margin-bottom: 5px;" type="file" name="f1" onchange="javascript:readURL_f2(this);"/>
If the file is uploaded from f1, then before sending to to server, the name should become pic1_[filename].jpg, instead of just sending the raw filename.
I don't want this to be done in server side because i think it might be complicated.
EDIT : Upload.php is my php file which uploads whatever in the file. So, its been a challenge for me. i can change the filename, but that gets changed in all the three uploads.
for example i add an '_' for the incoming filename. Then, it gets changed to all filenames.
Anyway from clientside?
my upload script: Upload.php
upload.php
<?php mysql_connect('localhost','root','phpmyadmin');
$connected = mysql_select_db('image_Upload');
?>
<noscript>
<div align="center">Go Back To Upload Form</div><!-- If javascript is disabled -->
</noscript>
<?php
//If you face any errors, increase values of "post_max_size", "upload_max_filesize" and "memory_limit" as required in php.ini
//Some Settings
$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;
$id = 'm123';
//ini_set('memory_limit', '-1'); // maximum memory!
foreach($_FILES as $file)
{
// some information about image we need later.
$ImageName = $file['name'];
$ImageSize = $file['size'];
$TempSrc = $file['tmp_name'];
$ImageType = $file['type'];
if (is_array($ImageName))
{
$c = count($ImageName);
echo '<ul>';
for ($i=0; $i < $c; $i++)
{
$processImage = true;
$RandomNumber = rand(0, 9999999999); // We need same random name for both files.
if(!isset($ImageName[$i]) || !is_uploaded_file($TempSrc[$i]))
{
echo '<div class="error">Error occurred while trying to process <strong>'.$ImageName[$i].'</strong>, may be file too big!</div>'; //output error
}
else
{
//Validate file + create image from uploaded file.
switch(strtolower($ImageType[$i]))
{
case 'image/png':
$CreatedImage = imagecreatefrompng($TempSrc[$i]);
break;
case 'image/gif':
$CreatedImage = imagecreatefromgif($TempSrc[$i]);
break;
case 'image/jpeg':
case 'image/pjpeg':
$CreatedImage = imagecreatefromjpeg($TempSrc[$i]);
break;
default:
$processImage = false; //image format is not supported!
}
//get Image Size
list($CurWidth,$CurHeight)=getimagesize($TempSrc[$i]);
//Get file extension from Image name, this will be re-added after random name
$ImageExt = substr($ImageName[$i], strrpos($ImageName[$i], '.'));
$ImageExt = str_replace('.','',$ImageExt);
//Construct a new image name (with random number added) for our new image.
$NewImageName = $id.'_'.'pic'.($i+1).'.'.$ImageExt;
//Set the Destination Image path with Random Name
$thumb_DestRandImageName = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumb name
$DestRandImageName = $DestinationDirectory.$NewImageName; //Name for Big Image
//Resize image to our Specified Size by calling resizeImage function.
if($processImage && resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType[$i]))
{
//Create a square Thumbnail right after, this time we are using cropImage() function
if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType[$i]))
{
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.
*/
//Get New Image Size
list($ResizedWidth,$ResizedHeight)=getimagesize($DestRandImageName);
echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
echo '<tr>';
echo '<td align="center"><img src="uploads/'.$ThumbPrefix.$NewImageName.
'" alt="Thumbnail" height="'.$ThumbSquareSize.'" width="'.$ThumbSquareSize.'"></td>';
echo '</tr><tr>';
echo '<td align="center"><img src="uploads/'.$NewImageName.
'" alt="Resized Image" height="'.$ResizedHeight.'" width="'.$ResizedWidth.'"></td>';
echo '</tr>';
echo '</table>';
if(isset($id))
{
mysql_query("UPDATE imagetable SET ImageName='$DestRandImageName',ThumbName='$thumb_DestRandImageName',
ImgPath='uploads/' WHERE id='$id'");
}
else{
mysql_query("INSERT INTO imagetable (id, ImageName, ThumbName, ImgPath)
VALUES ('$id','$DestRandImageName', '$thumb_DestRandImageName', 'uploads/')");
}
}else{
echo '<div class="error">Error occurred while trying to process <strong>'.$ImageName.
'</strong>! Please check if file is supported</div>';
}
}
}
echo '</ul>';
}
}
// This function will proportionally resize image
function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType)
{
//Check Image size is not 0
if($CurWidth <= 0 || $CurHeight <= 0)
{
return false;
}
//Construct a proportional size of new image
$ImageScale = min($MaxSize/$CurWidth, $MaxSize/$CurHeight);
$NewWidth = ceil($ImageScale*$CurWidth);
$NewHeight = ceil($ImageScale*$CurHeight);
if($CurWidth < $NewWidth || $CurHeight < $NewHeight)
{
$NewWidth = $CurWidth;
$NewHeight = $CurHeight;
}
$NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);
// Resize Image
if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight))
{
switch(strtolower($ImageType))
{
case 'image/png':
imagepng($NewCanves,$DestFolder);
break;
case 'image/gif':
imagegif($NewCanves,$DestFolder);
break;
case 'image/jpeg':
case 'image/pjpeg':
imagejpeg($NewCanves,$DestFolder,$Quality);
break;
default:
return false;
}
if(is_resource($NewCanves)) {
imagedestroy($NewCanves);
}
return true;
}
}
//This function corps image to create exact square images, no matter what its original size!
function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType)
{
//Check Image size is not 0
if($CurWidth <= 0 || $CurHeight <= 0)
{
return false;
}
if($CurWidth>$CurHeight)
{
$y_offset = 0;
$x_offset = ($CurWidth - $CurHeight) / 2;
$square_size = $CurWidth - ($x_offset * 2);
}else{
$x_offset = 0;
$y_offset = ($CurHeight - $CurWidth) / 2;
$square_size = $CurHeight - ($y_offset * 2);
}
$NewCanves = imagecreatetruecolor($iSize, $iSize);
if(imagecopyresampled($NewCanves, $SrcImage,0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size))
{
switch(strtolower($ImageType))
{
case 'image/png':
imagepng($NewCanves,$DestFolder);
break;
case 'image/gif':
imagegif($NewCanves,$DestFolder);
break;
case 'image/jpeg':
case 'image/pjpeg':
imagejpeg($NewCanves,$DestFolder,$Quality);
break;
default:
return false;
}
if(is_resource($NewCanves)) {
imagedestroy($NewCanves);
}
return true;
}
}
When you are uploading the File you usually follow this workflow
User Chooses a File and Clicks Upload
Server Pics up the File from the temp folder - check MimeType, Resize and Rename the File and store it to which ever location you want on the file server.
While Renaming if you want to see if the same file name exsists and then append the _01, _02 then you will have to check if a file exists with that name and then append the unique number at the end.
Things like that are usually done in the server side. The purpose of preppending or appending a code or, say, changing the whole name of the file is to prevent uploaded file name conflicts. So imagine doing it to the client side? When upload button is pressed you need to ask the server if this file name is already existing, then you wait for the response of the server then do the renaming based on the response then send it to the server instead of just sending it to the server then do the checking then renaming then saving.

Why will my upload form not upload files over 2.1mb using php?

I am using an upload script that is working great:
ini_set('memory_limit', '256M');
function uploadImage($files_name, $files_tmp_name, $files_error, $files_type, $uploaded_photos_array, $image_type, $replace_position='69') { //Checks if the file uploaded correctly, saves the folder name to the DB, and calls the resizeAndPlaceFile 3 times
global $address;
//If the directory doesn't exist, create it
if (!is_dir('../images/uploads/temp/'.$address)) {
mkdir('../images/uploads/temp/'.$address);
}
$myFile_original = $files_name; //Store the filename into a variable
//Change the filename so it is unique and doesn't contain any spaces and is all lowercase
$myFile = str_replace(' ', '_', $myFile_original); //change all spaces to underscores within a file name
$myFile = strtolower($myFile); //Make all characters lowercase
//$anyNum = rand(20,500789000); //Generate a random number between 20 and 500789000
//$newFileName = $anyNum.'_'.$myFile; //Combine the random number with the filename to create a unique filename
$newFileName = $myFile;
$info = pathinfo($newFileName); //Finds the extension of the filename
$directory_name = basename($newFileName,'.'.$info['extension']); //Removes the extension from the filename to use as the name of the directory
$folder = '../images/uploads/temp/'.$address.'/'.$directory_name.'/'; //Folder to upload to
//If the directory doesn't exist, create it
if (!is_dir($folder)) {
mkdir($folder);
}
//===Check if the File already exists========
if (file_exists($folder.'large.jpg')) {
echo $myFile_original." already exists.";
} //******If file already exists in your Folder, It will return zero and Will not take any action===
else { //======Otherwise File will be stored in your given directory and Will store its name in Database===
//copy($_FILES['fileField']['tmp_name'],$folder.$newFileName); //===Copy File Into your given Directory,copy(Source,Destination)
// Check if file was uploaded ok
if(!is_uploaded_file($files_tmp_name) || $files_error !== UPLOAD_ERR_OK) {
exit('There was a problem uploading the file. Please try again.');
} else {
/*
$sql = 'INSERT into tblfileupload SET
file_name = "'.$folder.'"';
$result = $conn->query($sql) or die($conn->error);
if($result > 0) { //====$res will be greater than 0 only when File is uploaded Successfully====:)
echo 'You have Successfully Uploaded File';
}
*/
if(!function_exists('resizeAndPlaceFile')){
function resizeAndPlaceFile($image_size, $files_tmp_name, $files_type, $folder) { //Resizes the uploaded file into different sizes
//echo '<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />The resizeAndPlaceFile function is being called!';
// Create image from file
switch(strtolower($files_type)) {
case 'image/jpeg':
$image = imagecreatefromjpeg($files_tmp_name);
break;
case 'image/png':
$image = imagecreatefrompng($files_tmp_name);
break;
case 'image/gif':
$image = imagecreatefromgif($files_tmp_name);
break;
default:
exit('Unsupported type: '.$files_type);
}
// Get current dimensions
$old_width = imagesx($image);
$old_height = imagesy($image);
// Target dimensions for large version
switch($image_size) {
case 'large':
$max_width = '600'; //Large Photo (Listing Page)
break;
case 'medium':
$max_width = '157'; //Medium Photo (Dashboard)
break;
case 'thumbnail':
$max_width = '79'; //Small Photo (Listing Page - Thumbnail)
break;
}
if($max_width > $old_width) {
$max_width = $old_width;
}
$max_height = ($old_height/$old_width)* $max_width;
// Get current dimensions
$old_width = imagesx($image);
$old_height = imagesy($image);
// Calculate the scaling we need to do to fit the image inside our frame
$scale = min($max_width/$old_width, $max_height/$old_height);
// Get the new dimensions
$new_width = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);
// Create new empty image
$new = imagecreatetruecolor($new_width, $new_height);
// Resize old image into new
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
//Output the image to a file
imagejpeg($new, $folder.$image_size.'.jpg',100);
// Destroy resources
imagedestroy($image);
imagedestroy($new);
} //end function resizeAndPlaceFile
} //end if !function_exists['resizeAndPlaceFile']
resizeAndPlaceFile('large',$files_tmp_name, $files_type, $folder); //Large Photo (List Page)
resizeAndPlaceFile('medium',$files_tmp_name, $files_type, $folder); //Medium Photo (Dashboard)
resizeAndPlaceFile('thumbnail',$files_tmp_name, $files_type, $folder); //Small Photo (List Page - Thumbnail)
if($image_type == 'replace') { //If this is being run for a replace, then replace one of the values instead of adding it to the end of the array
$uploaded_photos_array[$replace_position] = $folder; //This replaces the value of the old image with the new image
} else if($image_type == 'initial') { //otherwise, add it to the end of the array
array_push($uploaded_photos_array,$folder);
}
return $uploaded_photos_array;
} //end else
} //end else
} //end function uploadImage
When I try to upload any file above 2.1mb, it won't upload the file and won't display any error so I have no idea why it is not working. Why will my upload form not upload files over 2.1mb using php?
Check and change the following php.ini instructions:
memory_limit = 32M
upload_max_filesize = 10M
post_max_size = 20M
update these parameters in your php.ini
upload_max_filesize
post_max_size
You can't change maximum file upload size from your php script. You should change in php.ini file as
upload_max_filesize = 30M
post_max_size = 30M
Some hosters dosen't allow to change php.ini(in case of shared hosting) in that u should use .htaccess and use following
php_value upload_max_filesize 30M

Categories