Display uploaded file or image in grid in php - php

I have successfully uploaded some images to the server. Im thinking to display them in my admin page in grid view.. currently it displayed vertically.
Can anyone help?
Thanks in advance for you kind assistance.
<?php
$dir_path = "../../img/gallery/";
$extensions_array = array('jpg','png','jpeg');
if(is_dir($dir_path))
{
$files = scandir($dir_path);
for($i = 0; $i < count($files); $i++)
{
if($files[$i] !='.' && $files[$i] !='..')
{
// get file name
echo "File Name: $files[$i]<br>";
// get file extension
$file = pathinfo($files[$i]);
$extension = $file['extension'];
{
// show image
echo "<img src='$dir_path$files[$i]' style='width:60px;height:80px;'><br>
</br>";
}
}
}
}
?>
This code works fine but I just don't know to display it in grid or table..

You can achieve that by echoing each table part inside the loop:
<?php
$dir_path = "../../img/gallery/";
$extensions_array = array('jpg','png','jpeg');
$numCol = 3;
if(is_dir($dir_path))
{
$files = scandir($dir_path);
for($i = 0; $i < count($files); $i++)
{
$n = 0;
echo '<table>';
echo '<tr>';
if($files[$i] !='.' && $files[$i] !='..')
{
$n ++;
// get file name
echo "<td>File Name: $files[$i]<br>";
// get file extension
$file = pathinfo($files[$i]);
$extension = $file['extension'];
// show image
echo "<img src='$dir_path$files[$i]' style='width:60px;height:80px;'></td>";
if($n % $numCol == 0) echo "</tr><tr>";
}
echo '</tr>';
echo '</table>';
}
}
?>
$numCol defines how many column must have every table's row.
Also, I removed these {} that were useless:
$extension = $file['extension'];
{
// show image
echo "<img src='$dir_path$files[$i]' style='width:60px;height:80px;'><br>
</br>";
}

Related

Multi image upload validate by php

