Uploading Files (PDF & Image) With CakePHP - php

What I am trying to do I have never done before. I am using CakePHP to build a form, I am using the form helper to do this. This all works with inputs and textareas but I am now trying to changed two of my inputs into file upload fields.
This I have done and seems the work, when I debug $this->data['Event']['img'] (The form is call Event). I get the following output :
Array
(
[name] => logo.gif
[type] => image/gif
[tmp_name] => /tmp/phpaU3aBa
[error] => 0
[size] => 7318
)
Now I am guesting here but I would have to save the file to my 'webroot' folder. I have made the path /webroot/eventfiles/img & webroot/eventfiles/pdf - I have started with doing just the image for now, so I can get it to work, but the other file type I will be uploading is a pdf.
Now I have looked at what the CakePHP website as on this but I just says to look at the PHP site and there seems to be a lot of ways to do this, but I am just not sure how to save it. So that I can access it later, e.g. it goes into the webroot folder so that Cake can see it.
Also as a side note, would also need to save the path + filename into the database. This, unless I am wrong, should be easy, just use $this->data['Event']['img']['name'] and that would save that into my database.
Please help? I have been working on this for days. I just can not seem to get my head around file upload. Is there a easy method to do this? E.g like how Cake as HTML & Form helpers, a easy method for saving uploaded files?
Thanks For Any Help You Can Give.
Glenn.

