PHP Overwrite Uploaded Image - php

I am trying some file upload code which I Googled.
Now Issue is when I try to upload image and if its already in folder then its over write and issues come. I Try Code From here and here as well but I face some error.
Here is my code. Can I do in this code that its upload file with some extra name which stop over write of existing file??
if(isset($_REQUEST['main']))
{
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
/*if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"] < 20000) && in_array($extension, $allowedExts)) {*/
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
if( move_uploaded_file($_FILES["file"]["tmp_name"], "../img/catalog/" . $_FILES["file"]["name"]) ){
$filepath = "img/catalog/" . $_FILES["file"]["name"];
}else{
echo $_FILES["file"]["name"]." unable to store";
}
}
/*}
} else {
echo "Invalid file";
}*/
}
$main = $_REQUEST['main'];
$sql="INSERT INTO image VALUES ('', '$filepath', '$main')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}

You can check if the file exists using file_exists.
If it exist, add some extra characters to the file name. Then you can save it.
Here is a function that generates random characters :
function randomString($length) {
$str="";
$chars = "subinsblogabcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen($chars);
for($i = 0;$i < $length;$i++) {
$str .= $chars[rand(0,$size-1)];
}
return $str;
}
Replace the code :
if( move_uploaded_file($_FILES["file"]["tmp_name"], "../img/catalog/" . $_FILES["file"]["name"]) ){
$filepath = "img/catalog/" . $_FILES["file"]["name"];
}else{
echo $_FILES["file"]["name"]." unable to store";
}
with :
$newLocation = "../img/catalog/" . $_FILES["file"]["name"];
if(file_exists($newLocation)){
$newLocation .= randomString(10); // We append 10 new characters
}
if( move_uploaded_file($_FILES["file"]["tmp_name"], $newLocation) ){
$filepath = str_replace("../img", "img", $newLocation); // make File Path starting with img/
}else{
echo $_FILES["file"]["name"]." unable to store";
}
The above code will check if the file exists. If yes, then a string of 10 random characters is appended to the file name and stored in the destination folder.

You didnt mention your problem but I think you have missed a point in your
if else
part. write it like this :
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
$_FILES["file"]["name"] = $_FILES["file"]["name"].$your_new_number;
}
if( move_uploaded_file($_FILES["file"]["tmp_name"], "../img/catalog/" . $_FILES["file"]["name"]) ){
$filepath = "img/catalog/" . $_FILES["file"]["name"];
}else{
echo $_FILES["file"]["name"]." unable to store";
}
}

Related

Unable to display BLOB image with Data URI

I have a jpg image stored in MySql Database table in the column with the data type as BLOB that part of the php code works fine.
I am trying to display that image using the below php code but it would not work. I see a small icon on the screen which is definitely not the image ? what's wrong any help?
1) Read the image php file
<?php
header("Content-Type: image/jpg");
$db=mysqli_connect("localhost","root","root123","deal_bank","3306");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($db,"deal_bank");
$sql = "SELECT * FROM image";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpg;base64,'.base64_encode( $result['image'] ).'"/>';
?>
2) Upload the file into the MySql Database
<?php
$con=mysqli_connect("localhost","root","root123","deal_bank","3306");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,"deal_bank");
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] > 20000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
$stmt = $con->prepare('INSERT INTO image (image) VALUES (?)');
$null = null;
$stmt->bind_param('b', $null);
$stmt->send_long_data(0, file_get_contents($_FILES['file']['tmp_name']));
$stmt->execute();
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
// $image = addslashes(file_get_contents($_FILE['file']['tmp_name']));
//mysqli_query($con,"INSERT INTO image (image) VALUES ('{$image}') ");
}
}
} else {
echo "Invalid file";
}
?>
I replaced
header("Content-Type: image/jpg");
with
ob_start( );
it now works fine i am not sure what was the problem before ?

PHP file upload restricting images over 20kb

