auto hyper-link - php

I am trying to auto generate pages.
What I am trying to do is make a upload form for an image upload that's displayed in a gallery.
I have this but I then want each image to have a page hyper-link auto made for each image where the image can be seen bigger with buying information that's also been uploaded to a MySQL table not 100% with codeigniter I am still luring please look at the site I am trying to build at http://www.fresherdesign.co.uk/PIFF/index.php/main/gallery
This is a direct link to the gallery that I would link to make the page's from, currently they just open a direct link to the image on its own
Any help would be awesome thanks to everyone in advance
Alan Morton

If you want the actual images to be uploaded (and not stored in the database - note that db storage is slightly more difficult to accomplish than your standard upload), you can create a field in the database for the image's location; that is how you are going to correspond your image data with your page content.
Now, if you want a hyperlink to automatically be made, I suggest querying the database of all "Active" entries (again, could be another field unless you simply delete old entries). Each entry should have a unique ID associated with it. This way, when you give the list, simply include a tag similar to
while($row = mysql_fetch_array($query_result)){
// Change this to whatever formatting you need
print '<!-- Whatever content for link -->';
}
Now that's just your loop to get the results. The actual page now should query the database based on the ID given. The query should grab the page content from the database. Something like this would work
<?php
if(!isset($_GET['id'])){
die("Please use a valid link!");
}
$q = mysql_query("SELECT * FROM YOUR_DB_TABLE WHERE ID='".mysql_real_escape_string($_GET['id'])."' LIMIT 1;");
if(!$q || mysql_num_rows($q) < 1){
die("A MySQL Error Occurred: ".mysql_error());
}
while($row = mysql_fetch_array($q)){
// Again, adjust this accordingly
print "Data column 1: ".$row['DataRow1']."<br />".
"Data Column 2: ".$row['DataRow2']."<br />".
"<img src='".$row['ImageLocation']."' />";
}
?>
Now, I haven't tested this exact code, however all of it should work as is. But you will need to adjust it appropriately to fit your requests; but this is one way to accomplish what you're looking for.

Precondition
You'll need to have the directory name in which things are stored, relative to where your php page is located. Obviously, you have this already to create the page. I will assume it is stored in the $dir variable.
Code
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
echo "<a href='http://www.mydomain.com/".$dir."/".$file."'>";
echo "<img src='http://www.mydomain.com/".$dir."/".$file."' />";
echo "</a>";
}
}
Output
This will provide you a list of images that link to the image file itself.
Possible Modifications
1) You may want to only show some of the files in the directory, or a certain amount: Use the if block added here to do that:
if ($handle = opendir($dir)) {
//set $strThatSpecifiesImages to whatever you want;
//for the example, I'm saying that we only want to show files with "gal_image" in the filename
$strThatSpecifiesImages = "gal_image";
$maxFilesToShow = 10; //set this to whatever you want; example max is 10
$count = 0;
while (($count < $maxFilesToShow) && (false !== ($file = readdir($handle))) {
if (strpos($file, $strThatSpecifiesImages) > -1) {
echo "<a href='http://www.mydomain.com/".$dir."/".$file."'>";
echo "<img src='http://www.mydomain.com/".$dir."/".$file."' />";
echo "</a>";
$count++;
}
}
}
2) You might also want to change how things are displayed, so that you don't just have the full image shown here every time. Do this by modifying things in the echo blocks that are outputting HTML. You can have the browser resize the images, or just change it completely so that the links use text instead, or something else.

Related

Image (src) not refreshing after file-upload -> image [duplicate]

