I attempted to display the image using PHP with the following code
<?php
header('Content-type: image/png');
$port = "*";
$server = "*:".$port;
$dbname ="*";
$user = "*";
$conn = mysql_connect ("$server", "$user", "$pass") or die ("Connection
Error or Bad Port");
mysql_select_db($dbname) or die("Missing Database");
$speakerPic = $_POST['speakerPic'];
$query = "SELECT Speaker.speaker_picture AS image FROM Speaker JOIN Contact c USING(contact_id)
WHERE c.lname = '";
$query .= $speakerPic."';";
$result = mysql_query($query,$dbname);
$result_data = mysql_fetch_array($result, MYSQL_ASSOC);
echo $result_data['image'];
?>
I keep on receiving this error, The image “.../query2.php” cannot be displayed because it contains errors.
Sorry to keep on bugging you guys, but can anyone tell what the problem is?
Not going to lie, there is a lot of bad with the OP code.
You should be pulling images from the database by id, not some string
You are not sanitizing the var being used in the query
You are not serving a default image if one doesn't exist
Also, I would suggest storing file uris in your database, not the actual image (blob). You should store a pointer to an image on your filesystem.
Not going to clean up the code too much, just make it less bad. I'd suggest something along these lines (untested):
// Utility.php
class Utility
{
/**
*
* #param mixed $id is abstract, could be name or an actual id
* #return string?
*/
public static function getImage($id)
{
try {
$port = "*";
$server = "*:".$port;
$dbname ="*";
$user = "*";
$conn = mysql_connect ("$server", "$user", "$pass");
if (!$conn) {
throw new Exception("Connection Error or Bad Port");
}
if (!mysql_select_db($dbname)) {
throw new Exception("Missing Database");
}
$query = "SELECT Speaker.speaker_picture AS image FROM Speaker JOIN Contact c USING(contact_id) WHERE c.lname = " . mysql_real_escape_string($id). ";";
$result = mysql_query($query,$dbname);
$result_data = mysql_fetch_array($result, MYSQL_ASSOC);
if (!isset($result_data['image'])) {
throw new Exception('Image not found');
}
echo $result_data['image'];
} catch Exception($e) {
error_log($e->getMessage();
return file_get_contents('/path/to/some/default/image.png');
}
}
}
// image.php
require_once 'Utility.php';
header('Content-type: image/png');
ob_start();
Utility::getImage($_POST['speakerPic']);
$image = ob_get_flush();
echo $image;
Related
Can any of you guys help me to reorganize this code? I'll try to explain the problem below.
I have a db_connection.php wich includes the following (just my db info and don't worry, i am just using it locally):
<?php
try {
$db = new PDO('mysql:host=localhost;dbname=webappeind;charset=utf8','root','');
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
But the problem is i have the following file that also includes my db info, but i do not know how to reorganize my code to get it working with my separate php file.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "webappeind";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM zoekopdrachten ORDER BY titel DESC LIMIT 3";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output gegevens van elke rij
while($row = $result->fetch_assoc()) {
echo "<div class='recenttoegevoegd'>"."<a href='#'>".$row["titel"]."</a>"."</div>";
}
} else {
echo "0 resultaten";
}
?>
You can put the connection information in a separate file called, say, conn.php where you mention the code related to database opening, including credentials. Then, in the calling file, say putdata.php, you use the "require" or "require_once" command to include that conn.php. Let the conn.php file return a connection. Somewhat like this :
<?php
function GetMyConn() {
$server_name = "localhost";
$db_name = "db_name_goes_here";
$db_user = "user_name_goes_here";
$db_pass = "password_goes_here_muahhhaa";
$db_full_addr = "mysql:host=" . $server_name . ";" . "dbname=" . $db_name;
$MyConn = new PDO($db_full_addr, $db_user, $db_pass);
$MyConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $MyConn;
}
?>
In the calling file, you would say, something like :
require_once "GetConn.php";
$MyConnHere = GetMyConn();
$SqlHere = "Sql Statemetn goes here...."
$SqlHere2 = $MyConnHere->prepare($SqlHere);
$SqlHere2->execute();
Also, I suggest you can download the source code of some open source PHP application, such as mantissa, and see how they have organized their code files, folders and settings.
I am attempting to build a database driven site whereby images are loaded via a php script like so;
<img src="get_image.php?holderID=2">
I can get images to load from a folder outside the root directory when the database is accessible but I also want to be able to load a default image if there is a failure with making the database connection. The DB connection is initiated form a separate php connection file mysqli_template_connect.php;
DEFINE('DB_USER', 'someusername');
DEFINE('DB_PASSWORD', 'amnesia');
DEFINE('DB_HOST', 'localhost');
DEFINE('DB_NAME', 'template');
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
and then config.inc.php sets some constants, one of which is for all DB connections;
define('MYSQL', '../../../dbconnect/mysqli_template_connect.php');
The get_image.php file then has a database connection conditional;
require('includes/config.inc.php');
REQUIRE(MYSQL);
$holderID = $_GET['holderID'];
if(!$dbc){
$image_name = 'img/unavailable.png';
$info = getimagesize($image_name);
header("Content-Type: {$info['mime']}\n");
readfile($image_name);
}
else {
$query = "SELECT imageID FROM image_holder WHERE image_holderID = $holderID ";
$result = #mysqli_query($dbc, $query);
$number_rows = mysqli_num_rows($result);
if ($number_rows == 1) {
$row = mysqli_fetch_array($result, MYSQLI_NUM);
$imageID = $row[0];
}
else {
$imageID = FALSE;
}
if ($imageID) {
$query = "SELECT file_name FROM image WHERE imageID = $imageID";
$result = mysqli_query($dbc, $query);
$number_rows = mysqli_num_rows($result);
if ($number_rows == 1) {
$row = mysqli_fetch_array($result, MYSQLI_NUM);
$image_name = '../../../uploads/' . $row[0];
}
else {
$image_name = 'img/unavailable.png';
}
}
else {
$image_name = 'img/unavailable.png';
}
$info = getimagesize($image_name);
header("Content-Type: {$info['mime']}\n");
readfile($image_name);
mysqli_close($dbc);
}
If I disable the MYSQL database in XAMP, the default image unavailable.png will not load even though the header and readfile section of code is virtually the same in the section of code that does work. I'm quite a newbie to all this so any ideas on loading the default image would be appreciated.
Depending on the database object you are using (MySQLi/PDO/etc), you can check if they connected. PDO returns a boolean that you can run against.
Since PDO is the most popular, I will provide an example of that. If you use something else, feel free to comment and I can clarify.
$connected = true;
if (!extension_loaded('PDO'))
{
$connected = false;
}
if (!extension_loaded('pdo_mysql'))
{
$connected = false;
}
try
{
$pdo = new PDO("mysql:host={$host};dbname={$db}", $user, $pass);
}
catch(PDOException $e)
{
$connected = false;
}
if(!$connected){ /* Load default image */ }
Note: just make sure you use the correct image headers.
Instead of
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
Use
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
hopefully it should work..
I have similar code that do the almost the same thing.
I suspect it was the header, since I have a bit more info added to the header. No harm for you to try out.
header('Content-Description: File Transfer');
header('Content-Type: '. $file_content_type);
header('Content-Length: ' . filesize($file_full_path));
header('Content-Disposition: inline; filename=' . $file_name);
readfile($file_full_path);
Right now I am inserting blob files into a database. I have read up on the update syntax for mysql I can not figure out how to modify my code to update a row with the BLOB instead of inserting a new row with the BLOB. Could someone help me with this?
Here is my code:
<?php
// Create MySQL login values and
// set them to your login information.
$username = "root";
$password = "";
$host = "localhost";
$database = "test";
$tbl_name="members";
// Make the connect to MySQL or die
// and display an error.
$link = mysql_connect($host, $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Select your database
mysql_select_db ($database);
// Make sure the user actually
// selected and uploaded a file
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Create the query and insert
// into our database.
$query = "INSERT INTO members ";
$query .= "(image) VALUES ('$data')";
$results = mysql_query($query, $link);
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
// Close our MySQL Link
mysql_close($link);
?>
1° You need to pass a referecence for what Data you are trying to update, like the Primary Key Id From Table.
2° Update SQL should be like it
$image = mysql_real_escape_string($unsafe_image);
$id = mysql_real_escape_string($unsafe_id);
$query = "UPDATE members SET image = '$data' WHERE id_image = $id";
$results = mysql_query($query, $link);
The codes I'm working on are a bit confusing since I didn't make this one. But what I want to do is get the login information from a different database. I can't just modify the config.php of the database connection cause it will mess up the whole system.
I tried the trick to connect 2 databases by storing different variables on mysql_connect. But in this case, its a bit confusing.
Is there another way to just change the database connection only once in the logging in process?
login.php (the php file once the login info is submitted)
include("inc/config.php");
$connection = mysql_connect($hostname, $user, $pass) or die ("Unable to connect!");
$query = "SELECT * FROM clients WHERE name = '$name' AND password = '$password'";
$result = mysql_db_query($database, $query, $connection);
$date_in = date("Y-m-d");
$time_in = date("H:i:s");
$client_accesslogin = $name;
if (mysql_num_rows($result) == 1)
{
session_start();
session_register('time_in');
session_register('date_in');
session_register('client_accesslogin');
session_register('remoteaddr');
$_SESSION['time_in']=$time_in;
$_SESSION['date_in']=$date_in;
$remoteaddr = $_SERVER['REMOTE_ADDR'];
$ipaddr = $_SERVER['REMOTE_ADDR'];
$client_accesslogin = $_SESSION['client_accesslogin'];
session_register("client_id");
session_register("client_name");
session_register("client_email");
session_register("client_company");
list($clientid, $name,$first_name,$last_name, $pass, $email, $company) = mysql_fetch_row($result);
$client_id = $clientid;
$client_name = $name;
$fname=$first_name;
$lname=$last_name;
$client_email = $email;
$client_company = $company;
$cisloggedin = 'Yes';
session_register("cisloggedin");
session_register("fname");
session_register("lname");
header("Location: menu.php");
mysql_free_result ($result);
mysql_close($connection);
}
$connection = mysql_connect($hostname, $user, $pass) or die ("Unable to connect!");
$query = "SELECT * FROM admins WHERE name = '$name' AND password = '$password'";
$result = mysql_db_query($database, $query, $connection);
$date_in = date("Y-m-d");
$time_in = date("H:i:s");
$accesslogin = $name;
if (mysql_num_rows($result) == 1)
{
session_start();
session_register('time_in');
session_register('date_in');
session_register('accesslogin');
session_register('remoteaddr');
$_SESSION['time_in']=$time_in;
$_SESSION['date_in']=$date_in;
$remoteaddr = $_SERVER['REMOTE_ADDR'];
$ipaddr = $_SERVER['REMOTE_ADDR'];
$accesslogin = $_SESSION['accesslogin'];
session_register("client_id");
session_register("client_name");
session_register("client_email");
list($clientid, $name, $pass, $email) = mysql_fetch_row($result);
$client_id = $clientid;
$client_name = $name;
$client_name = "admin";
$client_email = $email;
$isloggedin = 'Yes';
session_register("isloggedin");
header("Location: menu.php");
mysql_free_result ($result);
mysql_close($connection);
}
else
{
mysql_free_result ($result);
mysql_close($connection);
header("Location: index.php");
exit;
}
?>
That works. But If I remove the included config.php and just add the connection:
$database = "invoices";
$user = "root";
$pass = "";
$hostname = "localhost";
It doesn't login. I don't get it. the inc/config.php has some codes with the connection but why can't i just add the connection itself without using include?
I'm doing to assume that there's a dedicated page for login processing?
In which case you can just make a new config.php and connect to that db only on the login page?
A bit of your code or structure would help.
mysql_select_db() function sets the active MySQL database.
Syntax
bool mysql_select_db ( string database_name [, resource link_identifier])
mysql_select_db() attempts to select existing database on the server associated with the specified link identifier.
Returns TRUE on success, or FALSE on failure.
We can select database in mysql server by using mysql_select_db function. mysql_select_db() selects the current active database on the server that is associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to set a link as if mysql_connect() was called without arguments.
Made a function to connect to your database, also to close your connection.
function connect(user, pass, location)
function disconnect()
then you connect to your first db, do your operations. Close it and then open a new connection to the other db and do also your operations.
If you want to maintain 2 connections at the time, you could save your instances to variables
and do:
mysqli_select_db($instance1, 'SELECT ...');
mysqli_select_db($instance2, 'SELECT ...');
Also escape your variables in your query :)
Essentially, I am trying to print out information in JSON so that I can communicate with my app, but I cannot connect to the MySQL database from a php script for some odd reason. What could it be that causes the error:
Warning: mysql_connect() [function.mysql-connect]: Lost connection to MySQL server during query in /srv/disk11/1158855/www/(myphpwebsite)/lib.php on line 13
Could not connect: Lost connection to MySQL server during query.
Also, line 13 is indicating the line in lib.php:
mysql_connect ( $dbhost, $dbuser, $dbpass) or die("Could not connect: ".mysql_error());
It should also be noted that this is a followup to a previous question in case anyone wanted to track down the source: MySQL issue connecting to site with php.
Lastly, I get the same error from both a localhost and a remote server using mysql
lib.php
<?
//Database Information
$dbhost = "31.170.160.76";
$dbname = "testdatabase";
$dbuser = "(personalinformation)";
$dbpass = "tested123";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass) or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
//executes a given sql query with the params and returns an array as result
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
//loads up the source image, resizes it and saves with -thumb in the file name
function thumb($srcFile, $sideInPx) {
$image = imagecreatefromjpeg($srcFile);
$width = imagesx($image);
$height = imagesy($image);
$thumb = imagecreatetruecolor($sideInPx, $sideInPx);
imagecopyresized($thumb,$image,0,0,0,0,$sideInPx,$sideInPx,$width,$height);
imagejpeg($thumb, str_replace(".jpg","-thumb.jpg",$srcFile), 85);
imagedestroy($thumb);
imagedestroy($image);
}
?>
Index.php
<?
session_start();
require("lib.php");
require("api.php");
header("Content-Type: application/json");
switch ($_POST['command']) {
case "login":
login($_POST['username'], $_POST['password']); break;
case "register":
register($_POST['username'], $_POST['password']); break;
}
exit();
?>
api.php
<?php
function errorJson($msg){
print json_encode(array('error'=>$msg));
exit();
}
function register($user, $pass) {
//check if username exists
$login = query("SELECT username FROM login WHERE username='%s' limit 1", $user);
if (count($login['result'])>0) {
errorJson('Username already exists');
//try to register the user
$result = query("INSERT INTO login(username, pass) VALUES('%s','%s')", $user, $pass);
if (!$result['error']) {
//success
login($user, $pass);
} else {
//error
errorJson('Registration failed');
}
}
}
function login($user, $pass) {
$result = query("SELECT IdUser, username FROM login WHERE username='%s' AND pass='%s' limit 1", $user, $pass);
if (count($result['result'])>0) {
//authorized
$_SESSION['IdUser'] = $result['result'][0]['IdUser'];
print json_encode($result);
} else {
//not authorized
errorJson('Authorization failed');
}
}
?>
As this is on the "connect" line, the server has been found (otherwise you get a different message) but you've not negotiated your log in.
Straight from the manual:
More rarely, it can happen when the client is attempting the initial connection to the server. In this case, if your connect_timeout value is set to only a few seconds, you may be able to resolve the problem by increasing it to ten seconds, perhaps more if you have a very long distance or slow connection.
If that isn't it, it's either a network problem or your connection has been terminated mid-authentication. Check that your mysql host doesn't have some weird validation that you're coming from a particualr IP (I say weird, as there are more standard ways of managing it than killing the authentication mid-flow), or try your PHP script from a a server that is closer to the MySQL server (closer in terms of network speed).
I figured out what was the matter. It turns out that my php code further down was conflicting with the login. That's why it wouldn't authenticate on multiple remote MySQL's and my own Localhost