I have a page that automatically retrieves two random entries from a MySQL database and asks the user to compare them every time the page is refreshed. How can I convert those two strings into the first google image result for them automatically? This is what I have so far:
<?php //I retrieve the names and group names here//
$firstpersonaName = (string) $row["personaName"];
$firstpersonaGroupName = (string) $row["groupName"];
$firstpersonaGroupNameForGoogle = preg_split('( )', $firstpersonaGroupName);
?> //then convert any group names containing spaces into arrays here//
<?php //then here I build the query that displays a google image page//
$newname = '';
foreach ($firstpersonaGroupNameForGoogle as $firstpersonaPartofGroupName) {
$newname = $firstpersonaPartofGroupName . '+';
}
$newname = rtrim($newname, "+");
echo "https://www.google.com/search?q=" . $firstpersonaName . "+" . $newname . '&tbm=isch';
?>
This gives me stuff like: https://www.google.com/search?q=charlie+always+sunny&tbm=isch
So how do I take that link and turn it into the link of the first image? Or any of the first couple really. (In this case: http://cdn3.denofgeek.us/sites/denofgeekus/files/sunny_0.jpg)
Okay so here's what I ended up doing to randomly generate two pics per query:
First I downloaded this and added it to the same directory as the webpage: http://simplehtmldom.sourceforge.net/
Then I simply added this PHP code in the div where I wanted the picture to show up:
<?php
// Include the php dom parser
include_once 'simple_html_dom.php';
//build the google images query
$newname = '';
foreach ($firstpersonaGroupNameForGoogle as $firstpersonaPartofGroupName) {
$newname = $firstpersonaPartofGroupName . '+';
}
$newname = rtrim($newname, "+");
//echo "https://www.google.com/search?q=" . $firstpersonaName . "+" . $newname . '&tbm=isch';
$newname = "https://www.google.com/search?q=" . $firstpersonaName . "+" . $newname . '&tbm=isch';
//use parser on queried page
$html = file_get_html($newname);
//echo $html;
//create an array for all pics on page
$picarray = array();
$picurl = '';
// Find all images
foreach($html->find('img') as $element) {
//echo $element->src . '<br>';
$picurl = $element->src;
array_push($picarray,$picurl);
}
//then pick two random ones
$picurl = $picarray[array_rand($picarray)];
echo "<img src=" . $picurl . ">";
$picurl = $picarray[array_rand($picarray)];
echo "<img src=" . $picurl . ">";
?>
They're pretty small resolution (about 150px) but that actually works great with what I'm trying to do. If you wanted to retrieve a non-thumbnail pic that's a whole different can of worms.
Related
I have image thumbnails in 100s of directories. I am using PHP to retrieve the images. A bootstrap modal with id #imagePalette window pops up on clicking a button and displays all the images in the directory.
In javascript
$.post('getCroppedImages.php',{'location': location, 'brand':brand},function(data) {
var imagemodal = $('#imagePalette');
imagemodal.find('.modal-title').html('Brand: ' + brand + ' in ' + location);
imagemodal.find('.modal-body').html(data).show();
});
PHP code that retrieves the images:
$path = "projects/" . $database . '/' . $match . '/' . $location . '/' . $brandname . '/*.jpg';
$files = glob($path);
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
$filname = basename($num, ".jpg");
$imgname = basename($num);
$img = $path . $imgname;
$filnam = substr($filname, -9,9);
$filnam = rtrim($filnam);
echo '<ul class="croppeditem" id="croppeditem">';
echo '<li style="list-style:none;cursor:pointer" ><img onclick="clickCroppedImage(this.id); return false"; src="'.$num.'" id="'.$filnam.'"/>';
echo '<figcaption class="caption" name="caption">' . $filnam . '</figcaption>';
echo '</li></ul>';
}
The above code works perfectly. It displays the images. I have a function clickCroppedImage attached to each image. When the user clicks on a image in the modal window, this function triggers another php that deletes the image from the folder.
This deletion also works without any trouble. I am trying to refresh the modal modal without closing it so that the current set of images in the folder gets displayed. I have written similar php and javascript code and used unlink to delete the image from the folder.
In Javascript
$.post('deleteAnnCroppedImage.php', {'folder':wd, 'matchLst':matchLst, "imgPath" : clickedImg, 'currentAnnotCheckLocation': currentAnnotCheckLocation, 'currentAnnotCheckBrand': currentAnnotCheckBrand}, function(data){
//imagemodal.find('.modal-body').html().show();
var imagemodal = $('#imagePalette');
imagemodal.find('.modal-body').html("");
imagemodal.find('.modal-body').html(data).show();
});
PHP Code
$currentAnnotPath = "projects/" . $database . '/' . $match . '/' . $location . '/' . $brandname . '/*.jpg';
$files = glob($currentAnnotPath);
$imgPath = $_POST['imgPath'];
unlink($imgPath);
//echo "Deleted Image";
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
$filname = basename($num, ".jpg");
$imgname = basename($num);
$img = $currentAnnotPath . $imgname;
$filnam = substr($filname, -9,9);
$filnam = rtrim($filnam);
echo '<ul class="croppeditem" id="croppeditem">';
echo '<li style="list-style:none;cursor:pointer" ><img onclick="clickCroppedImage(this.id); return false"; src="'.$num.'" id="'.$filnam.'"/>';
echo '<figcaption class="caption" name="caption">' . $filnam . '</figcaption>';
echo '</li></ul>';
}
The php scripts returns the ul li data correctly which I can print to console. However, I am not able to refresh the modal body and display the returned images. I tried different combinations, but the modal window does not show any reaction.
How do I clear the modal body and reload the images without closing the modal window?
You will have to use AJAX if I understood your problem correctly.
After a user deleted an image you have to trigger a AJAX request and change the content of the modal.
A good introduction to AJAX can be found via google.
Best regards
You should be able to reach the modal-body element.
First of all make sure you can see it from the current function scope.
Sample codes that are working with the basic bootstrap modal:
Pure JS:
document.getElementsByClassName('modal-body')[0].innerHTML = '<p>some html</p>';
jQuery:
$('#imagePalette .modal-body:first').html('<p>some html</p>');
If there is an iFrame and the modal is inside than you should get into the iFrame document first from JavaScript.
Other:
In these cases you can use jQuery wrapper instead of introducing a new variable. You won't loose performance but it will make this code more readable.
I'm trying to add a script element to the HTML from the PHP code and instantly remove it so it won't be visible in the HTML. The script only contains things to execute at the same moment and not functions. Generally, I'm trying to replicate ASP.NETs runat property, so I'll be able to set values of elements (inputs for now) right from the PHP code.
This is what I tried so far (which I found in a different question, with some changes of mine) and it adds the script properly, but won't remove it.
function JSSetValue($id, $value) // Input 'value' only
{
echo '<script>
var input = document.getElementById("' . $id . '");
input.value = "' . $value . '"
</script>';
$html = <<<HTML
...
HTML;
$dom = new DOMDocument();
$dom->loadHTML($html);
$script = $dom->getElementsByTagName('script');
foreach($script as $item)
{
$item->parentNode->removeChild($item);
break;
}
$html = $dom->saveHTML();
}
Thanks for everyone who were trying to help. Anyway, I found a solution to my question, which is this:
function JSSetValue($id, $value) // Input 'value' only
{
echo '<script id="phpjs">
var input = document.getElementById("' . $id . '");
input.value = "' . $value . '";
document.getElementById("phpjs").remove();
</script>';
}
It adds the script and removes it, so it won't be visible when inspecting elements anymore.
I am developing a simple image gallery which shows images and related caption.
All images are inside a directory and caption in another (as single files). A php script lists all files in both directories and pass arrays to a javascript wich change image and caption when the user press a button.
[...]
for($x = 2; $x < $lenght; $x++) {
$filesi[$x] = $imgdirectory."/".$lsi[$x];
}
for($x = 2; $x < $lenght; $x++) {
$filename = $capdirectory."/".$lsc[$x];
$filesc[$x] = file_get_contents($filename);
}
//Create array for JS
$captions = '["' . implode('", "', $filesc). '"]';
$images = '["' . implode('", "', $filesi). '"]';
?>
<script>
var captions = <?php echo $captions; ?>;
var images = <?php echo $images; ?>;
[...]
Images work properly and I can also print caption's file name instead of caption
i.e.
$filesc[$x] = $filename;
but when I use "file_get_contents()" to read file the gallery stops working.
If I echo $captions and manually set $captions with the very same output
e.g.
$captions='["first caption","second caption", "..."]';
the gallery works properly, so the array should be properly formatted...
Thank you in advance
SOLUTION
I was creating an array with two empty elements (0,1) in order to avoid ./ and ../ in file list, so I have added a +2 to the lsi index.
for($x = 0; $x < $lenght-2; $x++) {
$filesi[$x] = $imgdirectory."/".$lsi[$x+2];
}
In addition I have used json_encode, as suggested, instead of manual json encodig. The output seems to be the same but now the gallery works!
var images = <?php echo json_encode($filesi); ?>;
In JS you have to escape new lines in strings like this:
var multilineString = "this is\
just an example";
Maybe try to use trim() and str_replace() if you don't want to make it easier with json_encode().
UPDATE
Then I was wrong. Did you know that you can push items to arrays with just $array[] = 'item';?
I am writing a hybrid app using Visual Studio with Cordova exetnstion and trying to pull data from www.a.com/b.php
My b.php code is:
<?php
// Connect to database server
mysql_connect("http://www.yo.com", "ya", "ye") or die (mysql_error());
// Select database
mysql_select_db("oh") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM Properties ORDER BY number DESC";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
echo '<select name="Address" id="address_search" style="width:282px; display:block;" required>';
while($row = mysql_fetch_array($rs))
{
// Write the value of the full address including unit code, address, city, state, zipcode (which is now in the array $row)
echo '<option value="'. $row['number'] . ", " . $row['address'] . ", " . $row['city'] . ", " . $row['state'] . ", " . $row['zipcode'] .'">'
. $row['number'] . ", " . $row['address'] . ", " . $row['city'] . ", " . $row['state'] . ", " . $row['zipcode'] .
'</option>';
}
echo '</select>';
// Close the database connection
mysql_close();?>
I already add select tag form directly in php code, but I don't know how to display the whole select box (with options being retrieved data) in .html.
Any help or tutorial? Thanks.
I have solved this issue like this:
First, in the server side-code (php in this case), in "file.php", I have an array with the database elements and I do the following:
$arrayElements = json_encode($arrayElements );
echo $_GET['jsoncallback'] . '(' . $arrayElements . ');';
After that, in the app js code, I use jQuery method $.getJSON() for getting the php array we prepare before. When the function get the server answer, then execute the code inside. Note that the variable "respuestaServer" is the array you have sent from php file, so you can go throw it with a loop and taking its values to your select (if you need to pass variables to your php file and receive them via GET just add the js variables inside the {}, in this example I send the variable datosUsuario and in php I receive it $_GET['usuario']).
var archivoValidacion = "http://example.com/file.php?jsoncallback=?";
var select = document.getElementById("idSelect");
$.getJSON( archivoValidacion, { usuario:datosUsuario ,password:datosPassword})
.done(function(respuestaServer) {
for(var i = 0; i < respuestaServer.length;i++){
var option = document.createElement("option");
var textNode = document.createTextNode(respuestaServer[i]);
option.appendChild(textNode);
select.appendChild(option);
}
})
I hope this can help you. If you have some questions just tweet me #ulisesveraes ;)
it is not clear how you call this code
I suppose you do this with jQuery ajax function
so your code will like something this
$('box-selector').load('b.php');
Basically I am trying to create a photo slideshow that will display specific photos depending on the userid. These photos will be stored in the directory of my web server space. Currently I have a html (not changed into php) file with basic html layout, css style sheet and an external js file that has my code that makes the photos fade in and out. I have added php at the bottom of my html. This is what I have:
$user_id = $_GET['userid'];
print "<h1> Hi, $user_id </h1>";
function returnimages($dirname = "Photos/1") { //will replace 1 with userid once something starts working
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";';
$curimage++;
}
}
closedir($handle);
}
return($files);
}
echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
and in my javscript, the code I had before for the array of photos:
// List of images for user one
var userphoto = new Array();
userphoto[0] = "Photos/1/1.jpg";
userphoto[1] = "Photos/1/2.jpg";
userphoto[2] = "Photos/1/1.jpg";
userphoto[3] = "Photos/1/1.jpg";
userphoto[4] = "Photos/1/1.jpg";
which I have now commented out and replaced it with this:
var userphoto = <? echo json_encode($galleryarray); ?>;
I am hoping to be able to change the src of photodisplay with the new array:
photodisplay[x].attr("src", userphoto[x]);
Sorry if my problem is not clear at all. I am very confused myself. :( hopefully someone can help!
$user_id = (int) $_GET['userid'];
print "<h1> Hi, $user_id </h1>";
function returnimages($dirname = "Photos/1") {
$dirname = str_replace('..', '.', $dirname); //only remove this if you know why it's here
$pattern = "*{.jpg,.png,.jpeg,.gif}"; //valid image extensions
return glob($dirname . DIRECTORY_SEPARATOR . $pattern, GLOB_BRACE);
}
echo "var galleryarray = ".json_encode(returnimages()).";\n";
?>
Also, you should use <?= json_encode($ret) ?> because the PHP short tag (<?) is deprecated, but <?= is not, and is the equivalent of <?php echo.