This question already has answers here:
PHP force refresh image
(5 answers)
Closed 2 years ago.
Having an image 'update' problem, whereby the image does not change after new file upload. the SRC attribute is designed to remain same; each uploaded file overwrites the previous one.
Let me elaborate::
I have a simple webpage, say Home.php and the page shows an image 'IMAGE1.jpg' where the image tag's src = "directory456/IMAGE1.jpg", understandably.
This homepage allows the user to change the image, through a file upload button Input type="file" (as we all know) located inside a "form". The form POSTS all the file data to another php file "Upload_File_Check.php".
Inside "Upload_File_Check.php", simple actions are performed:
(1) Check file size <2.0 MB,
(2) Check file "type" ($_FILES['filename']['type']) is one of {image/jpeg image/gif image/png}, and
(3) depending on whichever, utilizes the imagecreatefrom(gif/png/bmp)() function in PHP, to convert them ALL to jpg,
(4) ALL uploaded files are saved as "directory456/IMAGE1.jpg" using same file name hence overwriting the previous file sitting the in the directory. This way, knowing that the image's name will always be IMAGE1.jpg, I will not need to store/retrieve that from database. (comments welcome on this practice).
However, once the user clicks on the "Upload" button, and checks in "Upload_File_Check.php" are completed successfully, I would have thought that since "Home.php" is reloaded (? not sure about this), the image tag would get refreshed and now show the new image which has just been uploaded (SRC has remained same src="directory456/IMAGE1.jpg")?. The old image is showing, only upon manual page reload does the new image show.. how can I get the image tag to now refresh and load recent image pointed to ?
Code for Home.php:
<FORM method='post' action='Upload_File_Check.php' enctype='multipart/form-data'>
<INPUT type='file' name='filename_' size='10'>
<INPUT type='submit' value='upload'>
</FORM><?PHP echo $_SESSION['UPLOAD_FILE_ERR'];?>
Code for Upload_File_Check.php:
<?PHP
if($_FILES['filename_']['error'] > 0)
{ $_SESSION['UPLOAD_FILE_ERR'] .= "ERROR: ". $F_error;
header("location: HOME.PHP");}
else
{ $F_name = $_FILES['filename_']['name'];
$F_tmpnm = $_FILES['filename_']['tmp_name'];
$F_type = $_FILES['filename_']['type'];
$F_size = $_FILES['filename_']['size'];
if (!$F_tmpnm) // if file not chosen
{ $_SESSION['UPLOAD_FILE_ERR'] .= "ERROR - must have a file. "; }
if (!(($F_type == "image/bmp")||($F_type == "image/png")||($F_type == "image/jpeg")||($F_type == "image/gif")))
{ $_SESSION['UPLOAD_FILE_ERR'] .= "INVALID - only BMP JPG PNG GIF files allowed "; }
if ($F_size > 2097152)
{ $_SESSION['UPLOAD_FILE_ERR'] .= "File must be < 2.0MB "; }
if (($_SESSION['UPLOAD_FILE_ERR']) !== "")
{ header("HOME.PHP"); }
else
{ $F_destpath = "directory456/";
$F_destname = "IMAGE1.jpg";
move_uploaded_file($F_tmpnm, ($F_destpath . $F_name));
//convert MOVED file to jpg.
switch($F_type)
{ case "image/png":
$Converted_image=imagecreatefrompng($F_destpath . $F_name); break;
case "image/bmp":
$Converted_image=imagecreatefrombmp($F_destpath . $F_name); break;
case "image/gif":
$Converted_image=imagecreatefromgif($F_destpath . $F_name); break;
case "image/jpeg": break;
}
imagejpeg($Converted_image, $F_destpath . $F_destname , 90);
}
header("location: HOME.PHP");
}
?>
How do I get the IMAGE tag to refresh and point to the new image.. Would greatly appreciate your help...
New bie here, would also welcome all comments on the way I have programmed the stuff below.. what are best practices, what are faster (more efficient) methods, etc..
This question is a duplicate of PHP force refresh image.
The image isn't refreshing because the browser is caching the older file. To solve, just add a cache-busting query string to the URL in your img src. Unix timestamps work well for this. Note, however, that this will force the image to reload every time the page is loaded.
<img src="IMAGE1.jpg?t=<?php echo time() ?>">

php put_file_contents location problems, duplicate files