I've created an image upload using PHP, the idea being that the image will save to a directory and the path to the the database which is pretty standard. The problem is it wont save anything over 20kb. I have increased the max upload and post max size in the php.ini file to 10M and have also set size to < 200000kb in the function but it makes no difference. Can somebody please tell me where i have been banging my head off this for days now :(
File upload function (based on example at W3Schools)
function upload_file(){
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["page_main_image"]["name"]);
$extension = end($temp);
if ((($_FILES["page_main_image"]["type"] == "image/gif")
|| ($_FILES["page_main_image"]["type"] == "image/jpeg")
|| ($_FILES["page_main_image"]["type"] == "image/jpg")
|| ($_FILES["page_main_image"]["type"] == "image/pjpeg")
|| ($_FILES["page_main_image"]["type"] == "image/x-png")
|| ($_FILES["page_main_image"]["type"] == "image/png"))
&& ($_FILES["page_main_image"]["size"] < 200000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["page_main_image"]["error"] > 0) {
echo "Return Code: " . $_FILES["page_main_image"]["error"] . "<br />";;
}
else {
echo "Upload: " . $_FILES["page_main_image"]["name"] . "<br />";
echo "Type: " . $_FILES["page_main_image"]["type"] . "<br />";
echo "Size: " . ($_FILES["page_main_image"]["size"] / 1024) . " kb<br />";
if (file_exists("uploads/" . $_FILES["page_main_image"]["name"]))
{
echo $_FILES["page_main_image"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["page_main_image"]["tmp_name"],
"uploads/" . $_FILES["page_main_image"]["name"]);
echo "Stored in: " . "uploads/" . $_FILES["page_main_image"]["name"] . "<br />";
$image="{$_FILES['page_main_image']['name']}";
}
}
}
else {
echo "Invalid file";
}
return $image;
}
The form processing is as follows:
<?php
if (isset($_POST['submit'])) {
//Process the form
$image = upload_file();
$project_id = $_POST['project_id'];
//var_dump ($project_id);
$wireframe_title = mysql_prep($_POST["wireframe_title"]);
$browser_title = $_POST["browser_title"];
$url_key = $_POST["url_key"];
$wireframe_type = $_POST["wireframe_type"];
//$image = $_POST["page_main_image"];
$page_bg_color = $_POST ["page_bg_color"];
$query = "INSERT INTO wireframes (";
$query .= " project_id, wireframe_title, browser_title, url_key, wireframe_type, page_main_image, page_bg_color";
$query .= " ) VALUES (";
$query .= " '{$project_id}','{$wireframe_title}', '{$browser_title}', '{$url_key}', '{$wireframe_type}', '{$image}', '{$page_bg_color}' ";
$query .= ")";
echo $query;
try { $result = mysqli_query($connection, $query);
} catch (Exception $e) {
return 'Caught exception: '+ $e->getMessage()+ "\n";
}
//Test if there was a query error
if ($result) {
//Success
// would normally use a redirect ie redirect_to("somepage.php");
//$message = "Subject created.";
redirect_to("wireframes.php?id=$project_id");
}else {
//failure
//$message = "Subject creation failed.";
//redirect_to("add_project.php");
echo $query;
}
} else {
// This is probably a GET request
redirect_to("add_edit_wireframe.php?id= echo $_GET[$project_id]");
}
?>
The size in $_FILES is expressed in bytes. 200.000 = around 195 kilobyte.
Did you tested it without that condition in the if statement?

Syntax Error When Writing Data Into a Table - unexpected T_VARIABLE

