Photo Upload getimagesize() warning - filename cannot be empty - php

I've run into a conundrum and was wondering if anyone might be able to give me a straight answer. So I built a photo upload script using PHP/MySQL. Within the script photos are re-sized and given a temporary name while being uploaded. I tested it using several pictures (file size 220 KB | 960 x 720) and everything was working just fine. Then I attempted to upload several pictures from my digital camera (file size 2.47 MB | 3000 x 4000) and all of a sudden I got this error:
Warning: getimagesize() [function.getimagesize]: Filename cannot be empty in /php_parsers/photo_system.php on line 94
Warning: Cannot modify header information - headers already sent by (output started at /php_parsers/photo_system.php:94) in /php_parsers/photo_system.php on line 96
I checked stackoverflow for a post with a similar issue and came upon one however it didn't seem to apply to the scenario I'm experiencing.
Here is the applicable code for "photo_system.php". I have commented the offending lines 94 and 96. Any help/ideas you could give would be greatly appreciated!
<?php
if (isset($_FILES["photo"]["name"]) && isset($_POST["gallery"])){
$sql = "SELECT COUNT(id) FROM photos WHERE user='$log_username'";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
if($row[0] > 79){
header("location: ../message.php?msg=The system allows only 80 pictures total");
exit();
}
$gallery = preg_replace('#[^a-z 0-9,]#i', '', $_POST["gallery"]);
$fileName = $_FILES["photo"]["name"];
$fileTmpLoc = $_FILES["photo"]["tmp_name"];
$fileType = $_FILES["photo"]["type"];
$fileSize = $_FILES["photo"]["size"];
$fileErrorMsg = $_FILES["photo"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
$db_file_name = date("DMjGisY")."".rand(1000,9999).".".$fileExt; // WedFeb272120452013RAND.jpg
list($width, $height) = getimagesize($fileTmpLoc); //Offending Line 94
if($width < 10 || $height < 10){
header("location: ../message.php?msg=ERROR: That image has no dimensions"); //Offending Line 96
exit();
}
if($fileSize > 4194304) {
header("location: ../message.php?msg=ERROR: Your image file was larger than 4mb");
exit();
} else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
header("location: ../message.php?msg=ERROR: Your image file was not jpg, gif or png type");
exit();
} else if ($fileErrorMsg == 1) {
header("location: ../message.php?msg=ERROR: An unknown error occurred");
exit();
}
$moveResult = move_uploaded_file($fileTmpLoc, "../user/$log_username/$db_file_name");
if ($moveResult != true) {
header("location: ../message.php?msg=ERROR: File upload failed");
exit();
}
include_once("../php_includes/image_resize.php");
$wmax = 800;
$hmax = 600;
if($width > $wmax || $height > $hmax){
$target_file = "../user/$log_username/$db_file_name";
$resized_file = "../user/$log_username/$db_file_name";
img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
}
$sql = "INSERT INTO photos(user, gallery, filename, uploaddate) VALUES ('$log_username','$gallery','$db_file_name',now())";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
header("location: ../photos.php?u=$log_username");
exit();
}
?><?php
if (isset($_POST["delete"]) && $_POST["id"] != ""){
$id = preg_replace('#[^0-9]#', '', $_POST["id"]);
$query = mysqli_query($db_conx, "SELECT user, filename FROM photos WHERE id='$id' LIMIT 1");
$row = mysqli_fetch_row($query);
$user = $row[0];
$filename = $row[1];
if($user == $log_username){
$picurl = "../user/$log_username/$filename";
if (file_exists($picurl)) {
unlink($picurl);
$sql = "DELETE FROM photos WHERE id='$id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
}
}
mysqli_close($db_conx);
echo "deleted_ok";
exit();
}
?>

OK everyone. I figured out what the issue was. Hopefully this will help someone in the future. So I checked my phpinfo() and found that upload_max_filesize was only set to 2M. I added php.ini to the directory of the offending file and included:
upload_max_filesize = 250M
post_max_size = 250M
max_execution_time = 300
date.timezone = "America/Los_Angeles"
I had to add the date.timezone because my system didn't like the fact that I didn't have it defined. Anyway this has resolved the issue.

Related

PHP file size upload condition not working

