I am using the library WideImage to resize an uploaded image into two separate sizes then save the images in two separate directories. The problem is that the smaller image is not ALWAYS saving. Here is my attempt:
if(move_uploaded_file($_FILES['image']['tmp_name'], "../images/temp/$id.jpg")){
include '../../WideImage/WideImage.php';
$successfull = 0;
if($image = WideImage::load("../images/temp/$id.jpg")){
if($large=$image->resize(500, 375)){
$large->saveToFile("../images/large/product_$id.jpg");
$successfull = 1;
}
}
if($successfull==1){
$successfull = 0;
if($image_2 = WideImage::load("../images/temp/$id.jpg")){
if($small=$image_2->resize(300, 225)){
$small->saveToFile("../images/small/product_$id.jpg");
$successfull = 1;
}
}
if($successfull!=1){
$showError='style="background:#c60000;"';
$myError="An Error Occured Please Try Again";
}
else {
unlink("../images/temp/$id.jpg");
header("location: products.php");
exit;
}
}
This is always giving me an error. My assumption is that the saving of the image is taking some time. So my question is how can I ensure that all the steps have been successfully completed?
Related
I am new to PHP web development and making a simple website for adding products and categories and I am facing an issue with the update CRUD operation for the categories
when I upload an image.
Updating the image when less than 2MB is ok and the old image will be deleted, for the other scenarios when image is more than 2MB or upload different image extension than the allowed ones it's not being validated only the image name gets added to the database, below is my code and appreciate the help
include("../config/dbconn.php");
if (isset($_POST['update'])) {
$cat_id = mysqli_real_escape_string($dbconn, $_POST['cat_id']);
$cat_name = mysqli_real_escape_string($dbconn, $_POST['cat_name']);
$pervious_cat_name = filter_var($_POST['pervious_cat_name'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$cat_img = $_FILES['cat_img'];
// checking empty fields
if (empty($cat_name) || empty($cat_img)) {
if (empty($cat_name)) {
echo "<font color='red'>category name field is empty!</font><br/>";
}
if (empty($cat_img)) {
echo "<font color='red'>image field is empty!</font><br/>";
}
} else {
//updating the table
if ($cat_img['name']) {
$pervious_cat_path = '../../uploads/' . $pervious_cat_name;
if ($pervious_cat_path) {
unlink($pervious_cat_path);
}
$cat_img_name = $cat_img['name'];
$cat_temp_name = $cat_img['tmp_name'];
$cat_img_destination_path = '../../uploads/' . $cat_img_name;
$allow_files = ['png', 'jpg', 'jpeg','webp'];
$extension = explode('.', $cat_img_name);
$extension = end($extension);
if (in_array($extension, $allow_files)) {
if ($cat_img['size'] < 2000000) {
move_uploaded_file($cat_temp_name, $cat_img_destination_path);
} else {
$_SESSION['category_update'] = "couldn't update category, image size is too large";
}
} else {
$_SESSION['category_update'] = "couldn't update category, image should be png, jpg, jpeg";
}
}
$cat_img_to_insert = $cat_img_name ?? $pervious_cat_name;
$query = "UPDATE category SET cat_name='$cat_name', cat_img='$cat_img_to_insert' WHERE cat_id=$cat_id";
$result = mysqli_query($dbconn, $query);
if ($result) {
//redirecting to the display page. In our case, it is index.php
header("Location: admin_panel.php");
}
}
}
?>
below are a couple of images to see the results:
ok uploaded an image less than 2MB and in the allowed extensions.
image bigger than 2MB and in the allowed extensions.
not allowed image extensions:
appreciate the support.
First off, the upload folder is given 777, and my old upload script works, so the server accepts files. How ever this is a new destination.
I use krajee bootstrap upload to send the files. And I receive a Jason response. The error seems to be around move uploaded file. I bet it's a simple error from my side, but I can't see it.
<?php
if (empty($_FILES['filer42'])) {
echo json_encode(['error'=>'No files found for upload.']);
// or you can throw an exception
return; // terminate
}
// get the files posted
$images = $_FILES['filer42'];
// a flag to see if everything is ok
$success = null;
// file paths to store
$paths= [];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
$ext = explode('.', basename($filenames[$i]));
$target = "uploads" . DIRECTORY_SEPARATOR . md5(uniqid()) . "." . array_pop($ext);
if(move_uploaded_file($_FILES["filer42"]["tmp_name"][$i], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
}
// check and process based on successful status
if ($success === true) {.
$output = [];
$output = ['uploaded' => $paths];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
// delete any uploaded files
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
// return a json encoded response for plugin to process successfully
echo json_encode($output);
?>
I think field name is the issue. Because you are getting image name with filer42 and upload time, you are using pictures.
Please change
$_FILES["pictures"]["tmp_name"][$i]
to
$_FILES["filer42"]["tmp_name"][$i]
And check now, Hope it will work. Let me know if you still get issue.
The error is not in this script but in the post.
I was using <input id="filer42" name="filer42" type="file">
but it have to be <input id="filer42" name="filer42[]" type="file" multiple>
as the script seems to need an arrey.
It works just fine now.
I want to copy set of uploaded files from one folder to another folder.From the below code, all the files in one folder is copied.It takes much time. I want to copy only the currently uploaded file to another folder.I have some idea to specify the uploaded files and copy using for loop.But I don't know to implement.I am very new to developing.Please help me.Below is the code.
<?php
// connect to the database
include('connect-db.php');
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$file_array=($_FILES['file_array']['name']);
// check to make sure both fields are entered
if ($udate == '' || $file_array=='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($udate, $file_array, $error);
}
else
{
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
if(isset($_FILES['file_array']))
{
$name_arrray=$_FILES['file_array']['name'];
$tmp_name_arrray=$_FILES['file_array']['tmp_name'];
for($i=0;$i <count($tmp_name_arrray); $i++)
{
if(move_uploaded_file($tmp_name_arrray[$i],"test_uploads/".str_replace(' ','',$name_arrray[$i])))
{
// save the data to the database
$j=str_replace(' ','',$name_arrray[$i]);
echo $j;
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$provider = mysql_real_escape_string(htmlspecialchars($_POST['provider']));
$existfile=mysql_query("select ubatch_file from batches");
while($existing = mysql_fetch_array( $existfile)) {
if($j==$existing['ubatch_file'])
echo' <script>
function myFunction() {
alert("file already exists");
}
</script>';
}
mysql_query("INSERT IGNORE batches SET udate='$udate', ubatch_file='$j',provider='$provider',privilege='$_SESSION[PRIVILEGE]'")
or die(mysql_error());
echo $name_arrray[$i]."uploaded completed"."<br>";
$src = 'test_uploads';
$dst = 'copy_test_uploads';
$files = glob("test_uploads/*.*");
foreach($files as $file){
$file_to_go = str_replace($src,$dst,$file);
copy($file, $file_to_go);
/* echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Uploaded.\");
window.location = \"uploadbatches1.php\"
</script>";*/
}
} else
{
echo "move_uploaded_file function failed for".$name_array[$i]."<br>";
}
}
}
// once saved, redirect back to the view page
header("Location:uploadbatches1.php");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','');
}
?>
To copy only the uploaded files, there is only a slight change in the coding which I have made. That is instead of using "." from one folder, I passed the array value. So that only the files which are uploaded will be copied to the new folder instead of copying everything which takes long time.Below is the only change made to do:
$files = glob("test_uploads/$name_arrray[$i]");
I have a image gallery , users can upload the images, after uploading the image, PHP script create two copy of it - One for thumbnail and another for displaying in gallery in larger size.
The application is working fine, except that , When uploading some PNG pictures , the statement
if($image=#imagecreatefromstring($filedata))
returns false.
Below is the script. Please help.
<!---------------Processing uploaded image----------------->
<?php
if (isset($_FILES['file1']))
{
if($fgmembersite->CheckLogin())
{
if($_FILES['file1']['error']>0)
{
echo "file upload error".$_FILES['file1']['error'];
}
else
{
$allowedtype=array('image/jpg','image/jpeg','image/pjpeg','image/gif','image/png');
$maxsize=10*1024*1024;
$filename= mysql_real_escape_string($_FILES['file1']['name']);
$tmp_name=$_FILES['file1']['tmp_name'];
$size=$_FILES['file1']['size'];
$type=$_FILES['file1']['type'];
$ext=$filename;
if (!in_array($type,$allowedtype))
{
die ('Invalid file type');
}
if ($size>$maxsize)
{
die ('error- file size must be less than'.($maxsize/1024/1024).'MB');
}
filedata=file_get_contents($tmp_name);
if($image=#imagecreatefromstring($filedata))
{
$width=imagesx($image);
$height=imagesy($image);
//creating images
$large=imagecreatetruecolor(445,380);
imagecopyresampled($large,$image,0,0,0,0,445,380,$width,$height);
$largepath = 'image/large/' . uniqid('img',true) . '.jpg' ; //assigning file location and path
$thumb=imagecreatetruecolor(54,54);
imagecopyresampled($thumb,$image,0,0,0,0,54,54,$width,$height);
$thumbpath = 'image/thumb/' . uniqid('thumb',true) . '.jpg' ;
if (imagejpeg($thumb,$thumbpath) && imagejpeg($large,$largepath))
{
$con = connect();
query("INSERT INTO gallery (caption,thumbpath,largepath) values ('$caption','$thumbpath','$largepath')");
}
header('location:'.$_SERVER["PHP_SELF"]);
}
else
echo "failed";
}
}
}
?>
Check the manual on imagejpeg, it takes an optional third parameter that is the quality (0 - 100):
if (imagejpeg($thumb,$thumbpath, 92) && imagejpeg($large,$largepath, 96))
I am writing a code that will let me upload files. The code is to convert the file to all lowercase .Check to make sure the filename is not already inserted into the database and if the user uploads a .png or .jpg file, resize the image to a thumbnail and keep a copy of both the thumbnail and regular size image in a folder named: uploads. I am still a bit confusing cause there is something that aint right I went over and over it. I dont know if maybe I been working on it for days or what not but I can not see anything. Not only that I am still a newbie working on this.
Here is my code:
$aryImages=array("image/jpeg","image/png");
$aryDocs=array("application/msword","application/pdf","video/x-msvideo");
$filename=filenameSafe($_FILES['upload']['name']);
$fileType=$_FILES["upload"]["type"];
if (in_array($_FILES["upload"]["type"],$aryImages)){
createThumb($fileType,$_FILES['upload']['tmp_name'],$filename,100,100);
}
elseif (in_array($_FILES["upload"]["type"],$aryDocs)){
move_uploaded_file($_FILES['upload']['tmp_name'],
"../imagefolder/".$filename);
$aryColumns=array("sessionID"=>$curSess,"fileName"=>$filename,"fileType"=>$fileType,"thumbFileName"=>$thumbFilename,"dateCreated"=>date('Y-m-d H:i:s'));
dbInsert($filename,$aryColumns,$_FILES["upload"]["type"]);
}
else{
echo "File Uploaded";
}
}
function createThumb($type,$tmpname,$filename,$new_w,$new_h){
$thumbFilename="tmb-".$filename;
if (is_numeric(strpos($type,"jpeg"))){
$src_img=imagecreatefromjpeg($tmpname);
}
if (is_numeric(strpos($type,"png"))){
$src_img=imagecreatefrompng($tmpname);
}
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
if ($old_x > $old_y) {
$thumb_w=$new_w;
$thumb_h=$old_y*($new_h/$old_x);
}
if ($old_x < $old_y) {
$thumb_w=$old_x*($new_w/$old_y);
$thumb_h=$new_h;
}
if ($old_x == $old_y) {
$thumb_w=$new_w;
$thumb_h=$new_h;
}
$dst_img=imagecreatetruecolor($thumb_w,$thumb_h);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
if (is_numeric(strpos($type,"jpeg"))){
imagejpeg($dst_img,"../upload/".$thumbFilename);
imagejpeg($src_img,"../upload/".$filename);
}
if (is_numeric(strpos($type,"png"))){
imagepng($dst_img,"../upload/".$thumbFilename);
imagepng($src_img,"../upload/".$filename);
}
imagedestroy($dst_img);
imagedestroy($src_img);
dbInsert($filename,$thumbFilename,$type);
}
function filenameSafe($filename) {
$temp = $filename;
// Lower case
$temp = strtolower($temp);
// Replace spaces with a ’_’
$temp = str_replace(" ", "_", $temp);
// Loop through string
$result = "";
for ($i=0; $i<strlen($temp); $i++) {
if (preg_match('([0-9]|[a-z]|_|.)', $temp[$i])) {
$result = $result.$temp[$i];
}
}
dbConnect();
$SQL="SELECT fileID FROM upload WHERE fileName='".$result."'";
//echo $SQL;
$rs=mysql_query($SQL);
echo mysql_num_rows($rs);
if(mysql_num_rows($rs)!=0){
$extension=strrchr($result,'.');
$result=str_replace($extension,time(),$result);
$result=$result.$extension;
}
return $result;
}
function dbInsert($filename,$thumbFilename,$type){
dbConnect();
$SQL="INSERT Into tblFile (fileName,thumbFileName,fileType) values('".$filename."','".$thumbFilename."','".$type."')";
echo $query;
exit;
mysql_query($SQL);
}
I am thinking it is looping somewhere and I just cant catch it. When i click the upload button after the browse buttton the page comes up with nothing on it no picture or anything. I am not getting no error or nothing. Can someone please help me out. If i try to put some of the code out it will start giving me errors and fatal errors too. Thanks for looking.
You have several issues here so I'm only going to focus on one area right now that will (hopefully) help you write better code in the future.
Your filenameSafe() function is terribly inefficient. Using a regex on each character of a string inside a loop is like breaking an egg with a sledgehammer with dynamite strapped to the handle. Also, if your goal is to sanitize data before saving it to the database you should be using mysql_real_escape_string() on the data before queries to the db.
Additionally, by simply finding the first occurrence of a period in your filename to determine where the extension starts is dubious ... what if multiple periods made it into the filename somehow? Instead, try pathinfo() to get the extension.
Finally, I assume that by appending the current timestamp you're trying to avoid filename collisions in the filesystem. This is not an adequate solution because it is very possible for two files to be saved at the same second in time. While there are whole books on subjects like hashing, for the sake of time I'll just say you'd be better served by dropping a quick md5() or uniqid() on the filename.
So, an example of how to better handle that particular part of the code:
function filenameSafe($filename)
{
// Lower case
$filename = strtolower($filename);
// get extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
// Replace spaces with a ’_’
$filename = str_replace(" ", "_", $filename);
// Replace non-alphanumerics (except underscores)
$filename = preg_replace('/\W/', '', $filename);
// append the timestamp
$filename = $filename . time();
// create an md5 hash
$result = md5($filename);
// ensure the string is safe for the db query
$result = mysql_real_escape_string($result);
dbConnect();
$SQL="SELECT fileID FROM upload WHERE fileName='".$result.".$ext'";
$rs = mysql_query($SQL);
if (mysql_num_rows($rs) > 0) {
$result = str_replace(".$ext", time(), $result);
$result = "$result.$ext";
}
return $result;
}