Try to show image but shows a broken link instead - php

I want to show a picture in my code but for some reason I get a big white almost blank page with a broken link img. I want to show the image and along with any other information.
I also want to resize the image(so it doesnt cover the whole page).
The code:
<?php
session_start()
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1.0" />
<link rel="stylesheet" href="css/style.css" />
</head>
<div id="Container">
<div id="header">
<h1>Welcome!</h1>
</div>
<div id="navigation">
<?php
include_once "navigation.php";
?>
</div>
<div id="Content">
<?php
if (isset($_GET['search'])) {
$Name = $_GET['search'];
mysql_connect("localhost","root","") or die ("Could not connect to the server!");
mysql_select_db("pictures") or die ("That database could not be found!");
$query = mysql_query("SELECT * FROM picture WHERE Name='$Name'") or die ("The query could not be completed, please try again later!");
if (mysql_num_rows($wepquery) !=1) {
die ("That name could not be found!");
}
while ($row = mysql_fetch_array($query, MYSQL_ASSOC, 0)) {
$dbName = $row['Name'];
$dbCreator = $row['Creator'];
$dbDescription = $row['Description'];
$imageData = $row['Image'];
}
header("Content-type: image/jpeg");
if($Name != $dbName) {
die ("There has been a fatal error. Please try again.");
}
?>
<h2><?php echo $Name; ?></h2>
<br />
<table>
<tr><td>Creator: <?php echo $dbCreator;?></td></tr>
<tr><td>Description:<br /><?php echo $dbDescription;?></td></tr>
<tr><td>Picture:<br /><?php echo $imageData;?></td></tr>
</table>
<?php
} else die ("You need to specify a submission!");
?>
</div>
</div>
</html>
The database:
id, Name, Creator, Description, Image_name, Image(mediumblob).
The last two fields as you can see is dedicated to pictures. Yes I know about PDO and MySQLi, but I just want to finish this code first. Any help?

Images need to either be served by URL or the blob needs to be converted to a data URI like so:
<table>
<tr><td>Creator: <?php echo $dbCreator;?></td></tr>
<tr><td>Description:<br /><?php echo $dbDescription;?></td></tr>
<tr><td>Picture:<br /><?php echo "<img src='data:image/jpeg;base64," . base64_encode( $imageData ) . "' />"; ?></td></tr>
</table>

if you want image you need to enclose it with image tags. assume if your $imageData contains the location of the image then you can do the following.
<img src='<?php echo $imageData;?>' ... />
if your $imageData contains actual binary data of an image you need to create a separate call to a php script to return the imageData. and make the call to be the src attribute of an img tag.

is your path exactly pointing toward the image? have checked "../../" ? another question, is your image really inside an image tag? there must be something like this:
<img src="<?php echo $imagePath; ? />

Related

Show image in the page after uploading and inserting it to database

