I'm using PHP/MySQL to upload multiple images for photo album. The information associated with the images (filenames, extensions, descriptions etc.) is stored in database as base64 encoded data. I'm also able to edit the album images. My problem now is that I also want to create thumbnails for each of the images when uploading them on insert and edit mode and also store the information for the thumbnails the same way I do for the images (base64 encoded). What's the best way to do that? Thanks
Here's my code:
<?php
//Code for the editing albums in database
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit') {
//select photo album and get photos and descriptions to be merged with new.
$album_id = $_REQUEST['album_id'];
$old_photos = null;
$old_descriptions = null;
$getAlbumQ = mysql_query("select * from albums where id='$album_id'");
while ($old_album = mysql_fetch_array($getAlbumQ)) {
$old_photos = unserialize(base64_decode($old_album['photos']));
$old_descriptions = unserialize(base64_decode($old_album['descriptions']));
$old_timestamp=$old_album['timestamp'];
}
if (isset($_POST['album_name']) && isset($_POST['desc'])) {
$name = mysql_real_escape_string($_POST['album_name']);
$desc = mysql_real_escape_string($_POST['desc']);
$idesc = array();
$target_path = "/uploads/albums/";
foreach ($_FILES as $key => $value) {
foreach ($value as $k => $v) {
if ($k === 'name' && $v !== '') {
break;
} else {
unset($_FILES[$key]);
}
}
//first upload photos
$path = $target_path . basename($old_timestamp.$value['name']);
if(move_uploaded_file($value['tmp_name'], $path)) {
$hasUpload = true;
}
}
for ($j = 1; $j < 21; $j++) {
$img_index = $j;
$img_desc = $_POST['desc_' . $img_index];
array_push($idesc, $img_desc);
}
foreach ($_FILES as $key => $value) {
foreach ($value as $k => $v) {
if ($k=='name' && $v!='') {
break;
} else {
unset($_FILES[$key]);
}
}
}
function merge(&$a, &$b){
$keys = array_keys($a);
foreach($keys as $key){
if(isset($b[$key])){
if(is_array($a[$key]) and is_array($b[$key])){
merge($a[$key],$b[$key]);
}
else{
$a[$key] = $b[$key];
}
}
}
$keys = array_keys($b);
foreach($keys as $key){
if(!isset($a[$key])){
$a[$key] = $b[$key];
}
}
}
for ($i = 1; $i < 21; $i++) {
$file_index = $i;
$file_number = $_POST['image_' . $file_index];
if($_FILES['image_'.$i]['name']!= ''){
$hasUpload = true;
$presults = merge($old_photos, $_FILES);
$dresults = array_merge($old_descriptions, $idesc);
$images = base64_encode(serialize($presults));
$descriptions = base64_encode(serialize($dresults));
$posted = date("Y-m-d H:i:s");
}
else {
$hasUpload = false;
$presults = $old_photos;
$dresults = $idesc;
$images = base64_encode(serialize($presults));
$descriptions = base64_encode(serialize($dresults));
$posted = date("Y-m-d H:i:s");
}
}
}
if (mysql_query("update albums set description = '$desc', name = '$name', photos='$images', descriptions='$descriptions' where id='$album_id'")) {
$hasAlbums = true;
} else {
$hasErrors = true;
}
} else {
//Code for the inserting albums in database
if (isset($_POST['album_name'])) {
if (isset($_POST['album_name']) && isset($_POST['desc'])) {
$name = mysql_real_escape_string($_POST['album_name']);
$desc = mysql_real_escape_string($_POST['desc']);
$idesc = array();
$timestamp = time();
$target_path = "/uploads/albums/";
foreach ($_FILES as $k => $v) {
//first upload photos
$path = $target_path . basename($timestamp.$v['name']);
if(move_uploaded_file($v['tmp_name'], $path)) {
$img_index = explode('_', $k);
$img_index = $img_index[1];
$img_desc = $_POST['desc_' . $img_index];
array_push($idesc, $img_desc);
$file_name = $timestamp.$v['name'];
$hasUpload = true;
}
}
$images = base64_encode(serialize($_FILES));
$descriptions = base64_encode(serialize($idesc));
$posted = date("Y-m-d H:i:s");
$query = mysql_query("
INSERT INTO albums (description, posted, photos, name, descriptions, timestamp)
VALUES ('$desc', '$posted', '$images', '$name', '$descriptions', '$timestamp')
");
}
}
}
?>
I tried a simple thumbnail script found on this tutorial and it worked perfectly: http://net.tutsplus.com/articles/news/how-to-dynamically-create-thumbnails/
Thanks for your suggestions
You can use the Thumbnail class from
http://freecode.com/projects/easyphpthumbnailclass
You may use ImageMagick's resizeImage method.
explained in a tutorial here http://coffeeshopped.com/2009/01/creating-image-thumbnails-using-php-and-imagemagick
Also, you may try phpThumb() function and is available at sourceforge here http://phpthumb.sourceforge.net/
Hope this helps..
Related
I'm trying to make a recursive function to get all the directories and sub directories from my ftp server in an array.
I tried a lot of functions I've found on the web. The one that works best for me is this one:
public function getAllSubDirFiles() {
$dir = array(".");
$a = count($dir);
$i = 0;
$depth = 20;
$b = 0;
while (($a != $b) && ($i < $depth)) {
$i++;
$a = count($dir);
foreach ($dir as $d) {
$ftp_dir = $d . "/";
$newdir = ftp_nlist($this->connectionId, $ftp_dir);
foreach ($newdir as $key => $x) {
if ((strpos($x, ".")) || (strpos($x, ".") === 0)) {
unset($newdir[$key]);
} elseif (!in_array($x, $dir)) {
$dir[] = $x;
}
}
}
$b = count($dir);
}
return $dir ;
}
The problem with this function is it wont allow the directory to have a "." in it's name and every file that is located in the root directory will be considered a directory as well. So I adjusted the function and got this:
public function getAllSubDirFiles($ip, $id, $pw) {
$dir = array(".");
$a = count($dir);
$i = 0;
$depth = 20;
$b =0;
while (($a != $b) && ($i < $depth)) {
$i++;
$a = count($dir);
foreach ($dir as $d) {
$ftp_dir = $d . "/";
$newdir = ftp_nlist($this->connectionId, $ftp_dir);
foreach ($newdir as $key => $x) {
if (!is_dir('ftp://'.$id.':'.$pw.'#'.$ip.'/'.$x)) {
unset($newdir[$key]);
} elseif (!in_array($x, $dir)) {
$dir[] = $x;
}
}
}
$b = count($dir);
}
return $dir ;
}
This works pretty good but and gives the result I want. but it's so slow it's unusable.
I also tried working with ftp_rawlist but it has the same drawback of being horribly slow.
public function getAllSubDirFiles() {
$dir = array(".");
$a = count($dir);
$i = 0;
$depth = 20;
$b = 0;
while (($a != $b) && ($i < $depth)) {
$i++;
$a = count($dir);
foreach ($dir as $d) {
$ftp_dir = $d . "/";
$newdir = $this->getFtp_rawlist('/' . $ftp_dir);
foreach ($newdir as $key => $x) {
$firstChar = substr($newdir[$key][0], 0, 1);
$a = 8;
while ($a < count($newdir[$key])) {
if ($a == 8) {
$fileName = $ftp_dir . '/' . $newdir[$key][$a];
} else {
$fileName = $fileName . ' ' . $newdir[$key][$a];
}
$a++;
}
if ($firstChar != 'd') {
unset($newdir[$key]);
} elseif (!in_array($fileName, $dir)) {
$dir[] = $fileName;
}
}
}
$b = count($dir);
}
return $dir;
}
public function getFtp_rawlist($dir) {
$newArr = array();
$arr = ftp_rawlist($this->connectionId, $dir);
foreach ($arr as $value) {
$stringArr = explode(" ", $value);
$newArr[] = array_values(array_filter($stringArr));
}
return $newArr;
}
I've been stuck on this problem for the last couple of days and I'am getting desperate. If any one has any suggestion please let me know
If your server supports MLSD command and you have PHP 7.2 or newer, you can use ftp_mlsd function:
function ftp_mlsd_recursive($ftp_stream, $directory)
{
$result = [];
$files = ftp_mlsd($ftp_stream, $directory);
if ($files === false)
{
die("Cannot list $directory");
}
foreach ($files as $file)
{
$name = $file["name"];
$filepath = $directory . "/" . $name;
if (($file["type"] == "cdir") || ($file["type"] == "pdir"))
{
// noop
}
else if ($file["type"] == "dir")
{
$result = array_merge($result, ftp_mlsd_recursive($ftp_stream, $filepath));
}
else
{
$result[] = $filepath;
}
}
return $result;
}
If you do not have PHP 7.2, you can try to implement the MLSD command on your own. For a start, see user comment of the ftp_rawlist command:
https://www.php.net/manual/en/function.ftp-rawlist.php#101071
If you cannot use MLSD, you will particularly have problems telling if an entry is a file or folder. While you can use the ftp_size trick, calling ftp_size for each entry can take ages.
But if you need to work against one specific FTP server only, you can use ftp_rawlist to retrieve a file listing in a platform-specific format and parse that.
The following code assumes a common *nix format.
function ftp_nlst_recursive($ftp_stream, $directory)
{
$result = [];
$lines = ftp_rawlist($ftp_stream, $directory);
if ($lines === false)
{
die("Cannot list $directory");
}
foreach ($lines as $line)
{
$tokens = preg_split("/\s+/", $line, 9);
$name = $tokens[8];
$type = $tokens[0][0];
$filepath = $directory . "/" . $name;
if ($type == 'd')
{
$result = array_merge($result, ftp_nlst_recursive($ftp_stream, $filepath));
}
else
{
$result[] = $filepath;
}
}
return $result;
}
For DOS format, see: Get directory structure from FTP using PHP.
I've build an OOP FTP Client library that's can help you on this a lot, using just this code you can retrieve a list of only the directories with addition useful information like (chmod, last modified time, size ...).
The code :
// Connection
$connection = new FtpConnection("localhost", "foo", "12345");
$connection->open();
// FtpConfig
$config = new FtpConfig($connection);
$config->setPassive(true);
$client = new FtpClient($connection);
$allFolders =
// directory, recursive, filter
$client->listDirectoryDetails('/', true, FtpClient::DIR_TYPE);
// Do whatever you want with the folders
This code a variation of Martin Prikryl one. It is slower but do not have any failures with whitespaces. Use this code only if you have any problems with the code above.
function ftp_list_files_recursive($ftp_stream, $path){
$lines = ftp_nlist($ftp_stream, $path);
$result = array();
foreach ($lines as $line) {
if (ftp_size($ftp_stream, $line) == -1) {
$result = array_merge($result, ftp_list_files_recursive($ftp_stream, $line));
}
else{
$result[] = $line;
}
}
return $result;
}
How can I access the contents of $value[$i] which is an array. No luck using foreach in the form below.
The idea is to loop through $contentArray and display one item from each sub-array on every iteration.
$addsContent = $Adds->selectAdds(10);
$sharedArticlesContent = $SharedContent->getSharedContent($topic_selected, $filter_selected);
$blogPostsContent = $BlogPosts->getRecentBlogPostsByTopic("business");
$contentArray = array(
$sharedArticlesContent,
$addsContent ,
$blogPostsContent
);
foreach($contentArray as $value)
{
if(count($value)>$maxLength)
{
$maxLength = count($value);
}
}
for($i=0; $i<$maxLength; $i++)
{
foreach($contentArray as $value)
{
if(isset($value[$i]))
{
if($value==$sharedArticlesContent){
$data = $value[$i];
foreach($sharedArticlesContent as $data){
$post_id = $data['id'];
$uploaded_by = $data['uploaded_by'];
$text = $data['text'];
$image = $data['image'];
require 'template1.php';
}
}elseif($value==$addsContent){
//template2
}else{
//template3
}
}
}
}
You're dealing with an associative array here, you can access it like that:
<?php
$addsContent = $Adds->selectAdds(10);
$sharedArticlesContent = $SharedContent->getSharedContent($topic_selected, $filter_selected);
$blogPostsContent = $BlogPosts->getRecentBlogPostsByTopic("business");
$contentArray = array(
$sharedArticlesContent,
$addsContent ,
$blogPostsContent
);
foreach($contentArray as $value)
{
if(count($value)>$maxLength)
{
$maxLength = count($value);
}
}
for($i=0; $i<$maxLength; $i++)
{
foreach($contentArray as $value)
{
if(isset($value[$i]))
{
if($value==$sharedArticlesContent)
{
$post_id = $value[$i]['id'];
$uploaded_by = $value[$i]['uploaded_by'];
$text = $value[$i]['text'];
$image = $value[$i]['image'];
require 'template1.php';
}
elseif($value==$addsContent)
{
//template2
}
else
{
//template3
}
}
}
}
You don't need the foreach. $data is an associative array, you don't need to loop through it.
if($value==$sharedArticlesContent){
$data = $value[$i];
$post_id = $data['id'];
$uploaded_by = $data['uploaded_by'];
$text = $data['text'];
$image = $data['image'];
require 'template1.php';
}
I want to upload an Excel file into a MySQL table without using PDO, but just with a simple MySQL connection.
I want to load the Excel file using DOMDocument::load but can't get it to work.
Here's what I've tried so far:
mysql_connection("localhost", "root", "");
mysql_select_db("excel");
function add_data($abc, $pqr, $xyz) {
$str = "INSERT INTO excel(abc, pqr, xyz) VALUES('$abc', '$pqr', '$xyz')";
$qry = mysql_query($str);
}
if (isset($_FILES['file'])) {
$dom = DOMDocument::load($_FILES['file']['tmp_name']);
$rows = $dom->getElementsByTagName('Row');
$first_row = true;
foreach ($rows as $row) {
if (!$first_row) {
$abc = "";
$pqr = "";
$xyz = "";
$index = 1;
$cells = $row->getElementsByTagName('Cell');
foreach ($cells as $cell) {
$ind = $cell->getAttribute('Index');
if ($ind != null)
$index = $ind;
if ($index == 1)
$abc = $cell->nodeValue;
if ($index == 2)
$pqr = $cell->nodeValue;
if ($index == 3)
$xyz = $cell->nodeValue;
$index += 1;
}
add_data($abc, $pqr, $xyz);
}
$first_row = false;
}
}
I want to select four random images from a folder which contains a number of images.
What i want to display is a table (2x2) where i can display 4 random distinct images.
Can someone tell me how can i select random distinct files from a folder so that i can store their path in a variable and then can use these variables to display images randomly in the table!
Is there any particular function which can select random files from a folder or something like that?
Use glob() to get all files from directory.
Use array_rand() to get random entries from an array.
<?php
function get_imagess($root) {
$r = array();
$r = array();
$k = glob("$root/*");
shuffle($k);
foreach($k as $n) {
if (is_dir($n)) {
break;
//$r = array_merge($r, get_imagesss($n));
print_r("xxx");
} else {
$r[] = $n;
//print_r($n + "yeah");
}
}
return $r;
}
function get_images($root) {
$r = array();
$k = glob("$root/*");
shuffle($k);
$n = $k[0];
// foreach($k as $n) {
if (is_dir($n)) {
$r = array_merge($r, get_imagess($n));
} else {
$r[] = $n;
}
// }
return $r;
}
$files = get_images('.');
//print_r($files);
//break;
shuffle($files);
$true=true;
$extList = array();
$extList['gif'] = 'image/gif';
$extList['jpg'] = 'image/jpeg';
$extList['jpeg'] = 'image/jpeg';
$extList['png'] = 'image/png';
$ass=0;
while($true)
{
$ass=$ass+1;
if($ass>100){$true=false;}
$imageInfo = pathinfo($files[0]);
if (isset( $extList[ strtolower( $imageInfo['extension'] ) ] )){
$temp = substr($files[0], -5);
$temp = strtolower($temp);
if( $temp == "p.jpg"){shuffle($files);} // checking if jpg has a preview file
else{ // no preview found
$true=false;
//print_r($temp);
}}
else
{
shuffle($files);
//print_r('bad' + $temp);
}
}
//print_r($files[0]);
echo '<HTML><meta HTTP-EQUIV="Refresh" CONTENT="5; URL=./ImageRotateMaybe.php"><img src="';
echo $files[0];
echo ' " width=100%>';
?>
I have a photo album, with a 'photos' field in database which has serialized data and is base 64 encoded. I can upload up to 21 photos at the same time for the album (multiple uploading). When trying to add new photos to the album on edit mode, I can't get the new $_FILES array to merge with the old array in the database. I want to update only the values that I have changed. So let's say I already had 2 images inside my album, I would like to add a 3rd image without losing the other 2 images. I know I need to use unset() to delete empty values but I think i'm not doing it correctly. Here's my code:
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit') {
//select photo album and get photos and descriptions to be merged with new.
$album_id = $_REQUEST['album_id'];
$old_photos = null;
$old_descriptions = null;
$getAlbumQ = mysql_query("select * from albums where id='$album_id'");
while ($old_album = mysql_fetch_array($getAlbumQ)) {
$old_photos = unserialize(base64_decode($old_album['photos']));
$old_descriptions = unserialize(base64_decode($old_album['descriptions']));
}
if (isset($_POST['album_name']) && isset($_POST['desc'])) {
$name = $_POST['album_name'];
$desc = $_POST['desc'];
$idesc = array();
$target_path = "../uploads/albums/";
foreach ($_FILES as $k => $v) {
//first upload photos
$path = $target_path . basename($v['name']);
if(move_uploaded_file($v['tmp_name'], $path)) {
$hasUpload = true;
}
}
for ($j = 1; $j < 21; $j++) {
$img_index = $j;
$img_desc = $_POST['desc_' . $img_index];
$asdf = $_FILES['image_' . $img_index]['name'];
array_push($idesc, $img_desc);
}
foreach( $_FILES['images']['name'] as $key => $value ) {
if( empty($value) ) {
unset( $_FILES['images']['name'][$key] );
}
}
for ($i = 1; $i < 21; $i++) {
if($_FILES['image_'.$i]['name']!= '')
{
$hasUpload = true;
$presults = array_merge($old_photos, $_FILES); //THE PROBLEM WITH MERGING ARRAYS OCCURS HERE
$dresults = array_merge($old_descriptions, $idesc);
$images = base64_encode(serialize($presults));
$descriptions = base64_encode(serialize($dresults));
$posted = date("Y-m-d H:i:s");
}
else {
$hasUpload = false;
$presults = $old_photos;
$dresults = $idesc;
$images = base64_encode(serialize($presults));
$descriptions = base64_encode(serialize($dresults));
$posted = date("Y-m-d H:i:s");
}
}
}
}
I tried something similar to what Muu suggested. Combined it with another piece of code of a custom merge function found here http://keithdevens.com/weblog/archive/2003/Mar/30/MergeTwoArrays and it worked fine! Thanks for your help
Just needed to add the following lines of code outside the for ($i = 1; $i < 21; $i++) loop:
//delete empty values for $_FILES array
foreach ($_FILES as $key => $value) {
foreach ($value as $k => $v) {
if ($k=='name' && $v!='') {
break;
} else {
unset($_FILES[$key]);
}
}
}
//custom array merge function
function merge(&$a, &$b){
$keys = array_keys($a);
foreach($keys as $key){
if(isset($b[$key])){
if(is_array($a[$key]) and is_array($b[$key])){
merge($a[$key],$b[$key]);
}else{
$a[$key] = $b[$key];
}
}
}
$keys = array_keys($b);
foreach($keys as $key){
if(!isset($a[$key])){
$a[$key] = $b[$key];
}
}
}
then instead of array_merge(), I used merge() inside the for ($i = 1; $i < 21; $i++) loop:
$presults = merge($old_photos, $_FILES);
Instead of removing the empty values from the array, why not just ignore them?
For example:
$nonEmptyArray = array();
foreach ($_FILES as $k => $v) {
if (!$v) {
continue;
}
$nonEmptyArray[$k] = $v;
}
$_FILES = $nonEmptyArray;