cobusbo Posted September 30, 2015 Share Posted September 30, 2015 Hi I'm currently stuck with an image upload script that doesn't seem to rename my files correctly and if its a jpg file the conversion doesn't take place correctly as well any assistance please? All I'm trying to do is to change a random photo to jpg format and resize it to be less than 100kb <?php include $_SERVER['DOCUMENT_ROOT'] . '/chat2/chat_code_header.php'; $ip = $_SERVER["HTTP_X_MXIT_USERID_R"]; if(!isset($ip)) { $ip = "Debater"; } $result9 = mysql_query("SELECT * FROM Users2 WHERE mxitid = \"$ip\""); $row = mysql_fetch_array($result9); $id = $row['ID']; // Access the $_FILES global variable for this specific file being uploaded // and create local PHP variables from the $_FILES array of information $fileName = $_FILES["uploaded_file"]["name"]; // The file name $fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"]; // File in the PHP tmp folder $fileType = $_FILES["uploaded_file"]["type"]; // The type of file it is $fileSize = $_FILES["uploaded_file"]["size"]; // File size in bytes $fileErrorMsg = $_FILES["uploaded_file"]["error"]; // 0 for false... and 1 for true $fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName); // filter the $filename $kaboom = explode(".", $fileName); // Split file name into an array using the dot $imageTypeArray = array ( 0=>'UNKNOWN', 1=>'GIF', 2=>'JPEG', 3=>'PNG', 4=>'SWF', 5=>'PSD', 6=>'BMP', 7=>'TIFF_II', 8=>'TIFF_MM', 9=>'JPC', 10=>'JP2', 11=>'JPX', 12=>'JB2', 13=>'SWC', 14=>'IFF', 15=>'WBMP', 16=>'XBM', 17=>'ICO', 18=>'COUNT' ); $size = getimagesize($fileTmpLoc); $size[2] = $imageTypeArray[$size[2]]; $fileExt = $size[2]; // Now target the last array element to get the file extension // START PHP Image Upload Error Handling -------------------------------- if (!$fileTmpLoc) { // if file not chosen echo "ERROR: Please browse for a file before clicking the upload button."; exit(); } else if($fileSize > 5242880) { // if file size is larger than 5 Megabytes echo "ERROR: Your file was larger than 5 Megabytes in size."; unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder exit(); } else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) { // This condition is only if you wish to allow uploading of specific file types echo "ERROR: Your image was not .gif, .jpg, or .png."; unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder exit(); } else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1 echo "ERROR: An error occured while processing the file. Try again."; exit(); } // END PHP Image Upload Error Handling ---------------------------------- // Place it into your "uploads" folder mow using the move_uploaded_file() function $moveResult = move_uploaded_file($fileTmpLoc, "images/".$id."_".date_create()->getTimestamp().".".$fileExt); // Check to make sure the move result is true before continuing if ($moveResult != true) { echo "ERROR: File not uploaded. Try again."; exit(); } // Include the file that houses all of our custom image functions include_once("ak_php_img_lib_1.0.php"); // ---------- Start Universal Image Resizing Function -------- $target_file = "images/".$id."_".date_create()->getTimestamp().".".$fileExt; $resized_file = "images/resized_".$id."_".date_create()->getTimestamp()."." . $fileExt; $wmax = 320; $hmax = 240; ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt); unlink($target_file); // ----------- End Universal Image Resizing Function ---------- // ---------- Start Convert to JPG Function -------- $target_file = "images/resized_".$id."_".date_create()->getTimestamp()."." . $fileExt; $new_jpg = "images/resized_".$id."_".date_create()->getTimestamp().".jpg"; ak_img_convert_to_jpg($target_file, $new_jpg, $fileExt); unlink($target_file); $new_jpg = "images/resized_".$id."_".date_create()->getTimestamp().".jpg"; if(!get_magic_quotes_gpc()) { $new_jpg = addslashes($new_jpg); $filePath = addslashes($filePath); } $resultc = mysql_query("SELECT * FROM Users2 WHERE mxitid = '$ip'"); $rowc = mysql_fetch_array($resultc); $ppica = $rowc['pprofilepic']; $naam = "ADMIN"; $naam2 = $rowc['pprofilepic']; $msg = "You Requested a Profile Picture change, please wait till an Admin can manage the request"; $msg1 = "Please aprove my Profile Picture"; $post_time = date("U"); $read1 = "unread"; $banby2 = "ADMIN"; $result = mysql_query("UPDATE Users2 SET pprofilepic='$new_jpg', aprove='requested' WHERE mxitid='$ip'") or die(mysql_error()); unlink($ppica); $query1 = "INSERT INTO pm (`username`,`mxitid`,`message`,`time`,`read`,`ip`) VALUES (\"$naam\",\"$ip\",\"$msg\",\"$post_time\",\"$read1\",\"$banby2\")"; $result1 = mysql_query($query1, $db) or die("Invalid query: " . mysql_error()); $query2 = "INSERT INTO pm (`username`,`mxitid`,`message`,`time`,`read`,`ip`) VALUES (\"$naam2\",\"$banby2\",\"$msg1\",\"$post_time\",\"$read1\",\"$ip\")"; $result2 = mysql_query($query2, $db) or die("Invalid query: " . mysql_error()); // ----------- End Convert to JPG Function ----------- // Display things to the page so you can see what is happening for testing purposes echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />"; echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />"; echo "It is an <strong>$fileType</strong> type of file.<br /><br />"; echo "The file extension is <strong>$fileExt</strong><br /><br />"; echo "The Error Message output for this upload is: $fileErrorMsg"; if($result){ header('Location: ../profile/thankyou.php'); } else { echo "ERROR"; } // close mysql mysql_close(); ?> Quote Link to comment Share on other sites More sharing options...
scootstah Posted September 30, 2015 Share Posted September 30, 2015 Because your $imageTypeArray contains JPEG but you're later looking for jpg with: } else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) { Quote Link to comment Share on other sites More sharing options...
cobusbo Posted September 30, 2015 Author Share Posted September 30, 2015 Because your $imageTypeArray contains JPEG but you're later looking for jpg with: } else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) { The thing is people rename png files to jpg then I need to check what its real format type is. The photos get uploaded but its not saved as jpg it get saved as JPEG not jpg with a millisecond difference in the filename so if the file is named ....321.JPEG in my images directory but in my MySQL field its stored as .... 322.jpg then I cant recall the right picture... Quote Link to comment Share on other sites More sharing options...
scootstah Posted September 30, 2015 Share Posted September 30, 2015 You really should be working with MIME type, instead of doing it how you are. You can use finfo to do that. Â Something like this. Untested, but should work $finfo = new finfo(FILEINFO_MIME_TYPE); $mimetype = $finfo->file($fileTmpLoc); $allowedMimeTypes = array( 'image/jpeg', 'image/png', 'image/gif', ); if (in_array($mimetype, $allowedMimeTypes)) { // file is good } else { // invalid mime type } Quote Link to comment Share on other sites More sharing options...
cobusbo Posted October 1, 2015 Author Share Posted October 1, 2015 You really should be working with MIME type, instead of doing it how you are. You can use finfo to do that. Â Something like this. Untested, but should work $finfo = new finfo(FILEINFO_MIME_TYPE); $mimetype = $finfo->file($fileTmpLoc); $allowedMimeTypes = array( 'image/jpeg', 'image/png', 'image/gif', ); if (in_array($mimetype, $allowedMimeTypes)) { // file is good } else { // invalid mime type } The allowed MimTypes doesn't seem to be my problem the problem seems to be the renaming of my files and adding it to the database with another name.... Quote Link to comment Share on other sites More sharing options...
hansford Posted October 1, 2015 Share Posted October 1, 2015   The allowed MimTypes doesn't seem to be my problem the problem seems to be the renaming of my files and adding it to the database with another name  If the file is actually a png and the user renames it with a jpg/jpeg.....this should not be allowed on the part of the user. Storing the filename in the database should be secondary to storing the filename on the server. If the user is able to change the filename then there is obviously a flaw in the code. Quote Link to comment Share on other sites More sharing options...
Barand Posted October 1, 2015 Share Posted October 1, 2015 Stop calling getTimeStamp() repeatedly. Call it once and store in a variable, then use the variable. That way you always have a consistent timestamp. Quote Link to comment Share on other sites More sharing options...
scootstah Posted October 1, 2015 Share Posted October 1, 2015 The allowed MimTypes doesn't seem to be my problem The thing is people rename png files to jpg then I need to check what its real format type is. And the proper way to do this is to look at the MIME type. The extension of a file (.jpg, .png) is simply part of the file name. It is not required and it does not define what type of file it is.  So the proper steps to take would be:  - Obtain MIME type of the uploaded file - Make sure the MIME type is allowed - Generate a file name/modify file name and use the extension associated with the MIME type  Since you seem to only want to store .jpg, then you would check whether the MIME type is "image/jpeg" or not. If it is, just store as normal. If not, convert it from whatever type it is into .jpg. Quote Link to comment Share on other sites More sharing options...
cobusbo Posted October 1, 2015 Author Share Posted October 1, 2015 You see the problem I'm experiencing is the fact that if the photo is jpeg the photo get resized and stored as .JPEG but if a photo is png or gif it gets converted to jpg and stored as  .jpg. I cant change the the file Ext to jpg after resizing it because my script need to know the file type to convert it. I made a few changes to my script this is how it is now but I still have the same problem... If there is another better simpler way to do it can someone please point me in the right direction because after searching all over its the best example I could find to support my needs... <?php include $_SERVER['DOCUMENT_ROOT'] . '/chat2/chat_code_header.php'; $ip = $_SERVER["HTTP_X_MXIT_USERID_R"]; if(!isset($ip)) { $ip = "Debater"; } $time = date_create()->getTimestamp(); $result9 = mysql_query("SELECT * FROM Users2 WHERE mxitid = \"$ip\""); $row = mysql_fetch_array($result9); $id = $row['ID']; // Access the $_FILES global variable for this specific file being uploaded // and create local PHP variables from the $_FILES array of information $fileName = $_FILES["uploaded_file"]["name"]; // The file name $fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"]; // File in the PHP tmp folder $fileType = $_FILES["uploaded_file"]["type"]; // The type of file it is $fileSize = $_FILES["uploaded_file"]["size"]; // File size in bytes $fileErrorMsg = $_FILES["uploaded_file"]["error"]; // 0 for false... and 1 for true $fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName); // filter the $filename $kaboom = explode(".", $fileName); // Split file name into an array using the dot $imageTypeArray = array ( 0=>'UNKNOWN', 1=>'GIF', 2=>'JPEG', 3=>'PNG', 4=>'SWF', 5=>'PSD', 6=>'BMP', 7=>'TIFF_II', 8=>'TIFF_MM', 9=>'JPC', 10=>'JP2', 11=>'JPX', 12=>'JB2', 13=>'SWC', 14=>'IFF', 15=>'WBMP', 16=>'XBM', 17=>'ICO', 18=>'COUNT' ); $size = getimagesize($fileTmpLoc); $size[2] = $imageTypeArray[$size[2]]; $fileExt = $size[2]; // Now target the last array element to get the file extension // START PHP Image Upload Error Handling -------------------------------- if (!$fileTmpLoc) { // if file not chosen echo "ERROR: Please browse for a file before clicking the upload button."; exit(); } else if($fileSize > 5242880) { // if file size is larger than 5 Megabytes echo "ERROR: Your file was larger than 5 Megabytes in size."; unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder exit(); } else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) { // This condition is only if you wish to allow uploading of specific file types echo "ERROR: Your image was not .gif, .jpg, or .png."; unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder exit(); } else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1 echo "ERROR: An error occured while processing the file. Try again."; exit(); } // END PHP Image Upload Error Handling ---------------------------------- // Place it into your "uploads" folder mow using the move_uploaded_file() function $moveResult = move_uploaded_file($fileTmpLoc, "images/".$id."_".$time.".".$fileExt); // Check to make sure the move result is true before continuing if ($moveResult != true) { echo "ERROR: File not uploaded. Try again."; exit(); } // Include the file that houses all of our custom image functions include_once("ak_php_img_lib_1.0.php"); // ---------- Start Universal Image Resizing Function -------- $target_file = "images/".$id."_".$time.".".$fileExt; $resized_file = "images/resized_".$id."_".$time."." . $fileExt; $wmax = 320; $hmax = 240; ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt); unlink($target_file); // ----------- End Universal Image Resizing Function ---------- // ---------- Start Convert to JPG Function -------- if (strtolower($fileExt) != "jpg") { $target_file = "images/resized_".$id."_".$time."." . $fileExt; $new_jpg = "images/resized_".$id."_".$time.".jpg"; ak_img_convert_to_jpg($target_file, $new_jpg, $fileExt); unlink($target_file); } $new_jpg = "images/resized_".$id."_".$time.".jpg"; if(!get_magic_quotes_gpc()) { $new_jpg = addslashes($new_jpg); $filePath = addslashes($filePath); } $resultc = mysql_query("SELECT * FROM Users2 WHERE mxitid = '$ip'"); $rowc = mysql_fetch_array($resultc); $ppica = $rowc['pprofilepic']; $naam = "ADMIN"; $naam2 = $rowc['pprofilepic']; $msg = "You Requested a Profile Picture change, please wait till an Admin can manage the request"; $msg1 = "Please aprove my Profile Picture"; $post_time = date("U"); $read1 = "unread"; $banby2 = "ADMIN"; $result = mysql_query("UPDATE Users2 SET pprofilepic='$new_jpg', aprove='requested' WHERE mxitid='$ip'") or die(mysql_error()); unlink($ppica); $query1 = "INSERT INTO pm (`username`,`mxitid`,`message`,`time`,`read`,`ip`) VALUES (\"$naam\",\"$ip\",\"$msg\",\"$post_time\",\"$read1\",\"$banby2\")"; $result1 = mysql_query($query1, $db) or die("Invalid query: " . mysql_error()); $query2 = "INSERT INTO pm (`username`,`mxitid`,`message`,`time`,`read`,`ip`) VALUES (\"$naam2\",\"$banby2\",\"$msg1\",\"$post_time\",\"$read1\",\"$ip\")"; $result2 = mysql_query($query2, $db) or die("Invalid query: " . mysql_error()); // ----------- End Convert to JPG Function ----------- // Display things to the page so you can see what is happening for testing purposes echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />"; echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />"; echo "It is an <strong>$fileType</strong> type of file.<br /><br />"; echo "The file extension is <strong>$fileExt</strong><br /><br />"; echo "The Error Message output for this upload is: $fileErrorMsg"; if($result){ header('Location: ../profile/thankyou.php'); } else { echo "ERROR"; } // close mysql mysql_close(); ?> ak_php_img_lib_1.0.php <?php // ----------------------- RESIZE FUNCTION ----------------------- // Function for resizing any jpg, gif, or png image files function ak_img_resize($target, $newcopy, $w, $h, $ext) { list($w_orig, $h_orig) = getimagesize($target); $scale_ratio = $w_orig / $h_orig; if (($w / $h) > $scale_ratio) { $w = $h * $scale_ratio; } else { $h = $w / $scale_ratio; } $img = ""; $ext = strtolower($ext); if ($ext == "gif"){ $img = imagecreatefromgif($target); } else if($ext =="png"){ $img = imagecreatefrompng($target); } else { $img = imagecreatefromjpeg($target); } $tci = imagecreatetruecolor($w, $h); // imagecopyresampled(dst_img, src_img, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h) imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig); if ($ext == "gif"){ imagegif($tci, $newcopy); } else if($ext =="png"){ imagepng($tci, $newcopy); } else { imagejpeg($tci, $newcopy, 84); } } // ---------------- THUMBNAIL (CROP) FUNCTION ------------------ // Function for creating a true thumbnail cropping from any jpg, gif, or png image files function ak_img_thumb($target, $newcopy, $w, $h, $ext) { list($w_orig, $h_orig) = getimagesize($target); $src_x = ($w_orig / 2) - ($w / 2); $src_y = ($h_orig / 2) - ($h / 2); $ext = strtolower($ext); $img = ""; if ($ext == "gif"){ $img = imagecreatefromgif($target); } else if($ext =="png"){ $img = imagecreatefrompng($target); } else { $img = imagecreatefromjpeg($target); } $tci = imagecreatetruecolor($w, $h); imagecopyresampled($tci, $img, 0, 0, $src_x, $src_y, $w, $h, $w, $h); if ($ext == "gif"){ imagegif($tci, $newcopy); } else if($ext =="png"){ imagepng($tci, $newcopy); } else { imagejpeg($tci, $newcopy, 84); } } // ------------------ IMAGE CONVERT FUNCTION ------------------- // Function for converting GIFs and PNGs to JPG upon upload function ak_img_convert_to_jpg($target, $newcopy, $ext) { list($w_orig, $h_orig) = getimagesize($target); $ext = strtolower($ext); $img = ""; if ($ext == "gif"){ $img = imagecreatefromgif($target); } else if($ext =="png"){ $img = imagecreatefrompng($target); } $tci = imagecreatetruecolor($w_orig, $h_orig); imagecopyresampled($tci, $img, 0, 0, 0, 0, $w_orig, $h_orig, $w_orig, $h_orig); imagejpeg($tci, $newcopy, 84); } ?> Quote Link to comment Share on other sites More sharing options...
cobusbo Posted October 4, 2015 Author Share Posted October 4, 2015 Ok so after a lot of tries I decided to put something new together <?php include $_SERVER['DOCUMENT_ROOT'] . '/chat2/chat_code_header.php'; include $_SERVER['DOCUMENT_ROOT'] . '/chat2/smart_resize_image.function.php'; $ip = $_SERVER["HTTP_X_MXIT_USERID_R"]; if(!isset($ip)) { $ip = "Debater"; } $time = date_create()->getTimestamp(); $result9 = mysql_query("SELECT * FROM Users2 WHERE mxitid = \"$ip\""); $row = mysql_fetch_array($result9); $id = $row['ID']; $target_dir = "images/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { //indicate which file to resize (can be any type jpg/png/gif/etc...) $file = $target_file; //indicate the path and name for the new resized file $resizedFile = 'your_path_to_file/resized_File.png'; //call the function (when passing path to pic) smart_resize_image($file , null, 320, 240, false , $resizedFile , true , false ,100 ); } else { echo "Sorry, there was an error uploading your file."; } } ?> smart_resize_image.function.php <?php /** * easy image resize function * @param $file - file name to resize * @param $string - The image data, as a string * @param $width - new image width * @param $height - new image height * @param $proportional - keep image proportional, default is no * @param $output - name of the new file (include path if needed) * @param $delete_original - if true the original image will be deleted * @param $use_linux_commands - if set to true will use "rm" to delete the image, if false will use PHP unlink * @param $quality - enter 1-100 (100 is best quality) default is 100 * @return boolean|resource */ function smart_resize_image($file, $string = null, $width = 0, $height = 0, $proportional = false, $output = 'file', $delete_original = true, $use_linux_commands = false, $quality = 100 ) { if ( $height <= 0 && $width <= 0 ) return false; if ( $file === null && $string === null ) return false; # Setting defaults and meta $info = $file !== null ? getimagesize($file) : getimagesizefromstring($string); $image = ''; $final_width = 0; $final_height = 0; list($width_old, $height_old) = $info; $cropHeight = $cropWidth = 0; # Calculating proportionality if ($proportional) { if ($width == 0) $factor = $height/$height_old; elseif ($height == 0) $factor = $width/$width_old; else $factor = min( $width / $width_old, $height / $height_old ); $final_width = round( $width_old * $factor ); $final_height = round( $height_old * $factor ); } else { $final_width = ( $width <= 0 ) ? $width_old : $width; $final_height = ( $height <= 0 ) ? $height_old : $height; $widthX = $width_old / $width; $heightX = $height_old / $height; $x = min($widthX, $heightX); $cropWidth = ($width_old - $width * $x) / 2; $cropHeight = ($height_old - $height * $x) / 2; } # Loading image to memory according to type switch ( $info[2] ) { case IMAGETYPE_JPEG: $file !== null ? $image = imagecreatefromjpeg($file) : $image = imagecreatefromstring($string); break; case IMAGETYPE_GIF: $file !== null ? $image = imagecreatefromgif($file) : $image = imagecreatefromstring($string); break; case IMAGETYPE_PNG: $file !== null ? $image = imagecreatefrompng($file) : $image = imagecreatefromstring($string); break; default: return false; } # This is the resizing/resampling/transparency-preserving magic $image_resized = imagecreatetruecolor( $final_width, $final_height ); if ( ($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG) ) { $transparency = imagecolortransparent($image); $palletsize = imagecolorstotal($image); if ($transparency >= 0 && $transparency < $palletsize) { $transparent_color = imagecolorsforindex($image, $transparency); $transparency = imagecolorallocate($image_resized, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']); imagefill($image_resized, 0, 0, $transparency); imagecolortransparent($image_resized, $transparency); } elseif ($info[2] == IMAGETYPE_PNG) { imagealphablending($image_resized, false); $color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127); imagefill($image_resized, 0, 0, $color); imagesavealpha($image_resized, true); } } imagecopyresampled($image_resized, $image, 0, 0, $cropWidth, $cropHeight, $final_width, $final_height, $width_old - 2 * $cropWidth, $height_old - 2 * $cropHeight); # Taking care of original, if needed if ( $delete_original ) { if ( $use_linux_commands ) exec('rm '.$file); else @unlink($file); } # Preparing a method of providing result switch ( strtolower($output) ) { case 'browser': $mime = image_type_to_mime_type($info[2]); header("Content-type: $mime"); $output = NULL; break; case 'file': $output = $file; break; case 'return': return $image_resized; break; default: break; } # Writing image according to type to the output destination and image quality switch ( $info[2] ) { case IMAGETYPE_GIF: imagegif($image_resized, $output); break; case IMAGETYPE_JPEG: imagejpeg($image_resized, $output, $quality); break; case IMAGETYPE_PNG: $quality = 9 - (int)((0.9*$quality)/10.0); imagepng($image_resized, $output, $quality); break; default: return false; } return true; } The new problem I have now is the renaming of the files I uploaded to $id . "_" . $time . "File Ext"..... and with the resized file I want to rename the resized file to resiezed_$id . "_". $time . "File Ext" Quote Link to comment Share on other sites More sharing options...
cobusbo Posted October 5, 2015 Author Share Posted October 5, 2015 Ok so after a lot of tries I decided to put something new together <?php include $_SERVER['DOCUMENT_ROOT'] . '/chat2/chat_code_header.php'; include $_SERVER['DOCUMENT_ROOT'] . '/chat2/smart_resize_image.function.php'; $ip = $_SERVER["HTTP_X_MXIT_USERID_R"]; if(!isset($ip)) { $ip = "Debater"; } $time = date_create()->getTimestamp(); $result9 = mysql_query("SELECT * FROM Users2 WHERE mxitid = \"$ip\""); $row = mysql_fetch_array($result9); $id = $row['ID']; $target_dir = "images/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { //indicate which file to resize (can be any type jpg/png/gif/etc...) $file = $target_file; //indicate the path and name for the new resized file $resizedFile = 'your_path_to_file/resized_File.png'; //call the function (when passing path to pic) smart_resize_image($file , null, 320, 240, false , $resizedFile , true , false ,100 ); } else { echo "Sorry, there was an error uploading your file."; } } ?> smart_resize_image.function.php <?php /** * easy image resize function * @param $file - file name to resize * @param $string - The image data, as a string * @param $width - new image width * @param $height - new image height * @param $proportional - keep image proportional, default is no * @param $output - name of the new file (include path if needed) * @param $delete_original - if true the original image will be deleted * @param $use_linux_commands - if set to true will use "rm" to delete the image, if false will use PHP unlink * @param $quality - enter 1-100 (100 is best quality) default is 100 * @return boolean|resource */ function smart_resize_image($file, $string = null, $width = 0, $height = 0, $proportional = false, $output = 'file', $delete_original = true, $use_linux_commands = false, $quality = 100 ) { if ( $height <= 0 && $width <= 0 ) return false; if ( $file === null && $string === null ) return false; # Setting defaults and meta $info = $file !== null ? getimagesize($file) : getimagesizefromstring($string); $image = ''; $final_width = 0; $final_height = 0; list($width_old, $height_old) = $info; $cropHeight = $cropWidth = 0; # Calculating proportionality if ($proportional) { if ($width == 0) $factor = $height/$height_old; elseif ($height == 0) $factor = $width/$width_old; else $factor = min( $width / $width_old, $height / $height_old ); $final_width = round( $width_old * $factor ); $final_height = round( $height_old * $factor ); } else { $final_width = ( $width <= 0 ) ? $width_old : $width; $final_height = ( $height <= 0 ) ? $height_old : $height; $widthX = $width_old / $width; $heightX = $height_old / $height; $x = min($widthX, $heightX); $cropWidth = ($width_old - $width * $x) / 2; $cropHeight = ($height_old - $height * $x) / 2; } # Loading image to memory according to type switch ( $info[2] ) { case IMAGETYPE_JPEG: $file !== null ? $image = imagecreatefromjpeg($file) : $image = imagecreatefromstring($string); break; case IMAGETYPE_GIF: $file !== null ? $image = imagecreatefromgif($file) : $image = imagecreatefromstring($string); break; case IMAGETYPE_PNG: $file !== null ? $image = imagecreatefrompng($file) : $image = imagecreatefromstring($string); break; default: return false; } # This is the resizing/resampling/transparency-preserving magic $image_resized = imagecreatetruecolor( $final_width, $final_height ); if ( ($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG) ) { $transparency = imagecolortransparent($image); $palletsize = imagecolorstotal($image); if ($transparency >= 0 && $transparency < $palletsize) { $transparent_color = imagecolorsforindex($image, $transparency); $transparency = imagecolorallocate($image_resized, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']); imagefill($image_resized, 0, 0, $transparency); imagecolortransparent($image_resized, $transparency); } elseif ($info[2] == IMAGETYPE_PNG) { imagealphablending($image_resized, false); $color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127); imagefill($image_resized, 0, 0, $color); imagesavealpha($image_resized, true); } } imagecopyresampled($image_resized, $image, 0, 0, $cropWidth, $cropHeight, $final_width, $final_height, $width_old - 2 * $cropWidth, $height_old - 2 * $cropHeight); # Taking care of original, if needed if ( $delete_original ) { if ( $use_linux_commands ) exec('rm '.$file); else @unlink($file); } # Preparing a method of providing result switch ( strtolower($output) ) { case 'browser': $mime = image_type_to_mime_type($info[2]); header("Content-type: $mime"); $output = NULL; break; case 'file': $output = $file; break; case 'return': return $image_resized; break; default: break; } # Writing image according to type to the output destination and image quality switch ( $info[2] ) { case IMAGETYPE_GIF: imagegif($image_resized, $output); break; case IMAGETYPE_JPEG: imagejpeg($image_resized, $output, $quality); break; case IMAGETYPE_PNG: $quality = 9 - (int)((0.9*$quality)/10.0); imagepng($image_resized, $output, $quality); break; default: return false; } return true; } The new problem I have now is the renaming of the files I uploaded to $id . "_" . $time . "File Ext"..... and with the resized file I want to rename the resized file to resiezed_$id . "_". $time . "File Ext" Ok so I used $kaboom to explode the filename, but now the script don't seem to run correctly it tells me that its an image/jpeg mime but also tells me its not a jpg png or gif  File is an image - image/jpeg.Sorry, only JPG, JPEG, PNG & GIF files are allowed.Sorry, your file was not uploaded. I have no idea where I'm going wrong with this code? <?php include $_SERVER['DOCUMENT_ROOT'] . '/chat2/chat_code_header.php'; include $_SERVER['DOCUMENT_ROOT'] . '/chat2/smart_resize_image.function.php'; $ip = $_SERVER["HTTP_X_MXIT_USERID_R"]; if(!isset($ip)) { $ip = "Debater"; } $time = date_create()->getTimestamp(); $result9 = mysql_query("SELECT * FROM Users2 WHERE mxitid = \"$ip\""); $row = mysql_fetch_array($result9); $id = $row['ID']; $fileName = $_FILES["fileToUpload"]["name"]; // The file name $kaboom = explode(".", $fileName); // Split file name into an array using the dot $target_dir = "uploads/"; $target_file = $target_dir . $id . "_" . $time . "." . $kaboom[2]; $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { //indicate which file to resize (can be any type jpg/png/gif/etc...) $file = $target_file; //indicate the path and name for the new resized file $resizedFile = $target_dir . "resized_" . $id . "_" . $time . "." . $kaboom[2]; //call the function (when passing path to pic) smart_resize_image($file , null, 320, 240, false , $resizedFile , true , false ,100 ); } else { echo "Sorry, there was an error uploading your file."; } } ?> Quote Link to comment Share on other sites More sharing options...
scootstah Posted October 5, 2015 Share Posted October 5, 2015 I have no idea where I'm going wrong with this code? You're still only checking the file extension to determine if it is a valid jpg, png, or gif. The file extension is completely made up. You need to check the MIME type. Quote Link to comment Share on other sites More sharing options...
cobusbo Posted October 5, 2015 Author Share Posted October 5, 2015 You're still only checking the file extension to determine if it is a valid jpg, png, or gif. The file extension is completely made up. You need to check the MIME type. $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; I am checking the mime type here? Quote Link to comment Share on other sites More sharing options...
scootstah Posted October 5, 2015 Share Posted October 5, 2015 But not here: if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { Quote Link to comment Share on other sites More sharing options...
cobusbo Posted October 5, 2015 Author Share Posted October 5, 2015 But not here: if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { So I should change it to if($check["mime"] != "image/jpg" && $check["mime"] != "image/png" && $check["mime"] != "image/jpeg" && $check["mime"] != "image/gif" ) { Â Â echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; Â Â $uploadOk = 0; or just remove it because I've already checked it before? Quote Link to comment Share on other sites More sharing options...
Solution scootstah Posted October 5, 2015 Solution Share Posted October 5, 2015 (edited) It's cleaner to have a list of allowed MIME types and compare the uploaded file's MIME type to that list, as I have demonstrated in my earlier post. Â or just remove it because I've already checked it before? You checked that it's a valid image as determined by getimagesize(), but you have not checked that it matches the file types that you want to allow. Â Another problem that I see is that you're assuming a specific naming convention for a file. Â $resizedFile = $target_dir . "resized_" . $id . "_" . $time . "." . $kaboom[2]; Â A file can have many dots in the name and still be valid. Instead, you should use the extension that is associated with the MIME type of the file. $extensions = array( 'image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif', ); $extension = $extensions($check['mime']);You can also use that array to check if the image is an allowed MIME type. You can either just do a simple isset($extensions[$check['mime']]), or use in_array: if (!in_array($check['mime'], array_keys($extensions))) { // not a valid image } Edited October 5, 2015 by scootstah Quote Link to comment Share on other sites More sharing options...
cobusbo Posted October 5, 2015 Author Share Posted October 5, 2015 It's cleaner to have a list of allowed MIME types and compare the uploaded file's MIME type to that list, as I have demonstrated in my earlier post.   You checked that it's a valid image as determined by getimagesize(), but you have not checked that it matches the file types that you want to allow.  Another problem that I see is that you're assuming a specific naming convention for a file. A file can have many dots in the name and still be valid. Instead, you should use the extension that is associated with the MIME type of the file. $extensions = array( 'image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif', ); $extension = $extensions($check['mime']);You can also use that array to check if the image is an allowed MIME type. You can either just do a simple isset($extensions[$check['mime']]), or use in_array: if (!in_array($check['mime'], array_keys($extensions))) { // not a valid image } Ok so I implemented the changes but getting the error     File is an image - image/jpeg. Fatal error: Function name must be a string in /home/u342037492/public_html/chat2/profile/new.php on line 44 <?php include $_SERVER['DOCUMENT_ROOT'] . '/chat2/chat_code_header.php'; include $_SERVER['DOCUMENT_ROOT'] . '/chat2/smart_resize_image.function.php'; $ip = $_SERVER["HTTP_X_MXIT_USERID_R"]; if(!isset($ip)) { $ip = "Debater"; } $time = date_create()->getTimestamp(); $result9 = mysql_query("SELECT * FROM Users2 WHERE mxitid = \"$ip\""); $row = mysql_fetch_array($result9); $id = $row['ID']; // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); $extensions = array( 'png' => 'image/png', 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'gif' => 'image/gif', 'bmp' => 'image/bmp',); $extension = $extensions($check['mime']); $target_dir = "uploads/"; $target_file = $target_dir . $id . "_" . $time . "." . $extension; $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if (!in_array($check['mime'], array_keys($extensions))) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { //indicate which file to resize (can be any type jpg/png/gif/etc...) $file = $target_file; //indicate the path and name for the new resized file $resizedFile = $target_dir . "resized_" . $id . "_" . $time . "." . $extension; //call the function (when passing path to pic) smart_resize_image($file , null, 320, 240, false , $resizedFile , true , false ,100 ); } else { echo "Sorry, there was an error uploading your file."; } } ?> Quote Link to comment Share on other sites More sharing options...
scootstah Posted October 5, 2015 Share Posted October 5, 2015 $extension = $extensions[$check['mime']]; Quote Link to comment Share on other sites More sharing options...
cobusbo Posted October 5, 2015 Author Share Posted October 5, 2015 (edited) Thank you  Just one last question I'm storing the path the file in my database table, How would I first check my table field if it already have the path to a previous picture and if it does unlink the picture from the directory before storing the new file in the directory and update the field in my database?  To retrieve the field I will use $resultc = mysql_query("SELECT * FROM Users2 WHERE mxitid = '$ip'"); $rowc = mysql_fetch_array($resultc); $ppica = $rowc['pprofilepic']; Here is my latest code <?php include $_SERVER['DOCUMENT_ROOT'] . '/chat2/chat_code_header.php'; include $_SERVER['DOCUMENT_ROOT'] . '/chat2/smart_resize_image.function.php'; $ip = $_SERVER["HTTP_X_MXIT_USERID_R"]; if(!isset($ip)) { $ip = "Debater"; } $time = date_create()->getTimestamp(); $result9 = mysql_query("SELECT * FROM Users2 WHERE mxitid = \"$ip\""); $row = mysql_fetch_array($result9); $id = $row['ID']; // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); $extensions = array( 'image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif', ); $extension = $extensions[$check['mime']]; $target_dir = "uploads/"; $target_file = $target_dir . $id . "_" . $time . "." . $extension; $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if (!in_array($check['mime'], array_keys($extensions))) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { //indicate which file to resize (can be any type jpg/png/gif/etc...) $file = $target_file; //indicate the path and name for the new resized file $resizedFile = $target_dir . "resized_" . $id . "_" . $time . "." . $extension; //call the function (when passing path to pic) smart_resize_image($file , null, 320, 240, false , $resizedFile , true , false ,75 ); $resultc = mysql_query("SELECT * FROM Users2 WHERE mxitid = '$ip'"); $rowc = mysql_fetch_array($resultc); $ppica = $rowc['pprofilepic']; $naam = "ADMIN"; $naam2 = $rowc['Username']; $msg = "You Requested a Profile Picture change, please wait till an Admin can manage the request"; $msg1 = "Please aprove my Profile Picture"; $post_time = date("U"); $read1 = "unread"; $banby2 = "ADMIN"; $result = mysql_query("UPDATE Users2 SET pprofilepic='$resizedFile', aprove='requested' WHERE mxitid='$ip'") or die(mysql_error()); unlink($ppica); $query1 = "INSERT INTO pm (`username`,`mxitid`,`message`,`time`,`read`,`ip`) VALUES (\"$naam\",\"$ip\",\"$msg\",\"$post_time\",\"$read1\",\"$banby2\")"; $result1 = mysql_query($query1, $db) or die("Invalid query: " . mysql_error()); $query2 = "INSERT INTO pm (`username`,`mxitid`,`message`,`time`,`read`,`ip`) VALUES (\"$naam2\",\"$banby2\",\"$msg1\",\"$post_time\",\"$read1\",\"$ip\")"; $result2 = mysql_query($query2, $db) or die("Invalid query: " . mysql_error()); } else { echo "Sorry, there was an error uploading your file."; } } if($result){ header('Location: ../profile/thankyou.php'); } else { echo "ERROR"; } ?> Edited October 5, 2015 by cobusbo Quote Link to comment Share on other sites More sharing options...
cobusbo Posted October 5, 2015 Author Share Posted October 5, 2015 Thank you! Â For someone else who wish to use something similar here is my final script <?php include $_SERVER['DOCUMENT_ROOT'] . '/chat2/chat_code_header.php'; include $_SERVER['DOCUMENT_ROOT'] . '/chat2/smart_resize_image.function.php'; $ip = $_SERVER["HTTP_X_MXIT_USERID_R"]; if(!isset($ip)) { $ip = "Debater"; } $time = date_create()->getTimestamp(); $result9 = mysql_query("SELECT * FROM Users2 WHERE mxitid = \"$ip\""); $row = mysql_fetch_array($result9); $id = $row['ID']; // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); $extensions = array( 'image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif', 'image/bmp' => 'bmp', ); $extension = $extensions[$check['mime']]; $target_dir = "images/"; $target_file = $target_dir . $id . "_" . $time . "." . $extension; $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if (!in_array($check['mime'], array_keys($extensions))) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { //indicate which file to resize (can be any type jpg/png/gif/etc...) $file = $target_file; //indicate the path and name for the new resized file $resizedFile = $target_dir . "resized_" . $id . "_" . $time . "." . $extension; //call the function (when passing path to pic) smart_resize_image($file , null, 320, 240, false , $resizedFile , true , false ,75 ); $resultc = mysql_query("SELECT * FROM Users2 WHERE mxitid = '$ip'"); $rowc = mysql_fetch_array($resultc); $ppica = $rowc['pprofilepic']; unlink($ppica); $naam = "ADMIN"; $naam2 = $rowc['Username']; $msg = "You Requested a Profile Picture change, please wait till an Admin can manage the request"; $msg1 = "Please aprove my Profile Picture"; $post_time = date("U"); $read1 = "unread"; $banby2 = "ADMIN"; $result = mysql_query("UPDATE Users2 SET pprofilepic='$resizedFile', aprove='requested' WHERE mxitid='$ip'") or die(mysql_error()); $query1 = "INSERT INTO pm (`username`,`mxitid`,`message`,`time`,`read`,`ip`) VALUES (\"$naam\",\"$ip\",\"$msg\",\"$post_time\",\"$read1\",\"$banby2\")"; $result1 = mysql_query($query1, $db) or die("Invalid query: " . mysql_error()); $query2 = "INSERT INTO pm (`username`,`mxitid`,`message`,`time`,`read`,`ip`) VALUES (\"$naam2\",\"$banby2\",\"$msg1\",\"$post_time\",\"$read1\",\"$ip\")"; $result2 = mysql_query($query2, $db) or die("Invalid query: " . mysql_error()); } else { echo "Sorry, there was an error uploading your file."; } } if($result){ header('Location: ../profile/thankyou.php'); } else { echo "ERROR"; } ?> Quote Link to comment Share on other sites More sharing options...
benanamen Posted October 5, 2015 Share Posted October 5, 2015 What has not been mentioned is that you are using obsolete Mysql code that does not work in the latest version of Php. You need to be using PDO with parameterized queries or at the least Mysqli Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.