The code below fetches a jpg image from a server. if the length is larger than 1, we assume to have successfully grabbed the file. Then it proceeds to create a folder for the user if it isnt already there. (this part works)
from there, it should save the file in the /media/downloads/username location
instead it is going to /media/downloads/
I've looked at my concatenation a few times now, but I don't see where the issue is. I SEE that the filename is coming out with the username attached to the front, so I imagine its just a concatenation error.
Once this is fixed, I have a bigger issue- because I am using rand, when I cycle the script it just gives me duplicates. how can I prevent the duplicate images?!
if (strlen($data) > 1) {
$prePath = 'media/download/from_'.$sender.'_to_'.$recipient.'_id_'.$snapid.'.jpg';
if (!file_exists('media/download/'.$username)) {
mkdir('media/download/'.$username, 0777, true);
}
if (file_exists($prePath)){
$finalPath = 'media/download/'.$username.'/from_'.$sender.'_to_'.$recipient.'_id_'.$snapid.rand(0,100).'.jpg';
}
else {
$finalPath = 'media/download/'.$username.'/from_'.$sender.'_to_'.$recipient.'_id_'.$snapid.rand(0,100).'.jpg';
}
//echo "<img src='$data'></img>";
file_put_contents($finalPath, $data);
echo " <img src='".$finalPath."' alt='Smiley face' height='100' width='100'> ";
}

How to check an IF statement every 5sec in PHP?

I have a li and inside that i have a div class="reload" that have some content that should be reloaded for every 10 sec.
<li class="b1">
<div class="reload">
</div>
</li><!--col-->
So therefore i have got a script that does just that.
<script type="text/javascript">
$('.b1').children('.reload').load('php/reload/reload.php'); // load the content at start
window.setInterval(function(e) {
$('.b1').children('.reload').load('php/reload/reload.php'); // reload the content every 10 sec
}, 10000);
In the reload.php i get some content from a database. It looks like this, sort of..
<?php
// login info
require("../../connection_to_database_login.php");
// My query
$result = mysqli_query($l,'SELECT * FROM abcd WHERE efg=1 LIMIT 1');
// include some stuff
$r = mysqli_fetch_row($result);for ($p = 0; $p < $r[4]; ++$p){include("../some/stuff_$p.php");};
// include a random picture script or just load a picture
if ($r[4] == 0){include ('getRandPic.php');}
else {echo ('<img src="images/picture.png" />');}
?>
So far so good.. everything works.
The getRandPic.php file.. select one random picture from a folder
<?php
$img_dir = "images/images";
$images = scandir($img_dir);
$html = array();
foreach($images as $img) {
if($img === '.' || $img === '..') {continue;}
if ( (preg_match('/.jpg/',$img)) || (preg_match('/.gif/',$img)) || (preg_match('/.tiff/',$img)) || (preg_match('/.png/',$img)) ) {
$html[] .= '<img class="img-responsive" src="'.$img_dir.$img.'" />';
}
else { continue; }
};
echo $html[rand(0,6)];
?>
So this works ok.
But the thing is, i want to check if it shall "include a random picture script or just load a picture" every 5sec.
Therefore i need to check "if ($r[4] == 0)" every 5 sec.
So my question is: Is there any other way to do that?
As you asked in the comment... This is a rough guide only. You will have to develop and write your own code based on this guide.
Step 1a: optional
Make an ajax call from your webpage to the server. to get image file names.
Step 1b:
On server side in php file perform DB operation.
Let assume you have a table imageTable and column name images so you would read from DB using query SELECT images FROM imageTable
You will have to change the query, add condition (e.g. all images with animal and cute tags) to it and if you want limit the number of files that you want to randomize then you will have to add that as well.
Step 2:
Once you read from DB, as you are already doing, read all image names and put it in json format (json_encode). I personally prefer json. If you prefer, you can also return all names in simple string where names are separated by comma.
Step 3:
Store your response in JS.
var imagesArray = new Array();
$.ajax({
type: 'post',
url: pathtophpfile,
success: function(htmll) {
// get object with all data
imagesArray= JSON.parse(htmll);
},
});
Step 4:
Once you have it in your js object named imagesArray, use setInetval to perform task every 5 seconds.
Read a random value from 0 to imagesArrays length, and change the source of your image tag, <img class="img-responsive" src="+ randomimage +" />
Periodic updater will do your task.
Use ajax framework, it will reduce your db connection burden at the server side.
Have a look at it. It is a simple and nice way to achieve your task.
http://prototypejs.org/doc/latest/ajax/Ajax/PeriodicalUpdater/