Parse error: syntax error, unexpected T_VARIABLE in upload_file.php on line 44
The code worked until I added these lines :
Lines 42-44 :
$path = "uploads/" . $_FILES["file"]["name"];
$Link = mysql_connect($Host, $User, $Password);
$Query = "INSERT INTO $Table_7 VALUES ('0','"$path"')";
Thanks it sorta worked. The script is for uploading images into a folder. That part of works but I cannot write the image path into the table. I have a table with two fields :
picid - auto incrementing primary key
path - varchar(60)
Any idea what I'm doing wrong? I've added the full script.
UPDATE. FULL CODE
<?php
include "connect.php";
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 10000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("uploads/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"uploads/" . $_FILES["file"]["name"]);
echo "Stored in: " . "uploads/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
$path = "uploads/" . $_FILES["file"]["name"];
$Link = mysql_connect($Host, $User, $Password);
$Query = "INSERT INTO $Table_7 VALUES ('0','{$path}')";
?>
You are missing you concatenation operator on line 44:
$Query = "INSERT INTO $Table_7 VALUES ('0','"$path"')";
should be
$Query = "INSERT INTO $Table_7 VALUES ('0','".$path."')";
or
$Query = "INSERT INTO $Table_7 VALUES ('0','$path')";
or
$Query = "INSERT INTO $Table_7 VALUES ('0','{$path}')";

PHP - file upload will not move file to directory

the file upload script is below...the storing of the file name in the DB is working fine, but the file is not being moved to the proper directory. the "Avatars" file is located in the "/httpdocs/" directory. I have set the permissions to "777".
<?php
require('dbconfig.php');
//generate a random string
function generateRandomString($length = 40) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
$customname = generateRandomString();
$newimagename = "$customname." . pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION);
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
//echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
header ('Location: /dashboard.php?filetype=invalid');
exit();
}
else
{
//echo "Upload: " . $_FILES["file"]["name"] . "<br>";
//echo "Type: " . $_FILES["file"]["type"] . "<br>";
//echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
//echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
//echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"avatars/" . $newimagename);
//echo "Stored in: " . "profile_videos/" . $newimagename;
$storedtoken = $_COOKIE['login_token'];
$mysqlicon = mysqli_connect($db_host, $db_username, $db_password, $db_name);
//identify the user by comparing tokens
$find_user_id = mysqli_query($mysqlicon, "SELECT * FROM logins WHERE token='$storedtoken'");
//grab the user's UUID
while ($row = mysqli_fetch_array($find_user_id)) {
$uuid = $row['userID'];
mysqli_query($mysqlicon, "UPDATE families SET avatarURL='avatars/$newimagename' where husbandID='$uuid' OR wifeID='$uuid'");
mysqli_close($mysqlicon);
}
header ('Location: /dashboard.php');
}
}
}
else
{
header ('Location: /dashboard.php?profile-video-upload=invalid');
mysqli_close($mysqlicon);
exit();
}
?>

Secure image upload with PHP?

