Delete Function
function delete_news($id,$img)
{
$sql = $this->con->prepare("DELETE FROM `nm_news` WHERE news_id=:id");
$sql->bindParam(':id', $id);
$sql->execute();
unlink("uploads/".$img);
header('Location: all_news.php');
$this->con = null;
}
Here I am able to delete all image like jpeg and png but unable to delete jpg
Inserting Image function
function update_category($id, $category_title, $sort_order, $status)
{
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
}
$image = basename($_FILES["imageUpload"]["name"], ".jpg");
if ($image) {
$sql = $this->con->prepare("UPDATE nm_category SET category_title=:category_title,category_image=:category_image,category_order=:category_order,category_status=:category_status WHERE category_id=:id");
$sql->bindParam(':category_title', $category_title);
$sql->bindParam(':category_image', $image);
$sql->bindParam(':category_order', $sort_order);
$sql->bindParam(':category_status', $status);
$sql->bindParam(':id', $id);
}
}
Insertion of image is working fine, but unlink on jpg is not working only working on jpeg and png
Result o/p: after pressing delete button, the whole data gets deleted but the image still remains in the folder of uploads
Change $image = basename($_FILES["imageUpload"]["name"], ".jpg"); to $image = basename($_FILES["imageUpload"]["name"]);
This was only storing the complete filename including extension for .jpeg and .png files. When you uploaded a .jpg file you stored the file in your uploads/ folder including the extension but saving to database without the extension.
So for example myJpgFile.jpg exists in your uploads/ folder, but you were trying to unlink myJpgFile from your uploads/ folder - which doesn't exist.
Related
I am uploading file into folder using PHP but my issue is its at a time writing file into 2 different path. My code is below.
if(array_key_exists('pimage',$_FILES)){
$tempFile = $_FILES['pimage']['tmp_name'];
$fileName = $_FILES['pimage']['name'];
$fileName = str_replace(" ", "-", $_FILES['pimage']['name']);
$fig = rand(1, 999999);
$saveFile = $fig . '_' . $fileName;
$uploadOk = 1;
if (exif_imagetype($_FILES['pimage']['tmp_name']) == IMAGETYPE_GIF) {
$ext=pathinfo($saveFile, PATHINFO_FILENAME);
$saveFile=$ext.'.png';
$png = imagepng(imagecreatefromgif($_FILES['pimage']['tmp_name']), $saveFile);
}
if (exif_imagetype($_FILES['pimage']['tmp_name']) == IMAGETYPE_JPEG) {
$ext=pathinfo($saveFile, PATHINFO_FILENAME);
$saveFile=$ext.'.png';
$png = imagepng(imagecreatefromjpeg($_FILES['pimage']['tmp_name']), $saveFile);
}
if (strpos($fileName,'php') !== false) {
# code...
}else{
$targetPath = PT_USERS_IMAGES_UPLOAD;
$targetFile = $targetPath . $saveFile;
if (file_exists($targetFile)) {
$data=array("msg"=>'profile image already exists');
$uploadOk = 0;
}
if ($_FILES["pimage"]["size"] > 2000000 || $_FILES["pimage"]["size"] == 0) {
$uploadOk = 0;
$data=array("msg" => "profile image should not greater than 2 MB.");
}
//echo $uploadOk;exit;
if ($uploadOk==0) {
$flag=0;
$data[]=array("msg" => $data['msg']);
}else{
$moved =move_uploaded_file($tempFile, $targetFile);
if ($moved) {
$filename = $saveFile;
$data = array('ai_image' => $filename);
$this->db->where('accounts_id', $dataArr['user_id']);
$this->db->update('pt_operator_accounts', $data);
}else{
$flag=0;
$data[]=array("msg" => "Not uploaded because of error #".$_FILES["pimage"]["error"]);
}
// print_r($data);exit;
}
}
}
Here I need to write file into PT_USERS_IMAGES_UPLOAD path but before uploading into this path also the file is uploading into project's root path. Here I need to upload only in PT_USERS_IMAGES_UPLOAD path not in project's root path.
It is likely because of these lines:
imagepng(imagecreatefromgif($_FILES['pimage']['tmp_name']), $saveFile);
If you look at the documentation regarding this imagepng(), it will either output an image to the browser (with a proper header) or save the file to disk when you fill out the second parameter, in your case you have used the to parameter ($saveFile). So, once you save it there, you then save it again using the move_uploaded_file($tempFile, $targetFile); which is the one saving it to the proper location.
If you are trying to convert something to PNG, then just do the imagepng() line and remove the move_uploaded_file() line. Change $saveFile to T_USERS_IMAGES_UPLOAD and then you should only get one saved file. Either way, remove one of those methods for saving the file to disk.
I am trying to upload an image with a random name, also when I update the image, I want the previous image to be deleted.
Code below:
$banner=$_FILES ['banner']['name'];
$upload="../image/banner/";
$target_file = $upload.basename($_FILES["banner"]["name"]);
$imagefiletype= pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES["banner"]["tmp_name"], $target_file );
Any help will be appreciated.
When update your new images at that time first store old image name in variable. after update true then delete old image in your directory using "unlink" function.
$old_image = "xyz" // store old image name
after update query success
unlink('../image/banner/'.$old_image); // delete old image in your directory
You can do it like this.
$path = 'image/folder/'; $unique_name=time().uniqid(rand());
$File_with_location = $path . $unique_name . '.' . strtolower(pathinfo($_FILES['img']['name'], PATHINFO_EXTENSION));
$filename = $_FILES["img"]["tmp_name"];
move_uploaded_file($filename, $File_with_location);
for deleting old image you can use this
$path = './root/home/folder/file.jpg';
if (unlink($path)) {
echo 'success';
} else {
echo 'fail';
}
I try using function to upload different kind of file by giving it variables. As shown below:
<?
function fn_fileUpload($data,$dir,$uid){
include_once($_SERVER['DOCUMENT_ROOT']."/cgi-bin/connect.php");
if(isset($data) && $data['error'] === UPLOAD_ERR_OK){
$fileTmpPath = $data['tmp_name'];
$fileName = $data['name'];
$fileSize = $data['size'];
$fileType = $data['type'];
$fileNameCmps = explode(".", $fileName);
$fileExt = strtolower(end($fileNameCmps));
$newFileName = $uid . '.' . $fileExt;
//check file ext
$okEXT = array('jpg', 'jpeg', 'png','doc','docx','pdf');
if (in_array($fileExt, $okEXT)) {
$fileDir = '/'.$dir.'/';
$dest_path = $fileDir.$newFileName;
if(move_uploaded_file($fileTmpPath, $dest_path)){
try{
$stmt2=$mysqli->prepare("insert into job_file (jfile_id, job_id, jfile_name, jfile_size, jfile_type, jfile_ext) valies(?,?,?,?,?,?)");
$stmt2->bind_param('iisiss',$zero,$uid,$newFileName,$fileSize,$fileType,$fileExt);
$stmt2->execute();
$result = 'ok';
}catch(mysqli_sql_exception $err){
$result=$err;
}
}else{
$result = 'Cannot upload file!';
}
}//in_array
}//if(isset
return $result;
}
?>
And this is how to use:
//upload file
$job_file=fn_fileUpload($_FILES['job_file'],'uploads',$_POST['passport_id']);
//upload photo
$job_img=fn_fileUpload($_FILES['job_img'],'photos',$_POST['passport_id']);
From here, the function always return : Cannot upload file!. At first I think. It might have something to do with move_uploaded_file but the file was there in /uploads directory but not with /photos. Both directories CHMOD 755 (tried 777 but no luck).
The db went through correctly. Is there any idea how to fix this?
You can only use move_uploaded_file() ONCE on a temporary file that has been uploaded through a form. This function destroys the temporary file after it has been moved, so the for the first upload in the uploads directory you can do it well but in for the second one no.
I am trying to upload images onto server.
On the Server the folder name:{photo}
I check the permissions on the folder and it currently on 0755.
When I run my php code, I get this error code:
"Error uploading file - check destination is writeable."
The post that was similar to my issues is this: How to upload photo to my hosting server folder directory
but I already have these functions in my code:
Here my php code:
<?php
$filetmp = $_FILES["file_img"]["tmp_name"];
$filename = $_FILES["file_img"]["name"];
$filetype = $_FILES["file_img"]["type"];
$filesize = $_FILES["file_img"]["size"];
$fileinfo = getimagesize($_FILES["file_img"]["tmp_name"]);
$filewidth = $fileinfo[0];
$fileheight = $fileinfo[1];
$filepath = "../photo/".$filename;
$filepath_thumb = "../photo/thumb/".$filename;
if($_POST['btn_upload'])
{
$sPhotoFileName = $filename;
$nPhotoSize = $filesize;
$sTempFileName = $filetmp;
chmod($filepath_thumb,0755);
chmod($filepath,0755);
if(file_exists('photo/' . $_FILES['file_img']['name'])){
die('File with that name already exists.');
}else{
if ($sPhotoFileName) // file uploaded
{ $aFileNameParts = explode(".", $sPhotoFileName);
$sFileExtension = end($aFileNameParts); // part behind last dot
if ($sFileExtension != "jpg"
&& $sFileExtension != "png"
&& $sFileExtension != "gif")
{ die ("Choose a JPG for the photo");
}
}
if($_FILES['file_img']['error'] > 0){
die('An error ocurred when uploading.');
}
if ($nPhotoSize == 0)
{ die ("Sorry. The upload of $sPhotoFileName has failed.
Search a photo smaller than 300K, using the button.");
}
if ($nPhotoSize > 30240000000)
{ die ("Sorry.
The file $sPhotoFileName is larger than 300K.
Advice: reduce the photo using a drawing tool.");
}
// read photo
$oTempFile = fopen($sTempFileName, "r");
$sBinaryPhoto = fread($oTempFile, fileSize($sTempFileName));
// Try to read image
$nOldErrorReporting = error_reporting(E_ALL & ~(E_WARNING)); // ingore warnings
$oSourceImage = imagecreatefromstring($sBinaryPhoto); // try to create image
error_reporting($nOldErrorReporting);
if (!$oSourceImage) // error, image is not a valid jpg
{ die ("Sorry.
It was not possible to read photo $sPhotoFileName.
Choose another photo in JPG format.");
}
}
$nWidth = imagesx($oSourceImage); // get original source image width
$nHeight = imagesy($oSourceImage); // and height
// create small thumbnail
$nDestinationWidth = 80;
$nDestinationHeight = 60;
//$oDestinationImage = imagecreatetruecolor($nDestinationWidth, $nDestinationHeight);
$oDestinationImage = imagecreate($nDestinationWidth, $nDestinationHeight);
/*$oResult = imagecopyresampled(
$oDestinationImage, $oSourceImage,
0, 0, 0, 0,
$nDestinationWidth, $nDestinationHeight,
$nWidth, $nHeight); // resize the image
*/
imagecopyresized($oDestinationImage, $oSourceImage,0, 0, 0, 0,$nDestinationWidth, $nDestinationHeight,$nWidth, $nHeight); // resize the image
ob_start(); // Start capturing stdout.
imageJPEG($oDestinationImage); // As though output to browser.
$sBinaryThumbnail = ob_get_contents(); // the raw jpeg image data.
ob_end_clean(); // Dump the stdout so it does not screw other output.
// attempt insert query execution
$sql = "INSERT INTO UploadImg (img_name, img_path, img_type) VALUES ('$sPhotoFileName', '$filepath', '$filetype')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
if(!move_uploaded_file($_FILES["file_img"]["tmp_name"],"../photo/".$_FILES["file_img"]["name"])){
die('Error uploading file - check destination is writeable.');
echo "Error Code: " .$_FILES["file_img"]["name"] . "<br>";
}else{
$sBinaryThumbnail = addslashes($sBinaryThumbnail);
$oDatabase = $link;
mysqli_select_db("upload", $oDatabase);
$sQuery = "insert into Uploadimg (thumbnail) VALUES ('$sBinaryThumbnail')";
echo $sQuery;
mysqli_query($sQuery, $oDatabase);
die('File uploaded successfully.');
mysqli_close($link);
}
}
?>
Now I read an article say that even if your folder permission setup up to do all three read, write, and executed on all three level. the code still will not be able to read it depending on the settings on the server.
So I am confused and looking for clarification. Please assist me?
You can upload the image by binary data encoded and save the file with the image format on the server.
755 means it is not world writable. You can set it writable and executable with 777.
This is still vulnerable as anyone with access to your server os can write to the folder, so you should probably just make the web server user the owner of the folder and keep the permissions as they are now. If you're running apache, the user is usually www-data or apache.
I figure it out you gotta set the GID and UID permissionsfilepermission
The set group identification GID allows the owner to execute all applications to read, write and pull to the folder.
Same thing with the User identification UID. the problem is the your folder will be wide open for strangers to manipulate it but it works.
My images are uploading into the folder. Tell me what yall think?
First in your php.ini put
file_uploads = On
Next, create an HTML form that allow users to choose the image file they want to upload:
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
Make sure that the form uses method="post"
Then use the php code below to upload image
<?php
$target_dir = "uploads/";
$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;
}
}
?>
i have a problem with uploading images into different directory.
$path = "../uploads/";
$path2 = "../uploads2/";
$imagename = $_FILES['photoimg']['name'];
$actual_image_name = $imagename;
$uploadedfile = $_FILES['photoimg']['tmp_name'];
$widthArray = array(600,240); //resize width.
foreach($widthArray as $newwidth)
{
$filename = $uploadedfile,$path,$actual_image_name,$newwidth;
//Original Image
if(move_uploaded_file($uploadedfile, $path.$actual_image_name))
{}
if(move_uploaded_file($uploadedfile, $path2.$actual_image_name))
{}
i want to upload image into uploads and uploads2 folders also?
for example width width = 600px into uploads, width = 240px into folder upload2.
what's wrong with my code?
After moving the file with move_uploaded_file it isn't available in the location stored in $uploadedfile anymore. For the second file you have to use copy function.
Please try the following:
if(move_uploaded_file($uploadedfile, $path.$actual_image_name))
{}
if(copy($path.$actual_image_name, $path2.$actual_image_name))
{}
Remove this line. I don't know for what purpose it's there.
$filename = $uploadedfile,$path,$actual_image_name,$newwidth;
To resize the uploaded image use any library to resize it then pass it.
But here is the full code to upload in different directory. But you will have to resize these two $file1 & $file2 to your expected resize file and replace the same in $file1 & $file2
To resize you can use any code suggested here
$path1 = "../uploads/";
$path2 = "../uploads2/";
$file1= $_FILES['photoimg'];
$file2= $_FILES['photoimg'];
$file1_imagename = $file1['name'];
$file2_imagename = $file2['name'];
$file1_actual_image_name = $file1_imagename;
$file2_actual_image_name = $file2_imagename;
$file1_uploadedfile = $file1['tmp_name'];
$file2_uploadedfile = $file2['tmp_name'];
$widthArray = array(600, 240); //resize width.
if (move_uploaded_file($file1_uploadedfile, $path1 . $file1_actual_image_name)) {
echo "Uploaded Successfully!";
}
if (move_uploaded_file($file2_uploadedfile, $path2 . $file2_actual_image_name)) {
echo "Uploaded Successfully!";
}