PHP create embed image from database position

I searched Google and Stackoverflow but could not find the answer. Probably it is because I am searching for the wrong question. Without the right question, it’s hard to get the right answers. So I hope someone can help me.
I have created a top 20 list where people can rank their favourite website (I know it is not that original, but I do it to learn php)
Websites can be added to a database and are sorted based on votes. Each website has its own unique ID in the database, name and position.
What I cannot figure out is how to do the following.
Next to the list displayed show a get code button. This button will create a code for an image file that can be display on any website. For example:
<img src="http://www.example.com/counter.php?id=47"/>
or even better
<img src="http://www.example.com/47.gif"/>
To do this I need to make a php code, that can take the id and turn it into a nice image file and there I am stuck. I have seen twitter, feedburner, Technorati and over 100 other websites do this, but I cannot find out how.
I found this code that fakes feedburner, but I cannot figure out how to turn it into what I need.
<?php
//Send a generated image to the browser
create_image();
exit();
function create_image(){
//Create the image resource
$image = imagecreatefromgif('image.gif');
//Create text color
$brown = ImageColorAllocate($image, 0, 0, 0);
//Check for the get parameters
if (isset($_GET['count']) && is_numeric($_GET['count']))
$rank = $_GET['count'];
else
$rank = 20;
// Some Alignment Calculations
$bbox = imagettfbbox(8.5, 1,'verdana.ttf', $rank);
$xcorr = 0 + $bbox[2]; $xcorr = 31 - $xcorr;
//Add the number in brown color to the image
imagettftext($image,8.5,0,$xcorr,16,$brown,'verdana.ttf',$rank);
//Tell the browser what kind of file is come in
header("Content-Type: image/gif");
imagegif($image);
//Free up resources
ImageDestroy($image);}?>
Based on
www.mygeekpal.com/how-to-fake-your-feedburner-subscribers/
Using the above code and naming it counter.php I can fetch the position from the database and create
<img src='http://www.example.com/counter.php?count=".$array ['position']."' />
This takes the positon of a website from the database ($array has already been made to fetch) and creates an image with the position nr.
Works fine, but once the postion changes based on user ratings, the image will not show the correct data.
I hope someone can help. Thank you.
Summery
Basically what I am try to make is something that will show the most recent data, based on the ranking of the website. Just like showing the number of twitter followers, for example http://twittercounter.com/counter/?username=labnol or feedburner followers on http://feeds.feedburner.com/~fc/labnol
Both are images that show a number based on information in a database. But I want to create my own image, based on the rank of the website in the database.
Looking at your code it should update everytime the page is reloaded. Clear your browser cache.
If this fails i would check from where it is getting the Get['count'] data which im assuming is the Rank number of the site.
Can you check that the Get['Count'] data is updating as it should ?
Im not sure using an ARRAY in the URL is a good idea, why not use Sessions ?
This link might be of interest.
Sorry i have not been of more help.
This is what I have so far (I cannot edit this question from this computer, due to different cookies).
This is based on the help from
How to fetch data from database and display it in PHP?
thanks to
https://stackoverflow.com/users/353790/robertpitt
This seems to work
<?php
//Connect to DB
$db = mysql_connect("localhst","user","pass") or die("Database Error");
mysql_select_db("db_name",$db);
//Get ID from request
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
//Check id is valid
if($id > 0)
{
//Query the DB
$resource = mysql_query("SELECT * FROM domains WHERE id = " . $id);
if($resource === false)
{
die("Database Error");
}
if(mysql_num_rows($resource) == 0)
{
die("No User Exists");
}
$user = mysql_fetch_assoc($resource);
}
$img_number = imagecreate(110,24);
$image = imagecreatefromgif('image.gif');
$backcolor = imagecolorallocate($img_number,254,46,212);
$textcolor = imagecolorallocate($image, 0, 0, 0);
imagefill($image,0,0,$backcolor);
$number = $user['position'];
Imagestring($image,9,26,4,$number,$textcolor);
header("Content-Type: image/gif");
imagegif($image);
ImageDestroy($image);
?>