I want to show the image in my page after uploading and inserting it into the database. The image is used for my image slider. The reason i want to show the image here is to easily manage the image slider. That page is my admin. Im new to php and mysql, can someone give me ideas, what requirements, hints to do it?
here is the picture what i want to do.. like thumbnail
here is my slider its working.
NOTE: the image button is to upload the image.
here is my image slider code.
<?php
include('connect.php');
?>
<!DOCTYPE html>
<html>
<head>
<link href="css/style.css" rel="stylesheet" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="js/slider.js"></script>
<script>
$(document).ready(function () {
$('.flexslider').flexslider({
animation: 'fade',
controlsContainer: '.flexslider'
});
});
</script>
</head>
<body>
<div class="container">
<div class="flexslider">
<ul class="slides">
<?php
// Creating query to fetch images from database.
$query = mysqli_query($mysqli, "SELECT * from images order by id desc limit 5");
$result = $query;
while($r = mysqli_fetch_array($result)){
?>
<li>
<img src="<?php echo $r['photo'];?>" width="400px" height="300px"/>
</li>
<?php
}
?>
</ul>
</div>
</div>
</body>
</html>
here is my admin.php this is where i want to show the image.
<?php
//for connecting db
include('connect.php');
if (!isset($_FILES['image']['tmp_name'])) {
echo "";
}
else
{
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"gallery/" . $_FILES["image"]["name"]);
$photo="gallery/" . $_FILES["image"]["name"];
$query = mysqli_query($mysqli, "INSERT INTO images(photo)VALUES('$photo')");
$result = $query;
echo '<script type="text/javascript">alert("image successfully uploaded ");window.location=\'admin.php\';</script>';
}
?>
<form class="form" action="" method="POST" enctype="multipart/form-data">
<div class="image">
<p>Upload images and try your self </p>
<div class="col-sm-4">
<input class="form-control" id="image" name="image" type="file" onchange='AlertFilesize();'/>
<input type="submit" value="image"/>
</div>
</div>
</form>
here is my connect.php code
<?php
// hostname or ip of server
$servername='localhost';
// username and password to log onto db server
$dbusername='root';
$dbpassword='';
// name of database
$dbname='pegasus';
////////////// Do not edit below/////////
$mysqli = new mysqli($servername,$dbusername,$dbpassword,$dbname);
if($mysqli->connect_errno){
printf("Connect failed: %s\n", $mysql->connect_error);
exit();
}
?>
One approach would be to use glob to see if there are any files in the gallery folder
Something along the lines of:
<?php foreach(glob('./path/to/gallery/folder/*.{jpg,gif,png}', GLOB_BRACE) as $image): ?>
<img src="<?= $image; ?>" />
<?php endforeach; ?>
One benefit of this approach is that if there are no images, nothing will show and you're also saving a db query.
Or to make use of your database query again...
Copy this from your first file..
<?php
// Creating query to fetch images from database.
$query = mysqli_query($mysqli, "SELECT * from images order by id desc limit 5");
$result = $query;
while($r = mysqli_fetch_array($result)){
?>
<img src="<?php echo $r['photo'];?>" width="400px" height="300px"/>
<?php
}
?>
and reuse it in your file that you want to display the images
Reference: glob

PHP View Counter

I am trying to make a website and it's almost completed but I want to add a view counter so when someone visit the page it count the view and save it into the database.
My script is working fine but the problem is that it continue view count even visitor is viewing anyother page
My pages url show like this
pictures.php?ID=13
I have added this PHP code in *count.php*
<?php
session_start();
if (isset($_SESSION['views'])){
$_SESSION['views']++;
} else {
$_SESSION['views'] =0;
}
//echo $_SESSION['views'];
?>
Page *views.php*
<?php
session_start();
if (isset($_SESSION['$post_id'])){
$_SESSION['$post_id']++;
} else {
$_SESSION['$post_id'] =0;
}
//echo $_SESSION['views'];
?>
<?php
echo "<hr><div align=\"center\">";
echo $_SESSION['$post_id'];
?>
<?php
$save = $_SESSION['$post_id'];
$con=mysqli_connect("localhost","root","123","user");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"UPDATE save_data SET Views='$save' WHERE ID='$page_id'");
mysqli_close($con);
?>
And added this line in Pictures.php where I want to show and count visits
<?php include("views.php"); ?>
Problem:
When someone visits page pictures.php?ID=8 it will show him page view 1 and save this view in database where ID=8, when he visit page pictures.php?ID=12 it will show him view 2 and save this 2 in database where ID=12. My point is that it is continuously counting instead of each page view.
Thanks in advance
Here is Pictures.php
<?php
include("connection.php");
if(isset($_GET['ID'])){
$page_id = $_GET['ID'];
$select_query = "select * from save_data where ID='$page_id'";
$run_query = mysql_query($select_query);
while($row=mysql_fetch_array($run_query)){
$post_id = $row['ID'];
$post_title = $row['Title'];
$post_image = $row['Name'];
?>
<h3>
<a href="pictures.php?ID=<?php echo $post_id; ?>">
<?php echo $post_title; ?>
</a>
</h3><center>
<form id="search-form" action="javascript:void(0);">
<input type="text" id="dimen" name="dimension" />
<input type="submit" value="Resize" Onclick ="splitString()"/></form>
<div id="sizet">
Type size like 200*300 in box
</div></center>
<div id="img"><img id="myImage" src="uploads/<?php echo $post_image; ?>" /></div>
<?php } }?>
<center>
<div id="postdetails">
<?php include("posted_by.php"); ?></center>
</div>
<?php include("views.php"); ?>
<html>
<link href="css/Pictures.css" rel="stylesheet" type="text/css">
<body>
<head>
<script type="text/javascript">
function splitString()
{
var myDimen=document.getElementById("dimen").value;
var splitDimen = myDimen.split("*");
document.getElementById("myImage").width=splitDimen[0];
document.getElementById("myImage").height=splitDimen[1];
}
</script>
</head>
</body>
Variables inside of single quotes are not evaluated, so regardless of whether $post_id is 8 or 12, $_SESSION['$post_id'] is setting the key named literally $post_id, rather than the key named 12 or 8. Variables are evaluated inside double quotes, so $_SESSION["$post_id"] would work, but the simplest and best way is to use $_SESSION[$post_id] instead.
Additionally, using $_SESSION here is probably not what you want to do. $_SESSION will be different for every user who visits the site, so when a new visitor comes to the site, it will start over with a count of 1. What you probably want to do is load the views value from the database, add one to it, and then save it back to the database. $_SESSION is for keeping data that is specific to a certain user.
Try to use structure like this
$_SESSION['view'][{resource_name}_{resource_id}]
E.g. for picture with id 8 it will be
$_SESSION['views']['picutures_8']++

