Unlink function script is not working in php - php

I Want to use this code update image working fine but. I have need add unlink function this code so please help me ... where add code unlink function. I am using PHP 7.2 and database
Note: the Previous File Delete in a file after update new file
show error=>Warning: unlink(image/Banner-70399.jpg): No such file or
directory in D:\xammp\htdocs\trustandmeet\admin\update-imagebanner.php
on line 43
line number 43 is here =>unlink("image/$image");
<?php
if (isset($_POST['submit'])) {
$sql1 = "SELECT * FROM banner WHERE banner_id='$banner_id'";
$result1 = mysqli_query($conn, $sql1);
mysqli_num_rows($result1) > 0;
$row1 = mysqli_fetch_assoc($result1);
$fileinfo = #getimagesize($_FILES["image"]["tmp_name"]);
$width = $fileinfo[0];
$height = $fileinfo[1];
if (!empty($_FILES['image']['name'])) {
$extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$image = "Banner" . '-' . rand(10000, 99999) . '.' . $extension;
}
if ($_FILES["image"]["size"] > 2000000) {
$response = array(
"type" => "error",
($_SESSION['msg1'] = "Image size exceeds 2MB"),
);
} elseif ($width < "900" || $height < "250") {
$response = array(
"type" => "error",
($_SESSION['msg2'] = "the image should be used greater than 900 X 250 "),
);
} else {
$location = "image/banner/" . $image;
unlink("image/$image");
if (in_array(strtolower($extension), ['png', 'jpeg', 'jpg'])) {
compressImage($_FILES['image']['tmp_name'], $location, 60);
} else {
$image = $row1['image'];
}
$sql = mysqli_query(
$conn,
"update banner set Image='$image' where banner_id='$banner_id' "
);
$_SESSION['msg'] = "Successfully Banner Image Updated Successfully !!";
}
}
?>

It looks like you are trying to remove an image that ia in the banner directory but your unlink command does not include that directory. Instead of:
$location = "image/banner/".$image;
unlink("image/$image");
Use:
unlink($location);

Related

Flutter: Scanned 'Path' On Null

I'm trying to upload an image taken using the image picker package to my localhost server using a PHP API.
When the picture is taken, a message in the debug console appears saying "scanned (some path) to null" and the image path isn't saved.
I'd be very grateful if anyone who knows anything about this fills me in on how I can fix it. thank you in advance!
Here's my Relevant code:
-(PHP Backend)inserting an image to the database:
include_once "../../api/patients/create_image.php";
if (
isset($_POST["id"])
) {
if (!empty($_FILES["file"]['name']) )
{
$image = uploadImage("file", '../images/', 200,600);
$img_image = $image["image"];
}
else{
$img_image = "";
}
$id = $_POST["id"];
$insertArray = array();
array_push($insertArray, htmlspecialchars(strip_tags($img_image)));
array_push($insertArray, htmlspecialchars(strip_tags($id)));
$sql = "insert into patient_images (image, file_id) values (?,?)";
$result = dbExec($sql, $insertArray);
$resJson = array("result" => "success", "code" => 200, "body" => $insertArray);
echo json_encode($resJson, JSON_UNESCAPED_UNICODE);
} else {
//bad request
$resJson = array("result" => "fail", "code" => "400");
echo json_encode($resJson, JSON_UNESCAPED_UNICODE);
}
unction uploadImage($inputName, $uploadDir , $thumbnail_width , $image_width)
{
$image = $_FILES[$inputName];
//echo "error " . $image['name'] . $image['tmp_name'] . "end;";
$imagePath = '';
$thumbnailPath = '';
// echo "before";
// if a file is given
if (trim($image['tmp_name']) != '') {
$ext = substr(strrchr($image['name'], "."), 1); //$extensions[$image['type']];
// generate a random new file name to avoid name conflict
$imagePath = md5(rand() * time()) . ".$ext";
list($width, $height, $type, $attr) = getimagesize($image['tmp_name']);
// make sure the image width does not exceed the
// maximum allowed width
if ($width > $image_width) {
// echo "after";
$result = createThumbnail($image['tmp_name'], $uploadDir . $imagePath, $image_width);
$imagePath = $result;
} else {
$result = move_uploaded_file($image['tmp_name'], $uploadDir . $imagePath);
}
if ($result) {
// create thumbnail
$thumbnailPath = md5(rand() * time()) . ".$ext";
$result = createThumbnail($uploadDir . $imagePath, $uploadDir . $thumbnailPath, $thumbnail_width);
// create thumbnail failed, delete the image
if (!$result) {
unlink($uploadDir . $imagePath);
$imagePath = $thumbnailPath = '';
} else {
$thumbnailPath = $result;
}
} else {
// the product cannot be upload / resized
$imagePath = $thumbnailPath = '';
}
}
return array('image' => $imagePath, 'thumbnail' => $thumbnailPath);
}
(Front-end):
Future<bool> uploadFile(File imageFile, String id) async {
var stream = http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
var uri = Uri.parse(path_api + 'patients/insertImage.php');
print(uri.path);
var request = http.MultipartRequest('POST', uri);
var multiPartFile = http.MultipartFile('file', stream, length,
filename: basename(imageFile.path));
request.fields['id'] = id;
request.files.add(multiPartFile);
var response = await request.send();
if (response.statusCode == 200) {
print('ok');
} else {
print('nope');
}
}
Future getImageCamera() async {
var image = await picker.pickImage(source: ImageSource.camera);
setState(
() {
if (image != null) {
_image = File(image.path);
} else {
print('no image selected');
}
},
);
}

