So, this is the only issue I am having left to fix on my site. When it fetches a post from the database and is then called to parse/replace the URL as a it has a problem. The problem is only with duplicates or image names containing a space in them.
$result = mysql_query("SELECT * FROM posts ORDER BY postid DESC");
while($row = mysql_fetch_array($result))
{
$str = $row['post_content'];
$str = preg_replace_callback('#(?:https?://\S+)|(?:www.\S+)|(?:\S+\.\S+)#', function($arr)
{
if(strpos($arr[0], 'http://') !== 0)
{
$arr[0] = 'http://' . $arr[0];
}
$url = parse_url($arr[0]);
// images
if(preg_match('#\.(png|jpg|gif)$#', $url['path']))
{
return '<img src="'. $arr[0] . '" /><br /><br />';
}
Here is what it does for the first uploaded image:
http://domain.com/server/php/files/filename.jpg
Here is what it does for the second uploaded image:
http://domain.com/server/php/files/filename http://(1).jpg
I need to either control the naming convention for how names the file or control how it reads the spaces in the URL.
in your post there are two question :
How to read spaces in url
answer : you can use urlencode() function.
naming convention for file
there may be following options :
a. either don't allow space in file name . remove space with the help of regex
b. either check the file name first in db, if it exist then append 1 or 2 in filename.
if you have any question, let me know
Related
I have a folder (blogfiles/posts) with various text files, numbered (1.txt, 2.txt, 3.txt...) and they each hold a post for a blog (I haven't learned SQL yet). I'm trying to make a search engine for it that will take a query from a text box (done with this part), then search the files for each word in the query, and return the results (possibly in order of the number of times the word occurs).
Each text file looks like this:
Title on Line 1
Date Posted on Line 2 (in Month Date, Year form)
Post body to search on lines 3 and up
I currently have this code:
<?php
$q = $_GET["q"];
$qArray = explode(" ", $q);
//preparing files
$post_directory = "blogfiles/posts/";
$files = scandir($post_directory, 1);
$post_count = (count($files)) - 2;
$files = array_pop($files); // there are 2 server files I want to ignore (#1)
$files = array_pop($files); // there are 2 server files I want to ignore (#2)
foreach ($files as $file) {
//getting title
$post_path = $post_directory . $file;
$post_filecontents = file($post_path);
$post_title = $post_filecontents[0];
echo "<tr><td>" . $post_title . "</td></tr>";
}
if ($post_count > 2) {
$postPlural = "s";
}
echo "<tr><td>" . $post_count . " post" . $postPlural . ".";
?>
I'll apologize now for the formatting, I was trying to separate it to troubleshoot.
Any help to get this working would be greatly appreciated.
There are many ways to search files.
use preg_match_all function to match pattern for each file.
use system() function to run external command like grep (only available under *nix).
use strpos function ( not recommended because of low performance and lack of support of pattern ).
If you will face a big traffic you'd better use pre-build indexes to accelerate the search. for example split the posts into tokens ( words ) and add position info along with the words, when user search the some words you can just split the words first and then look for the indexes. It's simpler to discribe this method than to implement it. You may need a existing full-text search engine like Apache Lucene.
I've put together some code to search through a directory and for all the jpg images it finds, display thumbnails and my required iptc and exif info.
The problem is that I have many, many directories of photos and as it is I need an index.php file for each one.
My directories are named by month and year; "1401" for January 20014, "1402" for Feb etc. and I have a set of shortcut images for each one called "1401.jpg", "1402.jpg" etc.
so I use this code for users to nagivate to other directories where $shortcut has the values of 1401, 1402 etc:
echo("<img src=\"shortcutimages/" . $shortcut . "\">");
I'd love to allow users to navigate in a similar way without needing multiple index.php files.
I would guess the best way is as follows:
On a mouseclick on a link like above, the main php (similar to below) should be re-run, replacing what's currently displayed on the screen but with new value for $dir replaced with something like $dir="../" . $shortcut;
Is this the way to do it? As a newbie I apologise if this is really simple but as it is I can't seem to work it out.
thanks in advance for your help,
Sivadas
$dir="."; // or other folder path of choice!
$jpgcount=0;
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($image = readdir($dh)) !== false)
{
if (preg_match("/.jpg/", $image)) // only use .jpg files
{
$image=$dir . "/" . $image;
$exif = exif_read_data($image, 0, true);
$exif_name = $exif['FILE']['FileName'];
if(isset($exif['EXIF']['DateTimeOriginal']))
{
$timestamp = $exif['EXIF']['DateTimeOriginal'];
}
else
{
$timestamp = "1971:01:01 01:01:01"; // puts in a datestamp if one doesnt exist
}
$datename[] = $timestamp . $exif_name; // create array of date+name to allow sorting by date then retrieval of date ordered names once datestamp is removed
$jpgcount++; // counts number of jpgs in folder
}
}
sort($datename); // sort date+name array by date
for($c=0; $c<$jpgcount; $c++)
{
$image = pythonslice("$datename[$c]","19:"); // function strips off the datestamp (1st 19 characters) to leave the filename (taken from www.php.net/manual/en/function.substr.php slow at acedsl dot com)
$image=$dir . "/" . $image;
$size = getimagesize("$image", $info);
echo("<tr><td valign=top> <IMG border=0 src=showthumb.php?image=" . str_replace(' ', '%20', $image) ."><td><td valign=top><font size=-1 face=\"Arial Narrow\">"); // get thumbnail and link to full image
show_metadata($image,$info); // function to display all required metadata
echo "</font></td></tr>";
}
closedir($dh);
}
}
I have a folder unit_images that is full of images with random names except they have a prefix that corresponds to a PRIMARY KEY in a db table.
1_4534534fw4.jpg
2_43534tw4t45.png
You get my point. I am using YoxView to view images and am doing something like this:
<?php
$query = "SELECT id FROM images WHERE unit = ".$_GET['id']."";
$result = mysqli_query($con, $query);
echo '<div class="yoxview">';
while ($row = mysqli_fetch_assoc($result))
{
echo '<img src="unit_images/01.jpg" alt="First" title="First image" />
<img src="unit_images/02.jpg" alt="Second" title="Second image" />'
}
echo '</div>';
?>
I want to list the images from my folder unit_images WHERE the unit is the one currently being shown.I just do not know how to tell PHP the filename. I want to do something similar to a 1_% in SQL. Does that make sense? Since I do not know what the rest of the filename looks like I just need to tell php it doesn't matter.
The closest equivalent to SQL's % wildcard that works for files is the shell's * wildcard, which is available in php through the glob() function. You can iterate through its results as follows:
foreach (glob("unit_images/1_*.jpg") as $filename) {
echo '<img src="unit_images/' . htmlspecialchars(basename($filename))
. '" />';
}
If I understand you correctly, you want to get a list of items in a directory with a certain prefix.
Step 1 (use sandir() to determine the items in the directory):
$files = scandir('unit_images');
Step 2 (eliminate the unwanted image names):
for ($i=0; $i<count($files); i++)
{
$file = $files[i];
$prefix = explode("_", $file)[0];
if ($prefix != $_GET['id'])
{
unset($files[i]);
}
}
$files is now an array of only the file names prefixed with $_GET['id]
My advice would be to store the whole name of the file in a column so that you can reference it directly instead of having to search in the file system for a matching name.
Having said that, you can search for a file using the glob PHP function.
Maybe you can do something like this:
glob("unit_images/<YOUR_PRIMARY_KEY>_*.{png,jpg}", GLOB_BRACE);
My website has an image in a certain place and when a user reloads the page he should see a different image on the same place. I have 30 images and I want to change them randomly on every reload. How do I do that?
Make an array with the "picture information" (filename or path) you have, like
$pictures = array("pony.jpg", "cat.png", "dog.gif");
and randomly call an element of that array via
echo '<img src="'.$pictures[array_rand($pictures)].'" />';
Looks weird, but works.
The actual act of selecting a random image is going to require a random number. There are a couple of methods that can help with this:
rand() is used to generate a random number.
array_rand() is used to select a random element's index from an array.
You can think of the second function as a shortcut for using the first if you're specifically dealing with an array. So, for example, if you have an array of image paths from which to select the one you want to display, you can select a random one like this:
$randomImagePath = $imagePaths[array_rand($imagePaths)];
If you're storing/retrieving the images in some other way, which you didn't specify, then you may not be able to use array_rand() as easily. But, ultimately, you need to generate a random number. So some use of rand() would work for this.
If you store the information in your database, you can also SELECT a random image:
MySQL:
SELECT column FROM table
ORDER BY RAND()
LIMIT 1
PgSQL:
SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1
Best,
Philipp
An easy way to create random images on popup is this method below.
(Note: You have to rename the images to "1.png", "2.png", etc.)
<?php
//This generates a random number between 1 & 30 (30 is the
//amount of images you have)
$random = rand(1,30);
//Generate image tag (feel free to change src path)
$image = <<<HERE
<img src="{$random}.png" alt="{$random}" />
HERE;
?>
* Content Here *
<!-- Print image tag -->
<?php print $image; ?>
This method is simple and I use this every time when I need a random image.
Hope this helps! ;)
I've recently written this which loads a different background on every pageload. Just replace the constant with the path to your images.
What it does is loop through your imagedirectory and randomly picks a file from it. This way you don't need to keep track of your images in an array or db or whatever. Just upload images to your imagedirectory and they will get picked (randomly).
Call like:
$oImg = new Backgrounds ;
echo $oImg -> successBg() ;
<?php
class Backgrounds
{
public function __construct()
{
}
public function succesBg()
{
$aImages = $this->_imageArrays( \constants\IMAGESTRUE, "images/true/") ;
if(count($aImages)>1)
{
$iImage = (int) array_rand( $aImages, 1 ) ;
return $aImages[$iImage] ;
}
else
{
throw new Exception("Image array " . $aImages . " is empty");
}
}
private function _imageArrays( $sDir='', $sImgpath='' )
{
if ($handle = #opendir($sDir))
{
$aReturn = (array) array() ;
while (false !== ($entry = readdir($handle)))
{
if(file_exists($sDir . $entry) && $entry!="." && $entry !="..")
{
$aReturn[] = $sImgpath . $entry ;
}
}
return $aReturn ;
}
else
{
throw new Exception("Could not open directory" . $sDir . "'" );
}
}
}
?>
I have my root folder, and within my root folder is a folder named images.
Within the images folder is 4 subfolders, each named after a Suit of cards.
Within each Suit folder, I have 13 pictures named after cards. Ace.jpg, Two.jpg, etc.
Within my Code, I declare each suit and card as a variable.
/*Array used to select a random number*/
$CardNumber = array();
$CardNumber[0]="Ace";
$CardNumber[1]="Two";
$CardNumber[2]="Three";
$CardNumber[3]="Four";
$CardNumber[4]="Five";
$CardNumber[5]="Six";
$CardNumber[6]="Seven";
$CardNumber[7]="Eight";
$CardNumber[8]="Nine";
$CardNumber[9]="Ten";
$CardNumber[10]="Jack";
$CardNumber[11]="Queen";
$CardNumber[12]="King";
/*Array used to select a random suit.*/
$CardSuit = array();
$CardSuit[0]="Clubs";
$CardSuit[1]="Diamonds";
$CardSuit[2]="Hearts";
$CardSuit[3]="Spades";
After a player picks a Card and a Suit, is there anyway to display the card he chose?
E.G. If You picked the 5 of Clubs, it would display the picture named Five.jpg from the Clubs folder?
As far as I understand you just need to create an image tag with the src pointing to the right file in the right directory...
$suit = 'Hearts';
$card = 'Queen';
printf('<img src="%s/%s.jpg">', $suit, $card);
I guess you could do the following if you want to pick a random card
$CNkey = array_rand($CardNumber);
$CSKey = array_rand($CardSuit);
$randomCardNumber = $CardNumber[$CNKey];
$randomCardSuit = $CardSuit[$CSKey];
$image = '/images/' . $randomCardSuit . '/' . $randomCardNumber . '.jpg'; // or any other image extensions
echo '<img src="' . $image . '">';