How to increase the pagination speed

In my project I have done a pagination using PHP, I have done it as follows:
Each buttons(NEXT PAGE and PREVIOUS PAGE) are hyperlinks which links to the same page with passing a GET variable (PAGENUMBER). For each page change, there are scripts for
connect to DB .
query for the data for the specified page.
close the
DB connection. displays the data.
The problem is that it is working slowly. Is there any alternative method for each time connect to db and query for the data and close db connection.
Also During the pagination I want to reload only the datas from DB and all other contents in page remains the same and dont want to reload. How to achieve this?
The script is given below
<?php
require_once("./include/membersite_config.php"); //include files for login system
if($fgmembersite->CheckLogin())
{
$login=true;
}
else
{
$login=false;
}
require_once("db.php");
$con=connect(); //connect to db and select the db
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML>
<HEAD>
<TITLE> Gallery </TITLE>
<META name="generator" content="Adobe Photoshop(R) CS Web Photo Gallery">
<META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="images/galleryStyle.css" rel="stylesheet" type="text/css">
<link rel="STYLESHEET" type="text/css" href="style/new.css" />
</HEAD>
<body marginheight=0 marginwidth=0 leftmargin=0 topmargin=0>
<table><tr>
<?php
//////////////////DISPLAYING IMAGE THUNBNAILS//////////////////////
$query="SELECT COUNT(*) FROM gallery ";
$res = query($query);
$raw=mysql_fetch_array($res);
$imagecount=$raw[0];
if($imagecount==0) { die ("No images found"); }
$pagecount=ceil($imagecount/15);
$page = isset($_GET['page']) ? mysql_real_escape_string($_GET['page']) : 1;
if (isset($_GET['page']))
{
if (!(ctype_digit($_GET['page']) and $_GET['page']>0 and $_GET['page']<=$pagecount))
{
die ("You are not autorised to viw this page");
}
}
$start= ($page*15)-15;
$query = "SELECT * FROM gallery ORDER BY imageid DESC LIMIT $start , 15";
$res = query($query);
$count= mysql_num_rows($res);
$index=0;
for($i=1;$i<=3;$i++)
{
?>
<TR>
<?php
for($j=1;$j<=5;$j++)
{
if(!$raw=mysql_fetch_array($res)) {break;}
$index++;
$imageid=$raw['imageid'];
$thumbpath= $raw['thumbpath'];
$largepath=$raw['largepath'];
$caption=$raw['caption'];
?>
<A name=1 href="image.php?imageid=<?php echo $imageid ?>&imageindex=<?php echo ((($page-1)*15)+$index-1) ; ?> "><IMG border=0 src="<?php echo $thumbpath; ?>" height="75" width="75" alt="<?php echo $caption ?>" title="<?php echo $caption ?>" ></A><BR>
<?php
echo "<a href='delete.php?delete=yes&imageid=".$imageid.'&page='.$page."'>Delete </a>"
echo "<a href='replace.php?update=yes&imageid=".$imageid.'&page='.$page."'>Replace </a>"
?>
</table>
</td>
<?php } ?>
</TR>
<?php
}
if ($page!=1)
{
?>
<td width=17><IMG SRC="images/previous.gif" BORDER=0></td>
<?php } ?>
<td align=middle class="pagenums"><?php echo "page ".$page." of ".$pagecount ?></td>
<?php
if ($page!=$pagecount)
{
?>
<td align=right width=17><img border=0 src="images/next.gif"></td>
<?php } ?>
</table>
</body>
</html>
There are lot much options available
go with javascript pagination
ajax pagination
try to reduce pagination code(optimized code)
You do not need to connect/close db for each page change
use the ajax script for connecting and getting database values with reloading the current page you can do it -- -- -- --- -- -- try ajax