i modified my upload code based on this post https://stackoverflow.com/a/30074716/14787718 (its working code)
but my code does not work, please help.
my full code here: https://sandbox.onlinephpfunctions.com/code/c62b6bdf6fadd5aff63b2e7e65e75c1075d1dbb0
<?php
if (isset($_POST['upload']) && $_FILES['image']['error']==0) {
$j = 0; //Variable for indexing uploaded image
for ($i = 0; $i < count($_FILES['image']['name']); $i++) {//loop to get individual element from the array
$allow_ext = array('png','jpg','gif','jpeg','bmp','tif');
$allow_type = array('image/png','image/gif','image/jpeg','image/bmp','image/tiff');
$image_name = $_FILES['image']['name'][$i];
$image_type = getimagesize($_FILES['image']['tmp_name'][$i]);
$image_name = explode('.',$image_name);
$ext = end($image_name);
$j = $j + 1;//increment the number of uploaded images according to the files in array
if(in_array($ext, $allow_ext) && in_array($image_type['mime'], $allow_type)){
list($width, $height, $mime) = getimagesize($_FILES['image']['tmp_name'][$i]);
if ($width>0 && $height>0) {
$upload = move_uploaded_file($_FILES['image']['tmp_name'][$i], "uploads/".$_FILES['image']['name'][$i]);
if ($upload) {
echo '<p>File Uploaded: View Image</p>';
}
} else {
echo 'Error: Only image is allowed!';
}
} else {
echo 'Error: Invalid File Type!';
}
}
}
?>
thank you!
first move the Jquery call to place it before bootstrap:
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.0/js/bootstrap.min.js'></script>
And at your first test : if (isset($_POST['upload']) && $_FILES['image']['error']==0). $_FILES['image']['error'] is an array.
Delete this test to keep only if ( isset($_POST['upload']) )
Add this test in you for step:
for ($i = 0; $i < count($_FILES['image']['name']); $i++) {//loop to get individual element from the array
if ($_FILES['image']['error'][$i]==0) {
Tested, it works fine!

Is it possible to add action only at LOOP's final round?

I want to do redirect to other page after finish the loop
something like this
for($i = 0; $i < 5; $i++)
{
echo $i;
header('Location: home.php'); // do this if finish the loop
}
Note : My case the redirect has to be in loop because my real code is about upload multiple files in loop and check file type in loop so I want to not redirect if it has wrong filetype, and if upload correctly, redirect to home.php page too. but the problem is when I upload correctly in first round loop it will redirect to home page without doing upload residual files.
and If I put redirect outside of loop , the errormessage of filetype will not show because it will redirect to home only.
$path_upload = 'images/cover/';
$count = count($_FILES["images"]["name"]);
$allowed_types = array("image/gif", "image/jpeg", "image/png");
$nl = PHP_EOL.'<br>'; // Linux: \n<br> Window: \r\n<br>
$arr_newname = array();
for($i=0; $i < $count; $i++)
{
$file_type = $_FILES["images"]['type'][$i];
$file_name = $_FILES["images"]['name'][$i];
$file_size = $_FILES["images"]['size'][$i];
$file_error = $_FILES["images"]['error'][$i];
$file_tmp = $_FILES["images"]['tmp_name'][$i];
if($_FILES["images"]["name"][$i] != "")
{
if (in_array($file_type, $allowed_types) && $file_size < 2000000)
{
if ($file_error > 0) {
echo 'Upload file:'.$file_name.' error: '.$file_error.$nl;
} else {
$ext = explode('.', $file_name); // explode dots on filename
$ext = end($ext); // get last item of array
$newname = "album_id".$album_id."_".date('Y-m-d')."_".($i+1).".".$ext;
$arr_newname[$i] = $newname;
$path_new_upload = $path_upload.$newname;
if(move_uploaded_file($file_tmp, $path_new_upload))
{
$data = array(
'front_pic'.($i+1) => $arr_newname[$i]
);
$this->db->where('album_id', $album_id);
$this->db->update('oav_album', $data);
redirect('home.php'); ////////THIS will stop the residual round of loop
}
}
}
else
{
echo 'Invalid file type to: '.$file_name.$nl;
// continue the code
}
}
}
redirect('home.php'); ////////IF I put this outside loop it will not show error` message but redirect to home
You can write the statement after the loop so it works at the end of the loop for one time. If you want to use last known $i value you can define $i before the loop and use it after the loop.
$i = 0
for ($i = 0; $i < $count; $i++){
//loop
}
$i--;//get last value
echo $i;
header('Location: home.php'); // do this if finish the loop

PHP not echoing Ż correctly

I have a problem with PHP. It's not printing out name of a folder I've grabbed with readdir() properly.
The problem is only with a single character that is used in Polish.
<?php
//var with directory, put in the directory containing albums here
$main = "C:/Users/Jakub/Desktop/devving/gallery/images/";
$counter = 0;
$albumdata = [];
//gets all albums inside of the folder and stores inside of an array
if($opendir = opendir($main)){
while(($file = readdir($opendir)) !== false){
if($file == "." or $file == "..")continue;
$albumdata[$counter] = $file;
$counter += 1;
}
closedir($opendir);
$counter = 0;
}
//gets all files inside of albums and stores them inside of arrays with the names of the albums
for($i = 0;$i < count($albumdata); $i++){
if($opendir = opendir($main . $albumdata[$i])){
while(($file = readdir($opendir)) !== false){
if($file == "." or $file == "..") continue;
${$albumdata[$i]}[$counter] = $file;
$counter +=1;
}
closedir($opendir);
$counter = 0;
}
}
//echoes albums
for($i = 0;$i < count($albumdata); $i++){
$counter += 1;
if($counter == 1){
echo "<div class = 'firstimg'><a href = '"."images/".$albumdata[$i]."'><img src = '"."images/".$albumdata[$i]."/".${$albumdata[$i]}[0]."'><p>".$albumdata[$i]."</p></a></div>";
}else if($counter == 2){
echo "<div class = 'secondimg'><a href = '"."images/".$albumdata[$i]."'><img src = '"."images/".$albumdata[$i]."/".${$albumdata[$i]}[0]."'><p>".$albumdata[$i]."</p></a></div>";
}else{
echo "<div class = 'lastimg'><a href = '"."images/".$albumdata[$i]."'><img src = '"."images/".$albumdata[$i]."/".${$albumdata[$i]}[0]."'><p>".$albumdata[$i]."</p></a></div>";
$counter = 0;
}
}
?>
Here's the code. The albums in the $main directory are called Koty, Krajobrazy
Ptaki and Żaby. The problem is with the last one, instead of echoing Żaby in the paragraph
and the source it echoes �aby.
edit: Forgot to mention, I can echo Ż alone.

echo 15 random lines of html files

I have to do a php assignment for college.
How would I echo 15 random lines of a html file if there is a movie script text and a image with the same in the same folder?
What I have tried so far:
$folder = 'Filmnoir/';
$hitchcock ='Hitchcock/';
$shakespear ='Shakespear/';
$filetype = '*.*';
$files = glob($folder.$filetype);
$file2 = glob ($hitchcock.$filetype);
$file3 = glob ($shakespear.$filetype);
$count = count($files);
$count1 = count($file2);
$count2 = count($file3);
$scripttype ='*.html';
$Scripts = glob($ScriptFilmNoir.$scripttype);
$Scripts=file_get_contents("DoubleIndemnity.html");
if($_POST['radio1']=="0"){
if(($i %1)==0){
for ($i = 0; $i < $count; $i++)
{
echo '<div class="image2">';
echo '<img src="'.$files[$i].'" />';
echo '</div>';
if (condition) {
include 'DoubleIndemnity.html'; }
echo '</td></tr>';
}
echo '<div class="Passwordtext">';
echo 'Type in password to view full Script';
echo '</div>';
echo "<label><div class=\"password\"><input type='password' name='code' value='code'/></div></label>";
echo "<form method='POST' action='ca1_result.php'>";
echo "<div class=\"SubmitIt\"><input type='submit' name='submitScript' value='Submit Password'/></div>";
echo '</form>';
}
}
if($_POST['radio1']=="1"){
echo '<div class="Sorrytext">';
echo 'We apologize. No script available for this movie.';
echo '</div>';
}
if($_POST['radio1']=="2"){
echo '<div class="Sorrytext">';
echo 'We apologize. No script available for this movie.';
echo '</div>';
}
I want to achieve that when there is an image (e.g DoubleIndemnity.png) and movie script (e.g DoubleIndemnity.html) in the same folder that I get 15 random lines of the movie script text plus the image. Could I use the glob function and when yes how would I achieve that?
Can I ask another thing? When I submit the password how to I get then the full movie script?
I tried:
foreach($files as $file2) {
if($_POST['submitPassword']){
if($file2 === '.' OR $file2 === '..' OR $file2 === 'thumbs.db' OR !is_dir($folder.'/'.$file2)) {continue;}
if(file_exists($folder.'/'.$file2.'/doubleindemnity.gif') AND file_exists($folder.'/'.$file2.'/DOUBLEINDEMNITY.htm')) {
echo '<div class="Container">';
echo "<div class='image2'><img src='$folder/$file/doubleindemnity.gif'>";
$lines4 = file($folder.'/'.$file2.'/DOUBLEINDEMNITY.htm');
$count = count($lines4);
for($a = 0;$a < $count;$a++) {
echo substr($lines4[$a],strlen($folder),strpos($lines4[$a], '.')-strlen($folder));
}
echo "</div>";
}
echo "</div>";
}
}
?>
With that code I just get a couple of lines from the html file. I don't want that. I want the full text. And how can I use the string replace function to get rid of the code and just receive the text from the paragraphs?
Cheers:)
This piece of code will loop trough folders in a pre-defined folder (eg: /movies). It will look if whatever is inside is a folder, and if that folder has 2 files: image.png and lines.html. If it has those two files, it'll first place the image, then it'll read the HTML file, and writing down 15 random lines from that file.
<?php
$folder = "movies";
$files = scandir($folder);
foreach($files as $file) {
if($file === '.' OR $file === '..' OR $file === 'thumbs.db' OR !is_dir($folder.'/'.$file)) {continue;}
if(file_exists($folder.'/'.$file.'/image.png') AND file_exists($folder.'/'.$file.'/lines.html')) {
echo "<div class='image2'><img src='$folder/$file/image.png'>";
$lines = file($folder.'/'.$file.'/lines.html');
for($x = 1;$x<=15;$x++) {
echo $lines[rand(0, count($lines)-1)]."<br>";
}
echo "</div>";
}
}
Loops through files in $directory and then outputs 15 random lines into a html variable and if the image exists it adds it to the image html variable. If they are both added it returns the result. (untested but should work)
<?php
//I dont know where you have got some of these variables from
$directory = "Filmnoir";
$ScriptFilmNoir = "DoubleIndemnity";
$scripttype ='html';
$supportedImages = Array("png", "jpg", "jpeg");
$html = "";
$imagehtml = "";
$allFiles = scandir($folder);
$imageFound = 0;
$htmlFound = 0;
foreach($files as $file) {
if($file === '.' || $file === '..' || $file === 'thumbs.db' || is_dir($file)) {
continue;
}
$nameWithoutExtension = substr($file, 0 , (strrpos($file, ".")));
$fileExtension = $id = substr($file, strrpos($file, '.') + 1);
if($nameWithoutExtension == $ScriptFilmNoir){
if($fileExtension == $scripttype){
$htmlFound = 1;
$lines = file($directory . "/" . $ScriptFilmNoir . "." . $scripttype);//file in to an array
$range = range(1, count($lines));
$range = array_flip($range);
$range = array_rand($range, 15);
foreach($range as $line){
$html .= $lines[$value] . PHP_EOL;
}
}elseif(in_array ( $fileExtension , $supportedImages)){
$imageFound = 1;
$imagehtml = "<img src='{$directory}/{$ScriptFilmNoir}.{$fileExtension}' /><br />";
}
}
}
if($imageFound == 1 && $htmlFound == 1){
echo $imagehtml . $html;
}
I think what owen is looking for is a random extract of 15 lines rather than 15 random lines.
Using #ThijmenDF's example, just change
for($x = 1;$x<=15;$x++) {
echo $lines[rand(0, count($lines)-1)]."<br>";
}
to
$random = rand(0, count($lines)-1);
for($x = 1;$x<=15;$x++) {
echo $lines[$random + $x]."<br/>";
}

error in upload form

hello i copyed 1 upload file source code with upload progress bar
its work if i delete foreach and make 1 file for upload
but i want have 5 file field in my form
this is my code now:
$upload_directory = "$fUllp/";
//5M
$allowsize = 5242880;
foreach($_FILES as $file) {
$n = $file['name'];
$s = $file['size'];
$t = $file['type'];
$tmp = $file['tmp_name'];
if (is_array($n)) {
$c = count($n);
for ($i=0; $i < $c; $i++) {
if($s <= $allowsize){
$filename = explode('.',$n);
$filetype = $filename[1];
if(!isset($filename[2])){
$glast = mysql_query("select id from up_guest order by id desc limit 1");
$flast = mysql_fetch_array($glast);
if($flast['id'] == '' or $flast['id'] <= 0){
$flast = 1;
}
else{
$flast = $flast['id'] + 1;
}
$time = time();
$filename = $flast.'.'.$filename[1];
if(in_array($t,$allow)){
if (move_uploaded_file($tmp, $upload_directory . $filename)) {
//insert db
//img full
$fullurl = $siteurl.'/'.$upload_directory.$filename;
//for sql
$fullurlsq = '/'.$upload_directory.$filename;
$fullurlsqt = '/'.$upload_directory.'t/'.$filename;
//img resize
$image = new SimpleImage();
$image->load($upload_directory.'/'.$filename);
$image->resizeToHeight(100);
$image->resizeToWidth(100);
$image->save($upload_directory.'/t/'.$filename);
//img koochik
$imgt = $upload_directory.'/t/'.$filename;
mysql_query("insert into up_guest(name,name_t,type,time,ip) values('$fullurlsq','$fullurlsqt','$filetype',$time,'$ip')");
print '<br><div class="system-message"><ul class="index_info"><li>توضیح: <span>فایل با موفقیت آپلود شد<bR /><div class="thumb_img">';
print "<img src=\"$imgt\"></div>";
//tbl1
print '<table border="0" width="100%" cellspacing="0" cellpadding="0" class="up_box_input"><tbody><tr><td class="btitle">لینک تصویر کوچک</td><td class="all_box_link"><textarea readonly="readonly" rows="2" cols="40" class="up_input" tabindex="1" onclick="this.select();">';
print "[url=$siteurl/][img]$imgt [/img][/url]</textarea></td></tr></tbody></table>";
//tbl2
print 'echo file detaid for user';
}//file upload she
else{
echo '<div class="site_error_msg">cant up</div>';
}
}//age allow bood un file
else{
echo '<div class="site_error_msg">extention not allowed</div>';
}
}//if noghte vasatesh nabood
else{
echo '<div class="site_error_msg">you not must have . in file name</div>';
}
}//if sizesh mojaz bood
else{
echo '<div class="site_error_msg">uploaded file is more than 5 MB</div>';
}//end my code
but
its run else in first IF
i mean
if(in_array($t,$allow)){
and run this else
else{
echo '<div class="site_error_msg">uploaded file is more than 5 MB</div>';
}//end my code
so its must something wrong with
these lines and its set file name size incorect
foreach($_FILES as $file) {
$n = $file['name'];
$s = $file['size'];
$t = $file['type'];
$tmp = $file['tmp_name'];
if (is_array($n)) {
$c = count($n);
for ($i=0; $i < $c; $i++) {
ok find my nooblish problem ! i must inter my file size and name under For like this
foreach($_FILES as $file) {
$n = $file['name'];
$s = $file['size'];
$t = $file['type'];
$tmp = $file['tmp_name'];
if (is_array($n)) {
$c = count($n);
for ($i=0; $i < $c; $i++) {
$ss = $s[$i];
$tmpp = $tmp[$i];
$nn = $n[$i];
$tt = $t[$i];
if($ss <= $allowsize){
$filename = explode('.',$nn);
$filetype = $filename[1];
if(!isset($filename[2])){
$glast = mysql_query("select id from up_guest order by id desc limit 1");
$flast = mysql_fetch_array($glast);
if($flast['id'] == '' or $flast['id'] <= 0){
$flast = 1;
}
else{
$flast = $flast['id'] + 1;
}
$time = time();
$filename = $flast.'.'.$filename[1];
if(in_array($tt,$allow)){
thank you all :D

Categories