CSV Import to MySQL Table with image copy

Wondering if anyone would be so kind to help me with a addition to this script i have found online:
if(isset($_POST['SUBMIT']))
{
$fname = $_FILES['sel_file']['name'];
$chk_ext = explode(".",$fname);
if(strtolower($chk_ext[1]) == "csv")
{
$filename = $_FILES['sel_file']['tmp_name'];
$handle = fopen($filename, "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$sql = "INSERT into user(name,email,phone) values('$data[0]','$data[1]','$data[2]')";
mysql_query($sql) or die(mysql_error());
}
fclose($handle);
echo "Successfully Imported";
}
else
{
echo "Invalid File";
}
}
<form action='<?php echo $_SERVER["PHP_SELF"];?>' method='post'>
Import File : <input type='text' name='sel_file' size='20'>
<input type='submit' name='submit' value='submit'>
</form>
i have a csv which i want to import a bunch of data and this piece of code i have found online should do the trick but i have a couple of extra things i need to apply and hoping someone would be willing to write additional code to this for this to work.
i have 2 fields in the csv container image paths from another url:
image: http://blag.com/images.jpg
images: http://blag.com/images.jpg;http://blag.com/images.jpg;http://blag.com/images.jpg;http://blag.com/images.jpg
i am wanting to grab the image from the external url and upload it to a path on the site itself and then set the local image path and image name in the database
the images part contains multiple images which i need to do the same but apply to another field with those on them but would need to be able to display those additional images on the page but not sure if possible with that ; seperator in the database but guess you guys will know if its possible to fectha dn display but thats something ele i guess
if someone would be so kind to help me adapt that code so i can do that would be awesome as need to import a lot of data tonight :)
Thanks in advanced!
I wouldn't use php for this task. For importing the csv data I would use mysqlimport as it is much more efficient and less error prone then rolling your own php solution. For retrieving the images and storing them locally you could easily write a ruby or perl or even a bash script with curl to fetch the image and place them in the correct directory.
If this is part of another tool written in PHP then I would = look to using a system command to execute the mysqlimport on the local file. Then I would use the curl facility to grab the images and place them in the appropriate directory.
James,
you can add it easily,...
In this line:
$sql = "INSERT into user(name, email, phone) values('$data[0]','$data[1]','$data[2]')";
add the name of related Database Fields to the first part(for example:)
$sql = "INSERT into user(name, email, phone **,image, images** ) values('$data[0]','$data[1]','$data[2]')";
and for add their values from the result array in $data if they are immediately after other items (I mean if it is in this format: Name - Email - Phone - image - images) you just need to add to the index of array, in this condition it would be something like this:
$sql = "INSERT into user(name, email, phone **,image, images** ) values('$data[0]','$data[1]','$data[2]' **,'$data[3]','$data[4]'** )";
------------------------------------------------
UPDATED
OK, that's not hard too... I wrote a sample code for that, let me know if you have any problem:
// List of all images separated by ";"
$all_images = "http://www.google.com/images/nav_logo40.png;http://static.php.net/www.php.net/images/php.gif";
// Make an array from the list of images
$images = explode(";", $all_images);
// We want to copy all of images in the array
foreach ($images as $img_source_path){
// Retrive the name of file from path (It works for most of filenames!)
preg_match("/\/(?P<name>[a-zA-Z0-9._]+)$/", $img_source_path, $img_matches);
$img_filename = $img_matches[name];
// Make destination path
$img_destitation_path = getcwd()."/temp/".$img_filename;
// Copy file and check if it is done successfully
if (!copy($img_source_path, $img_destitation_path)) {
echo "failed to copy $img_filename...\n";
}
else {
echo "$img_filename copied successfully...\n";
}
}

Categories