Invalid image is uploaded to Amazon s3 of size in bytes

I want to upload image to my bucket, image is uploaded but it is uploaded in bytes(14 bytes).
When I downloaded the image using s3 browser it shows invalid image.
Below is my code snippet:
if ($s3->isBucketAvailable($bucketName)) {
$request = $this->getRequest();
$postFile = $request->getFiles ()->toArray ();
foreach ( $postFile as $key => $value ) {
if ($value ['name'] !== "") {
$randString = Rand::getString ( rand ( 18, 20 ), 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', true );
$microTime = microtime ( true ) * 10000;
$ext = pathinfo($value ["name"], PATHINFO_EXTENSION);
$id = 'postImg_' . $randString . $microTime . '.'.$ext;
$filename = date("Ymd").'/'. $id;
$filename = $bucketName.'/'.$filename;
if($s3->putObject($filename, $value['tmp_name'], $s3::S3_ACL_PRIVATE)) {
echo "Image posted";
} else {
echo "error";
}
}
}
}
In place of $value['tmp_name'] I also tried image url but it is also showing the same issue.

I can't upload multiple images using PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP - Upload multiple images
I want to upload multiple images using PHP and I am stuck. I have the code but it uploads only 1 image.
<?php
if (isset($_POST['newuser'])) {
if ((!empty($_POST['year'])) AND (!empty($_POST['make'])) AND (!empty($_POST['model'])) AND (!empty($_POST['engine'])) AND (!empty($_POST['mileage'])) AND (!empty($_POST['exterior'])) AND (!empty($_POST['interior'])) AND (!empty($_POST['transmission'])) AND (!empty($_POST['body'])) AND (!empty($_POST['fuel'])) AND (!empty($_POST['drive'])) AND (!empty($_POST['doors'])) AND (!empty($_POST['description']))) {
$year = htmlspecialchars($_POST['year']);
$make = htmlspecialchars($_POST['make']);
$model = htmlspecialchars($_POST['model']);
$engine = htmlspecialchars($_POST['engine']);
$mileage = htmlspecialchars($_POST['mileage']);
$exterior = htmlspecialchars($_POST['exterior']);
$interior = htmlspecialchars($_POST['interior']);
$transmission = htmlspecialchars($_POST['transmission']);
$body = htmlspecialchars($_POST['body']);
$fuel = htmlspecialchars($_POST['fuel']);
$drive = htmlspecialchars($_POST['drive']);
$doors = htmlspecialchars($_POST['doors']);
$description = htmlspecialchars($_POST['description']);
$target = "images/default.jpg";
$msg = "";
if (!empty($_FILES['fisier']['name'])) {
$target = "images/";
$target = $target . basename($_FILES['fisier']['name']);
$file_size = $_FILES['fisier']['size'];
$file_type = $_FILES['fisier']['type'];
$ok = 1;
if ($file_size > 2048000) {
echo "Too large";
$ok = 0;
}
if ($file_type == "application/octet-stream") {
echo "no PHP";
$ok = 0;
}
if ($ok == 0) {
echo "No file saved";
} else {
if (!move_uploaded_file($_FILES['fisier']['tmp_name'],$target)) {
$target = "images/default.jpg";
$msg = "No file saved. ";
}
}
}
require_once("mysql_connect.php");
$sql = "INSERT INTO astonmartin VALUES('','$year','$make','$model','$engine','$mileage','$exterior','$interior','$transmission','$body','$fuel','$drive','$doors','$description','$target','$target2','$target3','$target4','$target5','$target6')";
mysql_query($sql) or die(mysql_error());
$msg .= "";
header("Location: add_user.php?msg=$msg");
} else {
$error = "Complete form";
}
}
?>
I think you need first this function assoc, here: multidimensional for loops in php
And continue;
<?php
$allowed_types = array(
'image/gif',
'image/jpeg',
// add your mime types more
);
if (isset($_POST['newuser'])) {
if ((!empty($_POST['year'])) AND ...
// that gives an associative array
// i think it's more handy in your case
$files = assoc($_FILES['fisier']);
// now you have a files like
// tmp_name => d:\tmp\abs123, name => cats.jpg, size => 128 ..
// tmp_name => d:\tmp\abs254, name => dogs.jpg, size => 211 ..
// ... more code here
// and here, remove this line
if (!empty($_FILES['fisier']['name'])) {
// put this. yes 6, cos you want 6 pics
if (count($files) == 6) {
// loop over files
foreach ($files as $i => $file) {
// create targets, securely
$targets[$i] =
'images/'. preg_replace('~[^\w\d\.]~i', '',
basename($file['name']));
// check some errors
if ($file['error'] == 0 && $file['size'] < 2048000
// check file type
&& in_array($file['type'], $allowed_types)) {
if (!move_uploaded_file(
$file['tmp_name'], 'images/'. $file['name'])) {
$targets[$i] = 'images/default.jpg';
// collect messages
$messages[] = $file['name'] . ' not saved!';
}
}
}
}
// and creating target 1 2 3 ...
$targets_string = '';
if (!empty($targets)) {
// this provides: '$target', '$target2', '$target3' ...
$targets_string = "'". join("', '", $targets) ."'";
}
// ... more code here
// and sql part
$sql = "INSERT INTO astonmartin VALUES('', '$year', '$make', ..."
// add target string
. "'$description', $targets_string";
// ... more code here
// msg part
$msg = empty($messages) ? '' : join('', $messages);
header("Location: add_user.php?msg=$msg");
?>

Issues with PHP image upload

I've been creating a HTML5 Drag & Drop image up-loader. All is good with the Javascript side of things however the PHP is driving me crazy!
I've been able to create a script that successfully places a image in a folder upon the drop of an image, however once it tries to create a thumb nail for the image and place the image link into the users db table it all goes to pot. I've sat here for hours on end, trying and trying to no avail, so i believe as it is now just about 3am GMT i should admit defeat and ask for a little help.
The JavaScript:
$(function(){
var dropbox = $('#dropbox'),
message = $('.message', dropbox);
dropbox.filedrop({
paramname:'pic',
maxfiles: 5,
maxfilesize: 200,
url: 'uploadCore.php',
uploadFinished:function(i,file,response){
$.data(file).addClass('done');
},
error: function(err, file) {
switch(err) {
case 'BrowserNotSupported':
showMessage('Your browser does not support HTML5 file uploads!');
break;
case 'TooManyFiles':
alert('Too many files!');
break;
case 'FileTooLarge':
alert(file.name+' is too large! Please upload files up to 200mb.');
break;
default:
break;
}
},
beforeEach: function(file){
if(!file.type.match(/^image\//)){
alert('Only images are allowed!');
return false;
}
},
uploadStarted:function(i, file, len){
createImage(file);
},
progressUpdated: function(i, file, progress) {
$.data(file).find('.progress').width(progress);
}
});
var template = '<div class="preview">'+
'<span class="imageHolder">'+
'<img />'+
'<span class="uploaded"></span>'+
'</span>'+
'<div class="progressHolder">'+
'<div class="progress"></div>'+
'</div>'+
'</div>';
function createImage(file){
var preview = $(template),
image = $('img', preview);
var reader = new FileReader();
image.width = 100;
image.height = 100;
reader.onload = function(e){
image.attr('src',e.target.result);
};
reader.readAsDataURL(file);
message.hide();
preview.appendTo(dropbox);
$.data(file,preview);
}
function showMessage(msg){
message.html(msg);
}
});
Now for the PHP:
<?php
// db connection
include("db-info.php");
$link = mysql_connect($server, $user, $pass);
if(!mysql_select_db($database)) die(mysql_error());
include("loadsettings.inc.php");
//$upload_dir = 'pictures/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
if (isset($_SESSION["imagehost-user"]))
{
$session = true;
$username = $_SESSION["imagehost-user"];
$password = $_SESSION["imagehost-pass"];
$q = "SELECT id FROM `members` WHERE (username = '$username') and (password = '$password')";
if(!($result_set = mysql_query($q))) die(mysql_error());
$number = mysql_num_rows($result_set);
if (!$number) {
session_destroy();
$session = false;
}else {
$row = mysql_fetch_row($result_set);
$loggedId = $row[0];
}
}
$date = date("d-m-y");
$lastaccess = date("y-m-d");
$ip = $_SERVER['REMOTE_ADDR'];
$type = "public";
$pic = $_FILES['pic'];
$n = $pic;
$rndName = md5($n . date("d-m-y") . time()) . "." . get_extension($pic['name']);
$upload_dir = "pictures/" . $rndName;
move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name']);
// issues starts here
$imagePath = $upload_dir;
$img = imagecreatefromunknown($imagePath);
$mainWidth = imagesx($img);
$mainHeight = imagesy($img);
$a = ($mainWidth >= $mainHeight) ? $mainWidth : $mainHeight;
$div = $a / 150;
$thumbWidth = intval($mainWidth / $div);
$thumbHeight = intval($mainHeight / $div);
$myThumb = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($myThumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $mainWidth, $mainHeight);
$thumbPath = "thumbnails/" . basename($imagePath);
imagejpeg($myThumb, $thumbPath);
$details = intval(filesize($imagePath) / 1024) . " kb (" . $mainWidth . " x " . $mainHeight . ")" ;
$id = md5($thumbPath . date("d-m-y") . time());
$q = "INSERT INTO `images`(id, userid, image, thumb, tags, details, date, access, type, ip)
VALUES('$id', '$loggedId', '$imagePath', '$thumbPath', '$tags', '$details', '$date', '$lastaccess', 'member-{$type}', '$ip')";
if(!($result_set = mysql_query($q))) die(mysql_error());*/
exit_status('File was uploaded successfuly!');
// to here
$result = mysql_query("SELECT id FROM `blockedip` WHERE ip = '$ip'");
$number = mysql_num_rows($result);
if ($number) die(""); // blocked IP message
function imagecreatefromunknown($path) {
$exten = get_extension($path);
switch ($exten) {
case "jpg":
$img = imagecreatefromjpeg($path);
break;
case "gif":
$img = imagecreatefromgif($path);
break;
case "png":
$img = imagecreatefrompng($path);
break;
}
return $img;
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
It seems you pass wrong path to the imagecreatefromunknown() function. You pass $imagePath that equals $upload_dir, but your image destination is $upload_dir.$pic['name']

Extend variable from one function to another

I'm having an image upload function I did create for few weeks ago - it has an variable called $newname, which contains the path and file.
I'm then using the imageupload() function in another function called EditFrontPage(), which is used to 'update' some content.
If I update the image, it runs the imageupload function, which is great, it resize and optimize the image, and it moves it to the folder I specified.
What I then want, is within' my EditFrontPage() function, is to echo out the $newname variable from the imageUpload function.
is there a way to do this? in a smart way? :D
Here is my code:
<?php
function EditFrontPage($db)
{
$stmt = $db->prepare("SELECT `id`, `heading`, `content`, `image` FROM `content` WHERE `page` = 'forside';");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(isset($_POST['EditFrontpageSubmit']))
{
imageUpload(10000, 100, 100, '', 5);
global $newname;
echo $newname;
}
?>
<form class="adminForm" enctype="multipart/form-data" action="" method="post">
<h2>Overskrift</h2>
<input type="text" value="<?=$row['heading']?>" />
<input type="file" name="image[]" />
<h2>Tekst</h2>
<textarea><?=br2nl($row['content'])?></textarea>
<input type="submit" name="EditFrontpageSubmit" value="Opdater nyhed" />
</form>
<?php
}
function imageUpload($maxsize = 2000, $quality = 95, $imgwidth = 400, $imgheight = '', $numOfImages = 5, $path = '/lucas/images/')
{
// Turn on error reporting
error_reporting(-1);
//Set the max upload size in kilobytes
define("MAX_SIZE", "$maxsize");
if(empty($imgheight) && empty($imgwidth))
{
echo "<h1>Fejl: Definer bredde eller højde</h1>";
die();
}
//Makes a function that check the extension
function getExtension($str){
$i = strrpos($str, ".");
if(!$i){return "";}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//Set errors to 0 from standard
$errors = 0;
//Define the size as a variable
$size = '';
//foreach image selected
foreach($_FILES['image']['error'] as $key => $error)
{
//If no errors, return true
if($error == UPLOAD_ERR_OK)
{
//Gets the filename
$filename = stripslashes($_FILES['image']['name'][$key]);
//Gets the extension
$extension = getExtension($filename);
//convert the extension to lowercase
$extension = strtolower($extension);
//if the file extension doesn't match, return error
if(($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
echo "<h1>Unknown Extension!</h1>";
$errors = 1;
}
//This check if the amount of images is over 5.
elseif(count($_FILES['image']['name']) > $numOfImages)
{
//If it's over 5 images, return error and exit
echo "Too many images";
exit();
}
else
{
//Get the filesize of the image (total amount if multiple images).
$size += filesize($_FILES['image']['tmp_name'][$key]);
//if the filesize is over the defined amount
if($size > MAX_SIZE*1024)
{
echo "<h1>Du har overskredet maksimum fil-upload størrelse!</h1>";
$errors = 1;
}
//This renames the image, to contain, the microtime, and a unique ID + extension
$image_name = microtime(true) . uniqid('',true) . '.' . $extension;
//This sets the path of the image.
$newname = $_SERVER['DOCUMENT_ROOT'] . $path . $image_name;
//It moves the file(s) to the path defined above!
$copied = move_uploaded_file($_FILES['image']['tmp_name'][$key], $newname);
//Check if the extension is png
//if($extension == "png")
//{
//converts the quality from 'jpeg/gif' quality to png compression method
//$pngquality = round($quality/100 * 9);
//Executes a shell command optimizing the png
//shell_exec("gm mogrify -quality $pngquality -thumbnail ". $imgwidth ."x". $imgheight ."\> $newname $newname");
//}
//else
//Executes a shell command optimizing the jpeg/gif
//shell_exec("gm mogrify -quality $quality -thumbnail ". $imgwidth ."x". $imgheight ."\> $newname $newname");
//If the image isn't copied, return an error
if(!$copied)
{
echo "<h1>Der skete en fejl!</h1>";
$errors = 1;
}
//Creates an array of the images
$array[] = $newname;
}
}
}
//If the submit is set, and errors = 0 return true
if(isset($_POST['Submit']) && $errors != 1)
{
echo "<h1>Fil blev uploaded som den skulle!</h1>";
//Makes a for loop, that echo's out all uploaded images
for($i = 0; $i < count($array); $i++)
{
echo "<img src='{$array[$i]}' /><p>".preg_replace("/.*\//i", '', $array[$i])."</p>";
}
}
}
?>
Thank you a lot guys!
Have the imageupload() function return the $newname variable, and then set it like so on the EditFrontPage() function:
$newName = imageUpload(10000, 100, 100, '', 5);
just return $newname at the end of imageUpload function and modify this part:
if(isset($_POST['EditFrontpageSubmit']))
{
echo imageUpload(10000, 100, 100, '', 5);
}

Categories