I want to upload images to my server from browser window. However, the upload field will be visible for everyone, so I need to set up some restrictions. I've only found the w3schools file upload (and as of w3fools.com I don't trust it). I want the restrictions to be:
Maximum size 2,5M
Image types jpg, jpeg, png, gif
So here's the code that w3schools provides, but it won't actually save the file anywhere? I've modified it a bit to meet my needs.
<?php
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/jpeg"))
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 2500000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
}
else
{
echo "Invalid file";
}
?>
And as I don't want my site to be hacked, I want a secure solution, any help on this?
Edit
The code doesn't even do anything. So how should I do it?
You need to use php move_upload_file function and also I have made changes to your if statement here is the working and tested example:
<?php
if (isset($_REQUEST["submit"])) {
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ($_FILES["file"]["type"] == "image/gif" || $_FILES["file"]["type"] == "image/jpg" || $_FILES["file"]["type"] == "image/jpeg" || $_FILES["file"]["type"] == "image/png" && $_FILES["file"]["size"] < 2500000 && in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else {
$fname = $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $fname);
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $fname;
}
}
else {
echo "Invalid file type";
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" name="submit" value="submit" />
</form>
You can also use getimagesize function as suggested by doing next thing:
$size = getimagesize("http://www.simplestudio.rs/060620121945.jpg");
$file_format = $size['mime'];
$file_format will be represented as for example "image/jpeg" so you can easily check for image types like this:
foreach($allowedExts as $allowed) {
$chk_types = strpos($file_format, $allowed);
if($chk_types > -1) {
$type_is_good = true;
break;
}
}
Use : move_uploaded_file, See, Manual
And one more thing,
the $_FILES["file"]["type"] variable is not good to use as this can be changed by the browser settings.
Use getimagesize instead, See, Manual
$ratio2) { $thumb_w=$new_w;
$thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h;
$thumb_w=$old_x/$ratio2; }
$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(!strcmp("png",$ext)) imagepng($dst_img,$filename); else imagejpeg($dst_img,$filename);
imagegif($dst_img,$filename);
imagedestroy($dst_img); imagedestroy($src_img); } } if(!function_exists('getExtension')) { function
getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext; } }
$image=$_FILES["$imagename"]['name']; if($image) {
$filename = stripslashes($_FILES["$imagename"]['name']);
$extension = getExtension($filename); $extension =
strtolower($extension); if (($extension != "jpg") && ($extension
!= "jpeg") && ($extension != "png") && ($extension != "gif") &&
($extension != "bmp")) {
$obj->set_flash("Unknown extension...!"); header("Location: $filename "); exit; } else {
$size=getimagesize($_FILES["$imagename"]['tmp_name']);
$sizekb=filesize($_FILES["$imagename"]['tmp_name']);
if ($sizekb > MAX_SIZE*1024)
{
$obj->set_flash("You have exceeded the size limit...!");
header("Location: $filename");
exit;
}
$select_max = $obj->sql_query("select max($fieldname) as MaxID from ".$tablename."");
if($action=="Add") {
$Max = $select_max[0]['MaxID'];
$image_name = $Max + 1;
$new_name = $image_name.".".$extension;//the new name will be containing the full path where will be stored (images folder)
$$imagename = $new_name;//New Name of Image same as Image Field Name
$thumbfilename = $new_name;
$newname="$uploadpath/large/".$new_name;
$copied = copy($_FILES["$imagename"]['tmp_name'], $newname);
//we verify if the image has been uploaded, and print error instead
if (!$copied)
{
$obj->set_flash("Copy unsuccessfull...!");
header("Location: $filename");
exit;
}
else
{
$thumb_name="$uploadpath/thumb/".$thumbfilename;
$thumb=make_thumb($newname,$thumb_name,$WIDTH,$HEIGHT);
} } if($action=="Update") {
$new_name=$ID.".".$extension;
$$imagename = $new_name;//New Name of Image same as Image Field Name
$newname = "$uploadpath/large/".$new_name;
$thumbfilename = $new_name;
$copied = copy($_FILES["$imagename"]['tmp_name'], $newname);
if (!$copied)
{
$obj->set_flash("Copy unsuccessfull...!");
header("Location: $filename");
exit;
}
else
{
$thumb_name="$uploadpath/thumb/".$thumbfilename;
$thumb=make_thumb($newname,$thumb_name,$WIDTH,$HEIGHT);
} } } } if($action=="Delete") { $SelectImage = $obj->sql_query("select $imagename from $tablename where $fieldname
= ".$$fieldname." "); $ThisImage = $SelectImage[0]["$imagename"]; unlink("$uploadpath/thumb/".$ThisImage);
unlink("$uploadpath/large/".$ThisImage); } ?>
List item
<?php
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
$file_type = $_FILES['file']['type'];
/* variable array for store errors */
$errors = [];
/* Check if file already exists in location file save */
$file_dir = "uploads";
/** if folder not exists, then create it **/
if (!file_exists($file_dir)) {
mkdir($file_dir, 0777, true);
}
$file_target = $file_dir . $file_name;
if (file_exists($file_target)) {
//$errors[] = "Sorry, <strong>{$file_name}</strong> already exists.";
}
/* Check file size */
if ($file_size > 2500000) {
$errors[] = "Sorry, <strong>{$file_name}</strong> is too large. It size is {$file_size} > 2500000 bytes";
}
/* Check current file formats with file secure */
$file_secure = array('jpg', 'jpeg', 'png', 'gif');
$file_current = strtolower(pathinfo($file_name, PATHINFO_EXTENSION)); /* (end(explode('.', $file_name) */
if (in_array($file_current, $file_secure) === false) {
$errors[] = "Sorry, <strong>{$file_current}</strong> extension not allowed";
}
/* Check if Errors exist, then not upload. Or if Errors NOT exist, then try upload */
if (!empty($errors)) {
/* display error */
foreach ($errors as $keyError => $valueError) {
echo "$keyError = $valueError <br />";
}
echo "<br />";
echo "<strong>{$file_name}</strong> could not uploaded. <hr />";
} else {
if (move_uploaded_file($file_tmp, $file_target)) {
echo "Upload: " . $file_name . "<br />";
echo "Type: " . $file_type . "<br />";
echo "Size: " . ($file_size / 1024) . " Kb<br />";
echo "Stored in: " . $file_tmp;
} else {
echo "Invalid file";
}
}
?>

Categories