Hi i am trying to upload file and sets the limit 1 mb.
when file size is greater than 1 mb file doesn't move in folder but it updates in in mysql database.
<?php
$fileName = $_FILES['myfile']['name'];
$fileNameTmp = $_FILES['myfile']['tmp_name'];
$fileSize = $_FILES["myfile"]["size"];
$fileExtension = explode('.',$fileName);
$fileExtension = strtolower(end($fileExtension));
$maxsize = 1000000;
$fileUniqueName = uniqid().'.'.$fileExtension;
$store = 'uploads/'.$fileUniqueName;
if($fileSize>$maxsize)
{
echo 'size exceed';
}
else
{
move_uploaded_file($fileNameTmp,$store);
$query = mysql_query("update users set image = '$fileUniqueName' where id = '$_SESSION[id]'");
}
?>
Expected result: file name should not update in database if size exceeds 1 mb.
I'm guessing the file didn't upload and you're getting $fileSize equal to 0, bypassing your if condition.
Change it to if($fileSize > $maxsize || $fileSize == 0) to capture the error.

Issue with image uploading PHP

I'm trying to create a form where users can select an image and set their profile picture. After this I want to get this specific information and display it within HTML.
I have the following code inside profile.php;
if(isset($_POST['submit']) ){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$mysql->setUserAvatar($fileName, $fileTmpLoc, $fileType, $fileSize, $fileErrorMsg, $s_email);
}
I have the following code inside mysql.php (this code is inside a class name mysql):
function setUserAvatar($fileName, $fileTmpLoc, $fileType, $fileSize, $fileErrorMsg, $s_email){
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
echo "Image is too small";
exit();
}
$db_file_name = rand(100000000000,999999999999) . "." . $fileExt;
echo $db_file_name;
if($fileSize > 1048576) {
echo "Image can't be larger than 1MB";
exit();
} else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
echo "The file extension should be .gif, .jpg or .png";
exit();
} else if ($fileErrorMsg == 1) {
echo "An unknown error occurred";
exit();
}
$sql = "SELECT avatar FROM users WHERE email='$s_email' LIMIT 1";
$query = mysqli_query($this->db, $sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
if($avatar != ""){
$picurl = "../user/$s_email/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
}
$moveResult = move_uploaded_file($fileTmpLoc, SITE_ROOT . "/../user/$s_email/". $db_file_name);
if ($moveResult != true) {
echo "File upload failed";
exit();
}
$sql = "UPDATE users SET avatar='$db_file_name' WHERE email='$s_email' LIMIT 1";
$query = mysqli_query($this->db, $sql);
}
After this is done, I want to do something like:
<img src="user/" . $s_email . "/" . $data['avatar'] . " />
How ever, when I try to reach the avatar element from the MySQL database, I always get the same number, which is: 2147483647 (but in the user folder everything went right). So there is a problem with the value that is getting inserted into the database. Any suggestions what this problem might be?
EDIT: I've fixed the issue by decreasing the length of the random number. However, the problem is still that the value in the database hasn't receive the extension? The column datatype of avatar is VARCHAR.
It's this line:
$db_file_name = rand(100000,999999) . "." . $fileExt;
Yes, a nice feature of most random number generators is that they produce repeatable results unless you tell them not to.
In the case of PHP you tell it not to start at the same place using srand()
Your number is to big. and not very random.
$db_file_name = rand(100000000000,999999999999)
Your min and max are very close to each other/in wrong order, and to large because the number your getting 2147483647 = 2^30 -1 is most likely the size limit for the type of column input you decided to use for the name.
rand documentation http://php.net/manual/en/function.rand.php
Change your column type to something like varchar(40)
I'd also recommend not using random numbers greater than php's signed 32 bit integer rand(0,2147483647);

How to have my PHP script make images square, while maintaining their original ratio?