just though that I would post my answer, which fully works. I takes a pdf and jpeg image, from two file input files and then renames then to the given title, supplied by the user in a input text field. With the two vars in $newevent, these are what, with the other inputs, are saved to the database, path and the renamed image.
This code is very simple. The main body of this code come from a post on this site and I have just changed it to use for my use.
If you are also trying to add/upload different file types, e.g. doc or png, all you need to know is the header type for the document you want to upload and add it to the if statement.
Hope this will help someone else!
Glenn.
$pathimg = "/eventfiles/img/";
$pathpdf = "/eventfiles/pdf/";
$dir_pdf = getcwd().$pathpdf;
$dir_img = getcwd().$pathimg;
$PDF_Path = $dir_pdf . $this->data['Event']['pdf']["name"];
$IMG_Path = $dir_img . $this->data['Event']['img']["name"];
$IMG_WithOutSpace = preg_replace('/\s+/', '_', $newevent['title']);
$PDF_WithOutSpace = preg_replace('/\s+/', '_', $newevent['title']);
$newevent['img'] = "/vh/eventfiles/img/" . $IMG_WithOutSpace . ".jpg";
$newevent['pdf'] = "/vh/eventfiles/pdf/" . $PDF_WithOutSpace . ".pdf";
if ((( $this->data['Event']['img']["type"] == "application/pdf") || ( $this->data['Event']['img']["type"] == "image/jpeg"))) {
if (($this->data['Event']['img']["error"] > 0) || ($this->data['Event']['pdf']["error"] > 0)) {
$this->Session->setFlash(__('An error has occured during updating. Please check all the fields.', true), 'default', array('class' => 'error-message'));
$this->redirect($this->referer());
exit();
} else {
move_uploaded_file( $this->data['Event']['img']["tmp_name"], $IMG_Path);
rename($IMG_Path, $dir_img . $IMG_WithOutSpace. ".jpg");
move_uploaded_file( $this->data['Event']['pdf']["tmp_name"], $PDF_Path);
rename($PDF_Path, $dir_pdf . $PDF_WithOutSpace . ".pdf");
$filename= $this->data['Event']['pdf']["name"];
$filename= $this->data['Event']['img']["name"];
}

Related

How to delete image in database also in source folder

Can any one help me how to delete the image inside the folder?
this my code for deleting the image inside the database and its working
<?php
require('connection/dbconn.php');
if(ISSET($_POST['id'])){
foreach ($_POST['id'] as $id){
$dbconn->query("delete from `uploading` where `id` = '$id'");
}
}
?>
For deleting file with PHP, you have to use unlink function.
But you have to also provide a filepath, which is in your case should consists from upload directory path and fileID (which is $_POST['id']?)
/**
* Do user permissions check for this operation before going further
*/
foreach ($_POST['id'] as $fileId) {
$filePath = "/path/to/upload/dir/$fileId";
if (file_exists($filePath)) {
unlink($filePath);
}
}
Don't forget to make security and data consistency checks. For example, that the user, that sent this request for deleting has enough rights for it.
To delete the image from server, you will have to pass theimageName variable to your PHP script, and then you can delete the file using built-in function unlink():
$path = //your path to the upload images
unlink( $path . $imageName);
unlink( $path . 'Thumbnails/' . $imageName); //if also have thumbnail
You are interacting with your server file system, you'll want to be sure and sanitize the variables (prevent someone from using ../../../ to get to unwanted parts of your file system).
$imageName= str_replace( array( '..', '/', '\\', ':' ), '', $imageName);
You should sanitize the variables to make sure you escape .. characters in the filename otherwise you could something like "../../../public/index.php
Update:
You would have to store the name of an image in the database and create a hidden field in your delete form. While deleting, get the image name as $image = $_POST['image']; and then follow the unlink process.
Select image name from db or send image name with id
Use unlink function to delete file image
unlink('/path-to-upload-dir/' . $_POST['imagename']);

Is that correct way that this code i using (remove file/unlink) in php

I want to ask you guys about my code in my php update form.
I use unlink($file_Path) to Remove my image file in my folder & my server and that work fine!
So I wonder when using "unlink($file_Path)" to removing an image, In my php page it show me an "Image File Icon " when there was no picture (The image file was removed) But it show me like that (Image file Icon) Because, I though It still has a some value (my value = "../filename.jpg")
so I put "value=" "/" (None Value to Reset a Value)
example :
<input type="hidden" name="newSubimage1" value=""/>
and that work fine when I use with "!empty($ro.."
example :
if (isset($row['subimage1']) && !empty($row['subimage1']))
{
echo "<img src='../images/images_products/".$row['subimage1']."'>";
} else {
echo "No Image Here"; }
`
to not show an "Image File Icon"
Is that a correct way ? that I used to Removing file / Not display an Image File Icon or you has any easy way or the best way that you want to suggest me.
thanks
$image_file_ext = array('jpg', 'png', 'bmp');
$file_ext = pathinfo($row['subimage1'],PATHINFO_EXTENSION);
if (isset($row['subimage1']) && !empty($row['subimage1']) && in_array($file_ext, $image_file_ext))
{
echo "<img src='../images/images_products/".$row['subimage1']."'>";
} else {
echo "No Image Here";
}

Can I add user ID to the file name in file upload?

I would like to add user ID to file name in file upload. I tried this:
$date=date("Y-m-d");
$id=mysql_insert_id();
//Abstract File codes
$info = pathinfo($_FILES['abstract']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = $id."_Abstract.".$ext;
$target = "application/abstracts/"; $target = $target .$newname;
if (empty($ext))
{ $abstract='' ;}
else $abstract=$newname;
But I only get 0 for ID.
I can display $name but $id is not working. Is it because I do not have an input for $id on my form? Thank you. I should also mention that the user is filling out an application form (for the first time) and attaching files on the same page. I had the file upload after the application was submitted I don;t think I would have problem call the $id. But since everything is on one page I might be calling an empty $id.

Trying to display images from a filesystem in php

Today i am looking for help. This is my first time asking so sorry in advance if I make a few mistakes
I am trying to code a small web application that will display images.Originally I used the blob format to store my images in a database, however from researching on here People suggest to use a file system. My issue is I cannot display an image. It could be a very small error or even a bad reference to a files location however I cannot make it work.
This is a small project that I hope to be able to improve on and hopefully create into a sort of photo gallery. I am running this application on a localhost.
I am having an issue with displaying images from a filesystem.
// index.php
<form action="process.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="submit" value="Upload" />
</form>
My form then leads to a process page where the request is dealt with.
<?php
// process.php
// connect to the database
include 'connection.php';
// take in some file data
$filename =$_FILES['image']['name'];
// get the file extension
$extension = strtolower(substr($filename, strpos($filename, '.')+1));
// if the file name is set
if(isset($filename)){
// set save destination
$saved ='images/';
// rename file
$filename = time().rand().".".$extension;
$tmp_name=$_FILES['image']['tmp_name'];
// move image to the desired folder
if(move_uploaded_file($tmp_name, $saved.$filename)){
echo "Success!";
// if success insert location into database
$insert="INSERT INTO stored (folder_name,file_name) VALUES('$saved', '$filename')";
// if the query is correct
if($result=mysqli_query($con,$insert)){
echo "DONE";
echo"</br>";
// attempt to print image
echo "<img src=getimage.php?file_name=$filename>";
}
}
}
else{
echo "Please select a photo!!";
}
?>
Now as you can see I have an < img > tag. To try and learn, I was trying to just display the recently uploaded image. To try and do this I created a getimage file.
<?php
//getimage.php
// set the page to display images
header("Content-Type: image/jpeg");
include "connection.php";
// get requested filename
$name = ($_GET['file_name']);
$query = "SELECT * FROM stored WHERE file_name=$name";
$image = mysqli_query($con,$query);
$row = mysqli_fetch_array($image,MYSQLI_ASSOC);
$img = $row['file_name'];
echo $img;
?>
My database structure is as follows:
database name = db_file.
table name = stored.
columns = folder_name, file_name
Again, this is just a small project so I know I will have to alter the database if I wish to create a larger more efficient application.
It seems you use the database lookup to get just the file name, but you already have the file name. Try adding the folder name, create a valid path.
change
$img = $row['file_name'];
to
$img = $row['folder_name'] . '/' . $row['file_name'];
check your <img>tag to see if the correct url is present. You may or may not need the '/', it depends on how you stored the folder name. You may need to add the domain name. There is just not enough information know what is needed.
Your <img> should look like this
<img href="http://www.yourdomain.com/folder name/file name">
in the end

White empty images after PHP upload and MySQL insertion

I have created a PHP and MySQL script which successfully uploads submitted images via PHP to a folder on my server, and then adds the filename with extension to my MySQL database.
With an FTP program I can see the submitted image inside the correct folder on my server with its correct file size. However, when I type the file path of the newly uploaded image (http://xxxxxx.com/images/image.jpg) into my browser, I get a blank page. Also when I try to import the image onto a website, nothing shows up.
However, when I re-download the image via the FTP program onto my computer, I can see that the image is TOTALLY OK. What am I missing?
Excerpts of my code are below:
<?php
// getting current post id and slug
$pid = $_POST['pid'];
$slug = $_POST['slug'];
//This is the directory where images will be saved
$target = '../company/'.$slug.'/images/';
$target = $target . basename( $_FILES['image']['name']);
//This gets all the other information from the form
$pic = ($_FILES['image']['name']);
$fileTmpLoc = ($_FILES["image"]["tmp_name"]);
$extract = explode(".", $pic);
$fileExt = end($extract);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
header("location: ../message.php?msg=ERROR: That image has no dimensions");
exit();
}
$rename = rand(100000000000,999999999999).".".$fileExt;
// check for correct filetype
if (!preg_match("/\.(gif|jpg|png)$/i", $pic) ) {
header("location: ../message.php?msg=ERROR: incorrect filetype");
exit();
}
include_once "../database-connect.php";
//Writes the information to the database
mysqli_query($dbconnection,"UPDATE companies SET picture='$rename' WHERE ID='$pid'") ;
//Writes the photo to the server
if(move_uploaded_file($fileTmpLoc, "../company/'.$slug.'/images/$rename"))
{
.... etc
What am I missing that it does not show up in the browser?
Maybe the path is not what you think it is when you try to link to the image or when you try to open it.
Note that this looks very wrong:
if(move_uploaded_file($fileTmpLoc, "../company/'.$slug.'/images/$rename"))
This will add two quotes and two dots to your path, so if $slug is some_company, the path will be:
/company/'.some_company.'/images/123456789.jpg
Perhaps you don't see or didn't notice that in your ftp program.
Also note that you have an sql injection problem, you should switch to prepared statements with bound variables.
Problem was indeed the URL output structure. Have changed it, like jeroen suggested:
if(move_uploaded_file($fileTmpLoc, "../images/$rename"))
Works fine now

Categories