Create profile picture uploader in zend framework - php

I have recently started working on zend framework. I want to upload a profile picture and rename & re-size it. Am using the code below. with this am able to upload but am not able to rename and am not getting a way to re-size the uploaded file.
if($this->getRequest()->isPost())
{
if(!$objProfilePictureForm->isValid($_POST))
{
//return $this->render('add');
}
if(!$objProfilePictureForm->profile_pic->receive())
{
$this->view->message = '<div class="popup-warning">Errors Receiving File.</div>';
}
if($objProfilePictureForm->profile_pic->isUploaded())
{
$values = $objProfilePictureForm->getValues();
$source = $objProfilePictureForm->profile_pic->getFileName();
//to re-name the image, all you need to do is save it with a new name, instead of the name they uploaded it with. Normally, I use the primary key of the database row where I'm storing the name of the image. For example, if it's an image of Person 1, I call it 1.jpg. The important thing is that you make sure the image name will be unique in whatever directory you save it to.
$new_image_name = 'new';
//save image to database and filesystem here
$image_saved = move_uploaded_file($source, '../uploads/thumb'.$new_image_name);
if($image_saved)
{
$this->view->image = '<img src="../uploads/'.$new_image_name.'" />';
$objProfilePictureForm->reset();//only do this if it saved ok and you want to re-display the fresh empty form
}
}
}

To Rename a file while uploading, you will have to add the "Rename-Filter" to your file-form-element. The class is called Zend_Filter_File_Rename.
// Create the form
$form = new Zend_Form();
// Create an configure the file-element
$file = new Zend_Form_Element_File('file');
$file->setDestination('my/prefered/path/to/the/file') // This is the path where you want to store the uploaded files.
$file->addFilter('Rename', array('target' => 'my_new_filename.jpg')); // This is for the filename
$form->addElement($file);
// Submit-Button
$form->addElement(new Zend_Form_Element_Submit('save');
// Process postdata
if($this->_request->isPost())
{
// Get the file and store it within the specified destination with the specified name.
$file->receive();
}
To make the filename dynamically you may name it with a timestamp or something. You may also apply the Rename-filter within your post-data-processing before the call of $file->receive(). This could be useful if you insert a row into a table and want to name the file with the id of the just inserted row.
Since you want to store a profile picture you could get the id of the user from your db and name the pic with that id.

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']);

php - rand() update image with the name of the previous one

I have a table CRUD that display my database.
When I upload an image in my image folder I generate a random name of numbers with that function rand()
Here is what I have coded :
My upload function
function importer_image()
{
if(isset($_FILES["image"]))
{
$extension = explode('.', $_FILES['image']['name']);
$new_name = rand() . '.' . $extension[1];
$destination = './upload/' . $new_name;
move_uploaded_file($_FILES['image']['tmp_name'], $destination);
return $new_name;
}
}
My upload php
if($_POST["operation"] == "Ajouter")
{
$image = '';
if($_FILES["image"]["name"] != '')
{
$image = importer_image();
}
The problem is then when I code the update function, the substitued image stays in my folder and the new one has a new name generated. In order to avoid this, I would like to create a condition that says if $image !='' 1/ erase the old file 2/ upload the new file and keep the same name than the deleted image.
So I'm trying to create an update php process that would 1/ delete unlink() 2/ upload the new image with the name of the previous image.
In order to delete the old image and maintain new name of image as previous, you have to take a hidden input in your form which contain your uploaded image name.
For e.g :
<input type="hidden" name="old-image" value="here is your previous image">
Now when your upload function will hit then you can get previous image name by request and can delete or maintain new image as previous.
if($_FILES['image']['name'] != '') {
$old_image = $_POST['old-image']; // get old image
$new_name = $old_image; // make new image name as previous
unlink('/upload/'.$old_image); // remove old image from folder
$destination = './upload/' . $new_name;
move_uploaded_file($_FILES['image']['tmp_name'], $destination);
return $new_name;
} else {
//if there is no image uploaded in the form then it will maintain old image
return $new_name= $_POST['old-image'];
}
Hope it will help you.
Your code to get extension works only if you have just one dot in the uploaded filename, it won't work for example on image_a.1.jpg. Use instead:
$extension = strrchr($_FILES['image']['name'],'.');
Also, using rand() for naming will eventually give you a headache when it generates the same number the second time and the uploaded image will overwrite the old one or not get saved, possibly producing error showing the user your full server save path. I'd use some hashing, like:
$new_name = md5($_FILES['image']['name'] . time());
If you need to save the file name as int, use crc32() instead of md5(). You could convert md5() result to int, but that would produce a very long int (128bit) that might not fit in your database or even PHP code.

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

PHP: Properly storing image names in MySQL DB

I am storing images name inside on MySQL database. Everytime I perform an upload, I have it return a link back with the image name attached which then I extract the image name and saved to the database. I have corrections to some critical flaws but I am still facing issues of having blank spaces/ duplicate names inserted into my database even though I have established checkpoints.
How can I avoid duplication/blank spaces of file names?
Is there a better approach in storing names in DB?
Location of image inside webserver:
http://www.example.com/imageupload/uploads/medium/50038dc14afb7.jpg
Link in the browser:
http://www.example.org/imageupload/index.php?i=50038dc14afb7.jpg
PHP
<?
$images = retrieve_images();
insert_images_into_database($images);
function retrieve_images()
{
$images = explode(',', $_POST['i']);
return $images;
}
function insert_images_into_database($images)
{
if(!$images) //There were no images to return
return false;
$db = dbConn::getConnection();
foreach($images as $image)
{
$sql = "INSERT INTO `urlImage` (`image_name`) VALUES ( ? )";
$prepared = $db->prepare($sql);
$prepared->execute(array($image));
}
}
?>
First, the blank name issue can perharps be fixed by checking $_POST['i']:
if (!isset($_POST['i'])) {
echo "No image to upload!";
die();
}
Have you tried redirecting after uploading the image?
// When image is uploaded
header("Location: http://example.org/imageupload/index.php");
die();
you can change the image name at the time of upload,
rand() is the function, which return random value, so you can avoid the duplicate image name,
the date time option will return always new date time, so you can diffidently get unique image name
Ex.$imageName.rand().$extention;
OR
Ex. $date = new DateTime(now);
$date = $date->format('Y_m_d_H_i_s');
$imageName.$date.$extention;
a couple of things:
To make sure you have unique file names, use tempnam() (
http://php.net/manual/en/function.tempnam.php )
To avoid page reload issue, post the upload form to a different page, which redirects to a
different page (or the previous form page) after it finishes doing the upload.
This is unrelated to your question but your SQL prepared statement should be outside of the loop.

Categories