Hey fellow programmers,
What I'm trying to accomplish is a dynamic way to source images from a directory with the use of a class image.
I'm stuck at supplying an exact string which returns a match but when trying to echo " with the returned match if the whole string is not provided then the image is linked with a partial string plus the extension.
<?php $image = new image; ?>
calling the class function with:
<?php $image -> get_image('this_string_1',''); ?>
The Image directory contents
<?php $path = $_SERVER['DOCUMENT_ROOT'].'/images/;'?>
this_string_1.png
this_string_2.png
this_string_3.png
The class:
<?php
class image{
function get_image($name,$class){
if(strlen($class)==0){ $class="default"; }
####[ Checks the type of image
global $doc_root,$html_path;
if($handle = opendir($doc_root.'/images/')){
while(false !==($value = readdir($handle))){
if($value !== '..' && $value!=='.'){
$extention;
$ext_jpeg = substr($value,-3);
if($ext_jpeg=='jpg'){
$extention=".jpg";
}
$ext_png = substr($value,-3);
if($ext_png=='png'){
$extention=".png";
}
$ext_gif = substr($value,-3);
if($ext_gif=='gif'){
$extention='.gif';
}
}
switch($extention){
case '.jpg':
if(preg_match("/$name/",$value,$result)){
foreach($result as $jpg){
echo '<img class="'.$class.'" src="'.$html_path.'/images/'.$jpg.'.jpg">';
}
}
break;
case '.png':
if(preg_match("/$name/",$value,$result)){
foreach($result as $png){
echo '<img class="'.$class.'" src="'.$html_path.'/images/'.$png.'.png">';
}
}
break;
case '.gif':
if(preg_match("/$name/",$value,$result)){
foreach($result as $gif){
echo '<img class="'.$class.'"src="'.$html_path.'/images/'.$gif.'.gif">';
}
}
break;
}
}
}
}
}
?>
I'm sure there are many ways to accomplish something like this. Any advice would be greatly appreciated.
As per Martins advice.
I have removed the if and switch statements and replaced it with "substr" in the second if statement.
<?php
class image{
function get_image($name,$class){
if(strlen($class)==0){ $class="default"; }
global $doc_root,$html_path;
if($handle = opendir($doc_root.'/images/')){
while(false !==($value = readdir($handle))){
if($value !== '..' && $value!=='.' && substr($value, 0, -4)==$name){
echo '<img src="'.$html_path.'/images/'.$value.'">';
}
}
}
}
}
?>
1) I do not see much point of your sequence of if statements to assign $extention. Why don't you just do $extention = substr($value,-4)?
2) The switch($extention) has to be inside the if($value !== '..' && $value!=='.')
3) What are you trying to achieve by the preg_match?
If you just want to match name completely, just do substr($value, 0, -4) == $name. Well this rely on extension having 3 characters, what's not perfect, but you rely on that already.
Related
I have made a php script that searches a whole directory with text files in it, everything works fine, except that it is case sensitive. How would i search without it being case sensitive? Here's the code i have so far:
<?php
$query = $_POST['search'];
if ($handle = opendir('posts')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "<p>$entry ";
$file = file_get_contents('posts/'.$entry, FILE_USE_INCLUDE_PATH);
$check_str = strpos($file,$query);
if ($check_str == 0) {
print "not found</p>";
} else {
print "found</p>";
}
}
}
closedir($handle);
}
?>
Yeah, stripos() is what you're looking for. Here's the manual page.
You are maybe looking for strtolower , :
How may i able to retrieve different file extensions in a certain directory. Let say i have a folder named "downloads/", where inside that folder are different types of files like PDFs, JPEGs, DOC files etc. So in my PHP code i wanted those files be retrieved and listed with there file names and file extensions. Example: Inside "downloads/" folder are different files
downloads/
- My Poem.doc
- My Photographs.jpg
- My Research.pdf
So i wanted to view those files where i can get there file names, file extensions, and file directories. So in view will be something like this
Title: My Poem
Type: Document
Link: [url here]
Title: My Photographs
Type: Image
Link: [url here]
Title: My Research
Type: PDF
Link: [url here]
Anyone knows how to do it in php? Thanks a lot!
It's pretty simple. To be honest i don't know why didn't you searched on a php.net. They got whole lots of examples for this. Check it in here: click
Example:
<?php
function process_dir($dir,$recursive = FALSE) {
if (is_dir($dir)) {
for ($list = array(),$handle = opendir($dir); (FALSE !== ($file = readdir($handle)));) {
if (($file != '.' && $file != '..') && (file_exists($path = $dir.'/'.$file))) {
if (is_dir($path) && ($recursive)) {
$list = array_merge($list, process_dir($path, TRUE));
} else {
$entry = array('filename' => $file, 'dirpath' => $dir);
//---------------------------------------------------------//
// - SECTION 1 - //
// Actions to be performed on ALL ITEMS //
//----------------- Begin Editable ------------------//
$entry['modtime'] = filemtime($path);
//----------------- End Editable ------------------//
do if (!is_dir($path)) {
//---------------------------------------------------------//
// - SECTION 2 - //
// Actions to be performed on FILES ONLY //
//----------------- Begin Editable ------------------//
$entry['size'] = filesize($path);
if (strstr(pathinfo($path,PATHINFO_BASENAME),'log')) {
if (!$entry['handle'] = fopen($path,r)) $entry['handle'] = "FAIL";
}
//----------------- End Editable ------------------//
break;
} else {
//---------------------------------------------------------//
// - SECTION 3 - //
// Actions to be performed on DIRECTORIES ONLY //
//----------------- Begin Editable ------------------//
//----------------- End Editable ------------------//
break;
} while (FALSE);
$list[] = $entry;
}
}
}
closedir($handle);
return $list;
} else return FALSE;
}
$result = process_dir('C:/webserver/Apache2/httpdocs/processdir',TRUE);
// Output each opened file and then close
foreach ($result as $file) {
if (is_resource($file['handle'])) {
echo "\n\nFILE (" . $file['dirpath'].'/'.$file['filename'] . "):\n\n" . fread($file['handle'], filesize($file['dirpath'].'/'.$file['filename']));
fclose($file['handle']);
}
}
?>
You could use glob & pathinfo:
<?php
foreach (glob(__DIR__.'/*') as $filename) {
print_r(pathinfo($filename));
}
?>
You will try this code :
$Name = array();
$ext = array();
$downloadlink = array();
$dir = 'downloads'
while ($file= readdir($dir))
{
if ($file!= "." && $file!= "..")
{
$temp = explode(".",$file);
if (count($temp) > 1)
{
$Name[count($Name)] = $temp[0];
swich($ext)
{
case "doc" :
{
$ext[count($ext)] = "Document";
break;
}
[...]
default :
{
$ext[count($ext)] = "Error";
break;
}
}
$downloadlink[count($downloadlink)] = "http://yourdomain.com/".$dir."/".$file;
}
}
}
closedir($dir);
for($aux = 0; $aux < count($Name); $aux++)
{
echo "Name = " . $Name[$aux]."<br />
Type = " . $ext[$aux]."<br/>
Link = " . $downloadlink[$aux]."<br/>
";
}
I have a folder that contains logos for sponsors. In my website, a user can belong to a sponsor and the sponsor_id is set in session when the user logs in.
Here is my code:
function sponsor_logos($sponsor_id) {
$logos = glob("resources/content/sites/{$sponsor_id}*");
foreach($logos as $logo) {
if(file_exists("{$logo}"))
echo "<img src='/{$logo}' />";
}
}
The above works, but a sponsor can have multiple logos. So the multiple logos are saved like so: sponsor_id.jpg, sponsor_id_2.jpg, sponsor_id_3.jpg
I am not the strongest at regex, so any help is greatly appreciated! thanks!
You better open directory and check all files in it (if there are not so much files). You could do it like that:
function sponsor_logos($sponsor_id) {
if ($dh = opendir('resources/content/sites/')) {
while (($file = readdir($dh)) !== false) {
if(strpos($file, $sponsor_id . '.') === 0) {
$sponsor_files[] = $file;
}
else if(strpos($file, $sponsor_id . '_') === 0) {
$sponsor_files[] = $file;
}
}
closedir($dh);
}
foreach($sponsor_files as $logo) {
echo "<img src='resources/content/sites/" . $logo . "' />";
}
}
But best solution is to have normal naming scheme.
use this regex sponsor_id(_\d+)?\.jpg
I used the following code to display the contents of a Folder say images (Both Directories as well as Files in that folder)
<?php
$dir="images/"; // Directory where files are stored
if ($dir_list = opendir($dir))
{
while(($filename = readdir($dir_list)) !== false)
{
$newvar1="$dir$filename";// For Hyperlink Path
?>
<p><a href="<?php echo $newvar1; ?>"><?php echo $filename;
?></a></p>
<?php
}
closedir($dir_list);
}
?>
But the PHP file shows an output with two additional Links
A link to the folder 'images' and
A Link to the 'Homepage'.
I tried to filter those two links with "filesize" function but getting some error.
How can I resolve this?
Skip current dir and parent dir with a check.
while(...) {
if($filename == ".." || $filename == ".") continue;
...
}
Modify your code to something like this:
while(($filename = readdir($dir_list)) !== false)
{
if($filename != '.' || $filename != '..') // This part to check and ignore
$newvar1="$dir$filename";// For Hyperlink Path
else
continue; //while loop will no further be processed!
//...
}
This is a more in-depth answer and I'm so fed up with such things... This is absolutely an horrible piece of code, even though Php does permit such horrible things.
Something like this is easier to read, easier to maintain, and easier to debug:
<?php
$tab = array();
$dir="images/"; // Directory to parse
if ($dir_list = opendir($dir))
{
while(($filename = readdir($dir_list)) !== false)
{
if($filename != ".." && $filename != ".")
{
$tab[$filename] = $dir.$filename; // Hyperlink Path
}
}
closedir($dir_list);
}
/* Display separated from logic */
foreach ($tab as $filename => $hyperlink)
{
echo '<p>'.$filename.'</p>';
}
?>
More compact but a bit less easy to read:
<?php
$tab = array();
$dir="images/"; // Directory to parse
if ($dir_list = opendir($dir)) {
while(($filename = readdir($dir_list)) !== false) {
if($filename != ".." && $filename != ".") {
$tab[$filename] = $dir.$filename; // Hyperlink Path
}
}
closedir($dir_list);
}
/* Display separated from logic */
foreach ($tab as $filename => $hyperlink) {
echo '<p>'.$filename.'</p>';
}
?>
And some people (including my old teachers) tell that "if there's one line of code, don't use {}" (which I strongly disagree because it may lead to errors later on) but here's the "optimized" version:
<?php
$tab = array();
$dir="images/";
if ($dir_list = opendir($dir)) {
while(($filename = readdir($dir_list)) !== false)
if($filename != ".." && $filename != ".")
$tab[$filename] = $dir.$filename; // Hyperlink Path
closedir($dir_list);
}
foreach ($tab as $filename => $hyperlink)
echo '<p>'.$filename.'</p>';
?>
I've got a function below which reads the contents of wp-content/uploads and writes out all images that it finds there.
The problem is that it's reading off the blog title to determine the image path and when the blog title has a dot in it, there's trouble
Blog title is abc123.com
site url is abc123.com
test image filename is abc123-1.jpg
img tag SHOULD become:
<img src='http://abc123.com/wp-content/uploads/abc123-1.jpg' />
actual image tag written from the function below is:
<img src='http://abc123.com/wp-content/uploads/abc123.com-1.jpg' />
My question is, how did the ".com" get inserted into the filename???
Function follows...
function get_images()
{
global $options;
foreach ($options as $value) {
if (get_settings( $value['id'] ) === FALSE) { $$value['id'] = $value['std']; } else { $$value['id'] = get_settings( $value['id'] ); }
}
if($cb_custom_images !== "")
{
echo $cb_custom_images;
}
else
{
$dir = 'wp-content/uploads/';
$url = get_bloginfo('url').'/wp-content/uploads/';
$imgs = array();
if ($dh = opendir($dir))
{
while (($file = readdir($dh)) !== false)
{
if (!is_dir($file) && preg_match("/\.(bmp|jpeg|gif|png|jpg|)$/i", $file))
{
array_push($imgs, $file);
}
}
closedir($dh);
} else {
die('cannot open ' . $dir);
}
foreach ($imgs as $idx=>$img)
{
$class = ($idx == count($imgs) - 1 ? ' class="xlast"' : '');
echo '<img src="' . $url . $img . '" alt="' .$img . '"' . $class . ' />';
}
}
}
Are you sure your test file is named abc123-1.jpg? I just copied your code into a file and added dummy scaffolding, including a wp-content/uploads/abc123-1.jpg file.
I got the correct result when I ran the script:
% php img.php
<img src="http://abc123.com/wp-content/uploads/abc123-1.jpg" alt="abc123-1.jpg" class="xlast" />
`
I think it is preg_match issue try to remove character after jpg
Is there a abc123.com-1.jpg file in that directory?
That could be the problem.
Sorry about this one guys, nothing wrong with the function. I had a legacy file that this file relied on that was incompatible. After updating that file, all is well.
Now I just have to figure this one out (assuming I've got any cred left after this one :-) Do we get mulligans around here?