PHP file in <img> tag cannot be referenced using query string

i m trying to display an image stored in a database by passing the image_id(an auto increment field) into the query string and then including imagedisplay.php(file used to display the image) in image tag. The problem is that this file, imagedisplay.php is not access ie the control never seems to go into the file. The code for both the main file and the imagedisplay.php file are below. Please note that i m not able to write the head part of the code here due to some formatting issue. The head section is standard html section pre-formatted in Dreamweaver.
<body>
<div class="page shadow-round">
<div id="header">
<div id="logo">
<script type="text/javascript" src="../js/header.js"></script>
</div>
</div>
<div id="menu">
<script type="text/javascript" src="../js/navmenu.js"></script>
<script type="text/javascript">
</script>
</div>
<div class="content overflow" style="height:900px;">
<?php
require_once 'login.php'; //contains the classes for connecting to databases
$dbh=new DB_Mysql; //executing queries
$func=new DB_Mysql_code_functions;
session_start();
if(isset($_SESSION['username']))
{
echo<<<_END
<form method="post" action="admin_social_activities.php" enctype="multipart/form-data">
<table width="990">
<tbody>
<tr><td>Select an image file to be uploaded:</td></tr>
<tr><td><input type="submit" value="UPLOAD" /></td></tr>
</tbody>
</table>
</form>
_END;
if(isset($_FILES['imagefile']['tmp_name']))
{
$imagefile=$_FILES['imagefile']['tmp_name'];
$image_size=$_FILES['imagefile']['size'];
$image_name=addslashes($_FILES['imagefile']['name']);
$image_data = addslashes(file_get_contents($imagefile));
$image_array=getimagesize($imagefile);
$image_type=$image_array['mime'];
$image_height=$image_array[1];
$image_width=$image_array[0];
$maxfilesize=2000000;
if($maxfilesize<$image_size)
{
echo "Please upload a smaller image. The size of the image is too large.";
}
else
{
$query="INSERT INTO gallery(image_name,image_type,image,image_size) VALUES ('". $image_name."','".$image_type."','".$image_data."','".$image_size."')";
$stmt=$dbh->execute($query);
$lastimageid=mysql_insert_id();
echo "<p>You uploaded this image</p>";
echo "<img src='imagedisplay.php?imageid=".$lastimageid."' />";
}
}
}
else
echo "<br/><br/> Your are <span class=\"red\"><b>not Authorized</b></span> to view this page. If you are the Admin, please login with your credentials again. <a href='login_page.php'>Click here to continue</a>";
?>
</div>
</body>
</html>
Now the problem is that the control never goes to imagedisplay.php ie. it fails to reference imagedisplay.php altogether.
the code for imagedisplay.php is below:
<?php
require_once 'login.php';
$dbh= new DB_Mysql();
$func=new DB_Mysql_code_functions;
$id=$_GET['imageid'];
$query="SELECT * FROM gallery where image_id=".$id;
$stmt=$dbh->execute($query);
$row=$stmt->fetch_row();
$imagedata=$row[3];
header("Content-type:image/jpeg");
echo $imagedata;
?>
I have tried all permutation combinations with the quotes, tried echo statements to see if control enters the file....but it does not...it stays in the main file only...i dont understand the reason...please help...please don't worry about SQL injections as i plan to deal with them later, once the code starts working....thanks
Your echo command should be like this:
echo '<img src="imagedisplay.php?imageid=' . $lastimageid . ' " />';
Look at your generated HTML source and make sure it's right. Check your error log to see if you are getting any errors from your image script.