I have been developing my website for some time now, and I am looking to make it even better with one small detail. Currently, when a user creates and account, they can view their "My Page" and do all sorts of things, including change their profile picture from the default one I have provided, to whatever they want. Unfortunately, if they were to upload an image with a ratio of anything greater than or less than 1:1, i.e. 300x200, then my script will re-size it to fit the avatar form, but it keeps the ratio, and makes the image float to the top of the box. Here is an image of an avatar that does not have a 1:1 ratio:
As you can see, the image is as I describe it above. The only time it makes a perfect square is when the image that the user uploads has a 1:1 ratio. Here is an example:
Obviously, it is unreasonable to expect that a user will always upload a 1:1 image. So what I am looking for is someone to help me tweak my script, which I will provide, so that on all avatar uploads, even if the image has a 1:1 ratio, will pretty much mount the image into a black "canvas", for lack of better wording, and center the image on that canvas both vertically and horizontally. Here is what I mean, using an image that I edited in Photoshop to give it the black canvas:
As you can see, the profile picture in this last image is exactly what I need my script to do. I will provide my script:
PHP
<?php
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
header("location: ../message.php?msg=ERROR: That image has no dimensions");
exit();
}
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
if($fileSize > 2048576) {
header("location: ../message.php?msg=ERROR: Your image file was larger than 2MB");
exit();
} else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
header("location: ../message.php?msg=ERROR: Your image file was not jpg, gif or png type");
exit();
} else if ($fileErrorMsg == 1) {
header("location: ../message.php?msg=ERROR: An unknown error occurred");
exit();
}
$sql = "SELECT avatar FROM users WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
if($avatar != ""){
$picurl = "../user/$log_username/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
}
$moveResult = move_uploaded_file($fileTmpLoc, "../user/$log_username/$db_file_name");
if ($moveResult != true) {
header("location: ../message.php?msg=ERROR: File upload failed");
exit();
}
include_once("../php_includes/image_resize.php");
$target_file = "../user/$log_username/$db_file_name";
$resized_file = "../user/$log_username/$db_file_name";
$wmax = 200;
$hmax = 300;
img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
$sql = "UPDATE users SET avatar='$db_file_name' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
header("location: ../user.php?u=$log_username");
exit();
}
?>
Thanks in advance, any help will be much appreciated!
Insert the image as a background instead of an img tag, then you can position it center.
<div class="avatar"></div>
.avatar {
width: 200px;
height: 200px;
background-image: url("avatar.png");
background-repeat: no-repeat;
background-position: center center;
border-radius: 50%; // If you want it to be a circle
}

Any way to generate random file name when uploading?

I have created a website that uploads anything. The problem I have is that I'm new to all this. I have tried every code that generates random strings but I have nothing. Here is the code anyway:
<?php
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "uploads/$fileName")) {
echo '<a href="uploads/'.$fileName.'"><input type="button" class="button"
value="Download" /></a>';
} else {
echo "move_uploaded_file function failed";
}
?>
Could there be a way to generate random file names so that when someone uploads the same name as a file already on the server, it does not overwrite the existing file?
$fileName = "image_".uniqid();
The uniqid() function generates a unique ID based on the microtime
(current time in microseconds).
About uniqid function: http://www.php.net/manual/en/function.uniqid.php
You can use md5(microtime()) to get unique file name even you uploading more than one file at a time
you can use microtime time to make sure file name is unique.
$file_name = "custom_name_" . microtime();
Because a folder is limited to 65535 files, you need to create subfolders. This technique creates 3 subfolders (with 3 characters each) depending on the timestamp then creates a random filename.
For more randomness and future-proofness (because using time() and microtime() is weak if you have multiple users uploading at the same time) :
//Get the extension of the file
$fileExtension = end(explode(".", $_FILES['item']['name']));
$randOctalName = openssl_random_pseudo_bytes(5);
$randName = bin2hex($randOctalName).".".$fileExtension;
//Save it into uploads/123/456/789/
$path = "";
$timestamp = time();
$path = substr($timestamp,0,3)."/".substr($timestamp,3,3)."/".substr($timestamp,6,3)."/";
$relativePath = './uploads/'.$path;$timestamp = time();
$path = substr($timestamp,0,3)."/".ubstr($timestamp,3,3)."/".substr($timestamp,6,3)."/";
$relativePath = './uploads/'.$path;
_r_mkdir($relativePath);
And the mkdir recursive function :
private function _r_mkdir($path, $mode = 0755, $recursive = true)
{
if(empty($path)){
return false;
}
if($recursive) {
$toDo = substr($path, 0, strrpos($path, '/'));
if($toDo !== '.' && $toDo !== '..'){
_r_mkdir($toDo, $mode);
}
}
if(!is_dir($path)){
mkdir($path, $mode);
}
return true;
}
use the timestamp (or microtime), so you know it is necessarily different every time
$fileName = "image_".time();
TimeStamp
Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
Microtime
microtime() returns the current Unix timestamp with microseconds. This function is only available on operating systems that support the gettimeofday() system call.
//you can use both random and time function to get more unique no count:
$fileName = 'mypic'.mt_rand(100000, 999999).'_'.time(). $_FILES["file1"]["name"];
use are:-
mt_rand(100000, 999999)// for randm no.
time()// for timestring
$_FILES["file1"]["name"]//also you can give your file name
Study this code thoroughly. This is all you need.
<?php
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != "")
{
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileError = $_FILES["avatar"]["error"];
$kaboom = explode(".",$fileName);
$fileExt = end($kaboom);
list($width,$height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10)
{
header("location: ../message.php?msg=ERROR: That image has no dimensions");
exit();
}
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
if($fileSize > 5048576)
{
header("location: ../message.php?msg=ERROR: Your image file was larger than 1mb");
exit();
}
else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) )
{
header("location: ../message.php?msg=ERROR: Your image file was not jpg, gif or png type");
exit();
}
else if ($fileErrorMsg == 1)
{
header("location: ../message.php?msg=ERROR: An unknown error occurred");
exit();
}
$sql = "SELECT avatar FROM users WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx,$sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
if($avatar != "")
{
$picurl = "../user/$log_username/$avatar";
if (file_exists($picurl))
unlink($picurl);
}
$moveResult = move_uploaded_file($fileTmpLoc,"../user/$log_username/$db_file_name");
if ($moveResult != true)
{
header("location: ../message.php?msg=ERROR: File upload failed");
exit();
}
include_once("../php_includes/image_resize.php");
$target_file = "../user/$log_username/$db_file_name";
$resized_file = "../user/$log_username/$db_file_name";
$wmax = 200;
$hmax = 300;
img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
$sql = "UPDATE users SET avatar='$db_file_name' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
header("location: ../user.php?u=$log_username");
exit();
}
?>
try this
$now=date('d/m/y');
if(move_uploaded_file($fileTmpLoc, "uploads/$now.$fileName"))
it will add date infront of the filename

