I'm trying to make a PHP script that changes the featured picture of some item.
The general principle is that it when $_POST['featured'] is set, it renames that picture to featured.jpg and renames all other pictures to their hash_file value. However, it works well the first time when there is no featured picture set, but when I try to change it from one featured picture to another, the previous featured picture gets removed and the new one doesn't get renamed to featured.jpg. All pictures are in the same folder.
Here is the relevant code:
if (isset($_POST['featured'])) {
$id = $_POST['id'];
$slike = glob('../img/uploads/'.$id.'/*.{jpg,png}', GLOB_BRACE);
if ($slike != null) {
foreach ($slike as $slika) {
$path = realpath($slika);
$name = basename($path);
if($name == basename($_POST['featured'])){
if(!file_exists(dirname($path) . '/featured.jpg')){
rename($path, dirname($path) . '/featured.jpg');
}else{
rename(dirname($path) . '/featured.jpg', dirname($path) . '/' . hash_file('md5', $path) . '.jpg');
rename($path, dirname($path) . '/featured.jpg');
}
}else{
rename ($path, dirname($path) . '/' . hash_file('md5', $path) . '.jpg');
}
}
}
}
Related
Here is my code
$file = 'post.php';
$root = '/' . $dir_auth1 . '/'. $file;
$folder = mkdir(rand(10,10000));
$folder5 = $folder . '/' . $file;
echo $folder5;
if($folder) {
if (!copy($root, $folder5)) {
echo "failed to copy $file...\n";
} else {
echo "<p style='font-size:35px;font-family:verdana;text-align:center;'>status was successfuly created.</p>";
}
}
Basically what I am trying to do is upon a form submit create a directory with random digits and place the $file variable inside of the randomized directory
mkdir - return bool. Please read about mkdir
And rewrite you code something like this:
$file = 'post.php';
$root = '/' . $dir_auth1 . '/'. $file;
$folder = rand(10,10000);
mkdir($folder);
$folder5 = $folder . '/' . $file;
And check you if. You always true. (not empty string = true)
So I found this class on the internet that can put files into a zip.
I have a form where I can upload pictures into a folder, but when I try to add them into the zip I could add only the last file from that folder (loop).
zipper class
<?php
class zipper {
private $_files = array(),
$_zip;
public function __construct() {
$this->_zip = new ZipArchive;
}
public function add($input){
if(is_array($input)){
$this->_files = array_merge($this->_files, $input);
}else{
$this->_files[] = $input;
}
}
public function store($location = null){
if(count($this->_files) && $location){
foreach ($this->_files as $index => $file) {
if(!file_exists($file)){
unset($this->_files[$index]);
}
print_r($file . "<br>");// here gives me the exact path of the files.
}
if($this->_zip->open($location, file_exists($location) ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE)){
foreach ($this->_files as $file) {
$this->_zip->addFile($file, $file);
}
$this->_zip->close();
}
}
}
}
and this is my uploading file
> $uniqUser = uniqid(strtoupper($userName). "-" , true);
> $directory ='../upload/';
> $file_name is $files['name']
if(!is_dir("../upload/". $uniqUser ."/")) {
mkdir("../upload/". $uniqUser ."/");
}
if(move_uploaded_file($file_tmp, $directory . $uniqUser . "/" . $file_name)){
$uploaded[$position] = $directory . $uniqUser . "/" . $file_name;
$zipper = new zipper;
$zipper->add(BASE_URL . "/upload/" . $uniqUser . "/" . $file_name);
$zipper->store(BASE_URL . "/upload/" . $uniqUser . ".zip");
the last code is inside a foreach that loops into the files uploaded.
When I did a print_r("Added file:" . $file . "<br>"); to see if the all files are added, I get a positive response. But I always get the last file from the folder.
Thank you
EDIT
Well, Guess the problem is after each loop to add the files in the folder, the zip class adds the file into the zip, then after checks if the zip exists or no ... So after each loop the zip is overwritten and adds only the last file.
How can I make this better ?
The problem was kinda stupid ...
I had to create the class outside the foreach $zipper = new zipper; and $zipper-store("../upload/" . $uniqUser . ".zip");for unnecessary repeating (added it at the bottom).
Image is stored in database (as varchar(255)), but on page isn't shown.
This is code that stored image, and put's image in folder:
if (isset($_FILES["image"])) {
$title = date("dmyHms") . "_" . $_FILES["image"]["name"];
$path = "img/profile/" . $_POST["id"] . "_" . $title;
move_uploaded_file($_FILES["image"]["tmp_name"], $path);
}
And this is to display image:
foreach ($conn->results() as $conn):
$img = $_SERVER["CONTEXT_DOCUMENT_ROOT"] . $path . "img/profile" . $conn->id . "_" . $conn->image;
if (file_exists($img)) {
$image = $path . "img/profile/" . $conn->id . "_" . $conn->image;
} else {
$image = $path . "img/noimage.png";
}
<?php endforeach; ?>
When I print_r $img, it shows right path to image and still image is not displayed.
Display:
<?php echo $image; ?>
Where did you echoing your image? If it is inside foreach, you need to change your code little bit...
$image = '<img src="'.$path . "img/profile/" . $conn->id . "_" . $conn->image . '" />';
Hope, will work perfectly for you.... TQ
The following line is not correct:
foreach ($conn->results() as $conn):
Don't overwrite $conn. Change the variable to something different like $result
I want to be able to present the photo of a user. That user may be of the type Doctor, Nurse or Patient and each person belonging to each of those types has a distinct ID which identifies him. I have the photos of each type of users separated in three folders inside the directory /images/user_upload/ and a given user may or may not have a photo. If he has a photo, I want to present the photo with a name which is the same as his ID (Note that I don't know the extension of this file, only the name). If he doesn't I want to present a default image. I have a function called printUserPhoto for this end.
function printUserPhoto()
{
$path = '/images/user_upload/' .ucfirst($_SESSION['listtype']). '/' .$_SESSION['id']. '.*';
$source = glob($path);
if(empty($source))
echo '<img src="images/default_profile_img.png" />';
else
echo '<img src="',$source[0],'" />';
}
Although, I always get an empty array in the variable $source, even though the image exists. What am I doing wrong?
This way with glob
function printUserPhoto()
{
$pathToDocumentRoot = $_SERVER['DOCUMENT_ROOT'];
$path = $pathToDocumentRoot . '/images/user_upload/' .ucfirst($_SESSION['listtype']). '/' .$_SESSION['id']. '.*';
$source = glob($path);
if(empty($source)){
echo '<img src="images/default_profile_img.png" />';
} else {
echo '<img src="',$source[0],'" />';
}
}
Maybe limit the filetypes user can upload. With that you could do something like this:
function printUserPhoto()
{
$pathToDocumentRoot = $_SERVER['DOCUMENT_ROOT'];
$path = $pathToDocumentRoot . '/images/user_upload/' .ucfirst($_SESSION['listtype']). '/' .$_SESSION['id'];
$file = "images/default_profile_img.png";
if(file_exists($path . '.jpg')){
$file = $path . '.jpg';
}else if(file_exists($path . '.png')){
$file = $path . '.png';
}else if(file_exists($path . '.gif')){
$file = $path . '.gif';
}
echo '<img src="' . $file . '" />';
}
Also as being said by #Phil you are now referring to the file system root / being absolute path not relative to your document root.
I have a directory with almost 60 images but in HD quality so theirs size are around 5 ~ 6 MB and load all them in a web page is to much time for server and browser so both hang up. I read this post and this other too and since I'm using PHP 5.4.20 in my server I'll like to use DirectoryIterator and LimitIterator but example leave in the post are not so explicit to me since I don't know how to move forward/backward in this cases. Can any give me some sample code about paginate files in a directory?
UPDATE: show some code
Right now this is how I read files:
function directoryToArray($directory, $recursive) {
$array_items = array();
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if (is_dir($directory . "/" . $file)) {
if ($recursive) {
$array_items = array_merge($array_items, directoryToArray($directory . "/" . $file, $recursive));
}
$file = $directory . "/" . $file;
$array_items[] = preg_replace("/\/\//si", "/", $file);
} else {
$file = $directory . "/" . $file;
$array_items[] = preg_replace("/\/\//si", "/", $file);
}
}
}
closedir($handle);
}
return $array_items;
}
$images = directoryToArray("images/portfolio/");
for ($i = 0; $i < count($images); $i++) {
$old_img_name = explode('/', $images[$i]);
$new_img_name = $old_img_name[0] . "/" . $old_img_name[1] . '/large/' . $old_img_name[2];
echo '<div class="span4 element">';
echo '<div class="hover_img">';
echo '<img src="' . $images[$i] . '" alt="" />';
echo '<span class="portfolio_zoom"></span>';
echo '</div>';
echo '</div>';
}
Aristona's absolutely right. You should probably resize the images to an appropriate file-format, quality & size. At the very least if you're trying to make some sort of gallery, you could use something like image magick to make 'thumbnails' for the gallery where clicking on them may take you to the full-quality image.
Image magick is scriptable in a variety of languages to batch process your images and build thumbnails if you want it to run as a process, alternatively from the command line you can do it as a once off, something like what's mentioned here:
Batch resize images into new folder using ImageMagick