Set Page Title using PHP

I wish to set the title of my webpage to Ultan.me - Whatever the post title. I want it to display the post title. The posts are submitted to a MySQL database and the title row is called "title". Any help is appreciated with this small question.
Update:
Here is the page itself now but it doesn't display the title. Should I open the php document and connect to my database somewhere different to it's current locations?
The Code (The only necessary piece is the beginning):
<html>
<head>
<meta name="keywords" content="Mac user Ultan Casey TheCompuGeeks UltanKC">
<title>Ultan.me - <?echo $title;?></title>
<link rel="stylesheet" href="css/styles.css" type="text/css" />
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript"
src="js/jquery.labelify.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(":text").labelify();
});
</script>
<style>
a {text-decoration:none}
</style>
</head>
<body>
<div id="main">
<!-- Menu Start -->
<div id="menu">
<ul>
<li>home</li>
<li>about me</li>
<li>archives</li>
<li>contact</li>
<li>gallery</li>
</ul>
</div>
<!-- Menu End -->
<img src="images/banner.png" />
<div id="content">
<div id="posts">
<?php
mysql_connect ('localhost', 'root', 'root') ;
mysql_select_db ('ultankc');
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
die("Invalid ID specified.");
}
$id = (int)$_GET['id'];
$sql = "SELECT * FROM php_blog WHERE id='$id' LIMIT 1";
$result = mysql_query($sql) or print ("Can't select entry from table php_blog.<br />" . $sql . "<br />" . mysql_error());
while($row = mysql_fetch_array($result)) {
$date = date("l F d Y", $row['timestamp']);
$title = stripslashes($row['title']);
$entry = stripslashes($row['entry']);
$get_categories = mysql_query("SELECT * FROM php_blog_categories WHERE `category_id` = $row[category]");
$category = mysql_fetch_array($get_categories);
?>
<p><?php echo "<p id='post-title'><strong>" . $title . "</strong></p>"; ?><br /><br />
<div id="entry"><?php echo $entry; ?>
</div><br /><br />
<p id="date">Posted in <?php echo $category['category_name']; ?> on <?php echo $date; ?></p>
</p>
<h2 id="share-title">Share This Post</h2>
<div id="social-share">
<li id="link-right"><a href="http://twitter.com/home?status=
I just read <?php echo $title; ?> at http://ultan.me/post.php?id=<?php echo $id; ?>"><center>Twitter</center></a></li>
<li id="link-left"><center>Digg</center></li>
<br>
<li id="link-right"><center>Facebook</center></li>
<li id="link-left"><a href="http://www.google.com/buzz/post?url=http://ultan.me/post.php?id=<?php echo $id; ?>
"><center>Google Buzz</center></a></li>
<div class="clr"></div>
</div>
<h2 id="comments-title">Comments</h2>
<div id="comment-list">
<?php
}
$commenttimestamp = strtotime("now");
$sql = "SELECT * FROM php_blog_comments WHERE entry='$id' ORDER BY timestamp";
$result = mysql_query ($sql) or print ("Can't select comments from table php_blog_comments.<br />" . $sql . "<br />" . mysql_error());
while($row = mysql_fetch_array($result)) {
$timestamp = date("l F d Y", $row['timestamp']);
printf("<div class='comment-ind'><p id='comments'><a id='username' href=\"%s\">%s</a> %s</p>", stripslashes($row['url']), stripslashes($row['name']), $timestamp);
print("<p class='comments'>" . stripslashes($row['comment']) . "</p><div class='clr'><br></div></div>");
}
?>
<div class="clr"></div>
<form id="commentform" method="post" action="process.php">
<p><input type="hidden" name="entry" id="entry" value="<?php echo $id; ?>" />
<input type="hidden" name="timestamp" id="timestamp" value="<?php echo $commenttimestamp; ?>">
<input type="text" name="name" id="name" title="Name (required)" /><br />
<input type="text" name="email" id="email" title="Mail (will not be published) (required)" /><br />
<input type="text" name="url" id="url" title="Website" value="http://" /><br />
<br />
<textarea title="Your Comment Goes Here" name="comment" id="comment"></textarea></p>
<p><input type="submit" name="submit_comment" id="submit_comment" value="Add Comment" /></p>
</form>
</div>
<div id="pages">
<?php
$total_results = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS num FROM php_blog"));
$total_pages = ceil($total_results['num'] / $blog_postnumber);
if ($page > 1) {
$prev = ($page - 1);
echo "<< Newer ";
}
for($i = 1; $i <= $total_pages; $i++) {
if ($page == $i) {
echo "$i ";
}
else {
echo "$i ";
}
}
if ($page < $total_pages) {
$next = ($page + 1);
echo "Older >>";
}
?>
</div>
</div>
</div>
<!-- Sidebar Start -->
<div class="sidebar">
<!-- Item 1 -->
<div id="side-item">
<h2>
<a href="http://www.dailybooth.com/UltanCasey">
<img src="images/db-icon.jpg">Dailybooth
</a></h2>
<div id="side-item-content">
<center>
<img src="http://dailybooth.com/UltanCasey/latest/medium.jpg" />
</center>
</div>
</div>
<!-- Item 2 -->
<div id="side-item">
<h2><img src="images/connect.jpg" />Connect</h2>
</div>
<div id="side-item-content">
<div class="tweet-title"><p>Latest Tweet:</p></div>
<div id="tweet">
<?php
function getTwitterStatus($userid){
$url = "http://twitter.com/statuses/user_timeline/$userid.xml?count=1";
function auto_link_twitter ($text)
{
// properly formatted URLs
$urls = "/(((http[s]?:\/\/)|(www\.))?(([a-z][-a-z0-9]+\.)?[a-z][-a-z0-9]+\.[a-z]+(\.[a-z]{2,2})?)\/?[a-z0-9._\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1})/is";
$text = preg_replace($urls, " <a href='$1'>$1</a>", $text);
// URLs without protocols
$text = preg_replace("/href=\"www/", "href=\"http://www", $text);
// Twitter usernames
$twitter = "/#([A-Za-z0-9_]+)/is";
$text = preg_replace ($twitter, " <a href='http://twitter.com/$1'>#$1</a>", $text);
// Twitter hashtags
$hashtag = "/#([A-Aa-z0-9_-]+)/is";
$text = preg_replace ($hashtag, " <a href='http://hashtags.org/$1'>#$1</a>", $text);
return $text;
}
$xml = simplexml_load_file($url) or die("could not connect");
foreach($xml->status as $status){
$text = $status->text;
}
echo auto_link_twitter ($text);
}
getTwitterStatus("UltanKC");
?>
</div>
<br>
<ul>
<li id="social">YouTube</li>
<li id="social">Twitter</li>
<li id="social">LastFM</li>
<li id="social">Email</li>
</ul>
</div>
<!-- Item 2 End-->
<div id="side-item">
<h2><img src="images/archive.jpg" />Archives</h2>
</div>
<div id="archive-side">
<?php
mysql_connect ('localhost', 'root', 'root') ;
mysql_select_db ('ultankc');
$result = mysql_query("SELECT FROM_UNIXTIME(timestamp, '%Y') AS get_year, COUNT(*) AS entries FROM php_blog GROUP BY get_year");
while ($row = mysql_fetch_array($result)) {
$get_year = $row['get_year'];
$entries = $row['entries'];
echo "<li id='tag'>Entries from " . $get_year . " (" . $entries . ")<br /></li>";
}
$result1 = mysql_query("SELECT * FROM php_blog_categories ORDER BY category_name ASC");
while($row = mysql_fetch_array($result1)) {
$result2 = mysql_query("SELECT COUNT(`id`) AS entries FROM php_blog WHERE category = $row[category_id]");
$num_entries = mysql_fetch_array($result2);
echo '<li id="tag">' . $row['category_name'] . ' (' . $num_entries['entries'] . ')</li>';
}
?>
</div>
</div>
<div class="clr" />
</div>
<!-- Sidebar End -->
<div id="footer">
<p> © Ultan Casey 2010</p>
<p style="margin-top: -18px; float:right">Home | About Me | Email Me</p>
</div>
</div>
</div>
</body>
</html>
?>
Here's the method I use (for similar things, not just title):
<?
ob_start (); // Buffer output
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title><!--TITLE--></title>
</head>
<body>
<?
$pageTitle = 'Title of Page'; // Call this in your pages' files to define the page title
?>
</body>
</html>
<?
$pageContents = ob_get_contents (); // Get all the page's HTML into a string
ob_end_clean (); // Wipe the buffer
// Replace <!--TITLE--> with $pageTitle variable contents, and print the HTML
echo str_replace ('<!--TITLE-->', $pageTitle, $pageContents);
?>
PHP usually works be executing any bits of code and printing all output directly to the browser. If you say "echo 'Some text here.';", that string will get sent the browser and is emptied from memory.
What output buffering does is say "Print all output to a buffer. Hold onto it. Don't send ANYTHING to the browser until I tell you to."
So what this does is it buffers all your pages' HTML into the buffer, then at the very end, after the tag, it uses ob_get_contents () to get the contents of the buffer (which is usually all your page's HTML source code which would have been sent the browser already) and puts that into a string.
ob_end_clean () empties the buffer and frees some memory. We don't need the source code anymore because we just stored it in $pageContents.
Then, lastly, I do a simple find & replace on your page's source code ($pageContents) for any instances of '' and replace them to whatever the $pageTitle variable was set to. Of course, it will then replace <title><!--TITLE--></title> with Your Page's Title. After that, I echo the $pageContents, just like the browser would have.
It effectively holds onto output so you can manipulate it before sending it to the browser.
Hopefully my comments are clear enough.
Look up ob_start () in the php manual ( http://php.net/ob_start ) if you want to know exactly how that works (and you should) :)
You parse the field from the database as usual.
Then let's say you put it in a variable called $title, you just
<html>
<head>
<title>Ultan.me - <?php echo htmlspecialchars($title);?></title>
</head>
EDIT:
I see your problem. You have to set $title BEFORE using it. That is, you should query the database before <title>...
header.php has the title tag set to <title>%TITLE%</title>; the "%" are important since hardly anyone types %TITLE% so u can use that for str_replace() later. then, you use output buffer like so
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$buffer=str_replace("%TITLE%","NEW TITLE",$buffer);
echo $buffer;
?>
For more reference, click PHP - how to change title of the page AFTER including header.php?
What about using something like:
<?php
$page_title = "Your page tile";
include("navigation.php"); // if required
echo("<title>$page_title</title>");
?>
Move the data retrieval at the top of the script, and after that use:
<title>Ultan.me - <?php echo htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); ?></title>
You need to set the value of $title before echoing it.
Also, you should really sanitize any data before using it in queries as this is a security risk
create a new page php and add this code:
<?php
function ch_title($title){
$output = ob_get_contents();
if ( ob_get_length() > 0) { ob_end_clean(); }
$patterns = array("/<title>(.*?)<\/title>/");
$replacements = array("<title>$title</title>");
$output = preg_replace($patterns, $replacements,$output);
echo $output;
}
?>
in <head> add code: <?php require 'page.php' ?> and on each page you call the function ch_title('my title');
The problem is that $title is being referenced on line 5 before it's being assigned on line 58. Rearranging your code isn't easy, because the data is both retrieved and output at the same time. Just to test, how does something like this work?
Because you're only retrieving one row, you don't need to use a while loop, but I left it with hopes that it'll make it easier for you to relate to your current code. All I've done is removed the actual output from your data retrieval, and added variables for category and category name which are then referred to as usual later on. Also, I haven't tested this. :)
It'll be tricky to rearrange your code to make this work, but I'll try :)
So, put this at the top of your code:
<?php require_once('mysql.php'); ?>
The top of the file should look like:
<?php require_once('mysql.php'); ?>
<html>
<head>
<meta name="keywords" content="Mac user Ultan Casey TheCompuGeeks UltanKC">
<title>Ultan.me - <?php echo htmlspecialchars($title); ?> </title>
Then, create a file called mysql.php in the same directory that the file which contains the code you quoted is in.
Put this is mysql.php:
<?php
mysql_connect ('localhost', 'root', 'root');
mysql_select_db ('ultankc');
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
die("Invalid ID specified.");
}
$id = (int)$_GET['id'];
$sql = "SELECT * FROM php_blog WHERE id='$id' LIMIT 1";
$result = mysql_query($sql) or print ("Can't select entry from table php_blog.<br />" . $sql . "<br />" . mysql_error());
$res = mysql_fetch_assoc($result);
$date = date("l F d Y", $res['timestamp']);
$title = $res['title'];
$entry = $res['entry'];
$get_categories = mysql_query("SELECT * FROM php_blog_categories WHERE `category_id` = $res['category']");
$category = mysql_fetch_array($get_categories);
?>
Well, hope that helped :)
I know this is an old post but having read this I think this solution is much simpler (though technically it solves the problem with Javascript not PHP).
<html>
<head>
<title>Ultan.me - Unset</title>
<script type="text/javascript">
function setTitle( text ) {
document.title = text;
}
</script>
<!-- other head info -->
</head>
<?php
// Make the call to the DB to get the title text. See OP post for example
$title_text = "Ultan.me - DB Title";
// Use body onload to set the title of the page
print "<body onload=\"setTitle( '$title_text' )\" >";
// Rest of your code here
print "<p>Either use php to print stuff</p>";
?>
<p>or just drop in and out of php</p>
<?php
// close the html page
print "</body></html>";
?>
Simply add $title variable before require function
<?php
$title = "Your title goes here";
require("header.php");
?>
header.php
<title><?php echo $title; ?></title>
<?php echo APP_TITLE?> - <?php echo $page_title;?>
this should work fine for you
if you want to current script filename as your title tag
include the function in your project
function setTitle($requestUri)
{
$explodeRequestUri = explode("/", $requestUri);
$currentFileName = end($explodeRequestUri);
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $currentFileName);
$explodeCurrentFileName = explode("-", $withoutExt);
foreach ($explodeCurrentFileName as $curFileValue)
{
$fileArrayName[] = ucfirst($curFileValue);
}
echo implode(" ", $fileArrayName);
}
and in your html include the function script
and replace your title tag with this
<title>Your Project Name -
<?php setTitle($_SERVER['REQUEST_URI']); ?>
</title>
it works on php7 and above but i dont have any idea about php 5.*
Hope it helps

Categories