PHP Upload & Crop Image

I'm trying to create a php cropper based on other online tutorials but I keep coming up with errors and I can't understand what the actual errors mean. Here is my php code with the errors written in too:
<?php
include("settings.php");
$extension = end(explode(".", $_FILES["avatar"]["name"]));
$id = mysqli_real_escape_string($con, $_POST["id"]);
$time = time();
$avatarid= time().'-'.mt_rand(1000, 9999);
$avatar = mysqli_real_escape_string($con, $_POST["avatar"]);
$w= mysqli_real_escape_string($con, $_POST["w"]);
$h= mysqli_real_escape_string($con, $_POST["h"]);
$x= mysqli_real_escape_string($con, $_POST["x"]);
$y= mysqli_real_escape_string($con, $_POST["y"]);
$rw = 300;
$rh = 300;
$path = "../uploads/avatars/";
$unlink = "$path$avatar";
$newimage = "$path$avatar";
$insert_avatar_sql = "UPDATE members SET avatar = '".$avatarid.".".$extension."' WHERE id = '$id'";
$insert_avatar_res = mysqli_query($con, $insert_avatar_sql);
if(mysqli_affected_rows($con)>0){
unlink($unlink);
move_uploaded_file($_FILES["avatar"]["tmp_name"],"$path" . $avatarid . "." . $extension);
$wratio = ($rw/$w);
$hratio = ($rh/$h);
$newW = ceil($w * $wratio);
$newH = ceil($h * $hratio);
$newimg = imagecreatetruecolor($newW,$newH);
$ext=$extension;
if($ext=="jpg" || $ext=="jpeg" )
{
$source = imagecreatefromjpeg($newimage); // Warning: imagecreatefromjpeg(../uploads/avatars/1380641918-4496.jpg) [function.imagecreatefromjpeg]: failed to open stream: No such file or directory in C:\AppServ\www\music.co.uk\php\avatar.php on line 34
}
else if($ext=="png")
{
$source = imagecreatefrompng($newimage);
}
else
{
$source = imagecreatefromgif($newimage);
}
imagecopyresampled($newimg,$source,0,0,$x1,$y1,$newW,$newH,$w,$h); // Warning: imagecopyresampled(): supplied argument is not a valid Image resource in C:\AppServ\www\music.co.uk\php\avatar.php on line 44
uploads/1380642027-5994
imagejpeg($newimg,$path.$avatarid,90);
echo "uploads/".$avatarid;
exit;
header("Location: ../edit.php?page=profile");
}
else{
header("Location: ../404.php");
exit();
}
?>
Please help me with this, I've been messing with Avatar uploads for 3 days solid now and I want to get this done, even if I have to use a different php script
For your first error you're passing $newimage to imagecreatefromjpeg(). During this process $newimage does not have a value that imagecreatefromjpeg() can understand. So basically if $newimage is a file or directory, it's not valid so your problem is the value assigned to $newimage.(Make sure "../uploads/avatars/1380641918-4496.jpg" is valid) Not sure what to tell you on the second warning. Good Luck.

Categories