Currently, I developed a project that requires user to upload image from Computer. I do this from an example on the internet. For now, the column image at the database uses "BLOB" and the upload successful.
But, I don't want to uses BLOB, I want to change to LONGTEXT. When I change this format, the image saved to the database is successful but the image display is broken. The encode text and column image also looks weird. Can I know what is the problem? Below is the code
<?php
$connect = mysqli_connect("localhost", "root", "", "imagephp");
if(isset($_POST["insert"]))
{
$file = addslashes(file_get_contents($_FILES["image"]["tmp_name"]));
$query = "INSERT INTO tbl_images(name) VALUES ('$file')";
if(mysqli_query($connect, $query))
{
echo '<script>alert("Image Inserted into Database")</script>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br /><br />
<div class="container" style="width:500px;">
<h3 align="center">Insert and Display Images From Mysql Database in PHP</h3>
<br />
<form method="post" enctype="multipart/form-data">
<input type="file" name="image" id="image" />
<br />
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-info" />
</form>
<br />
<br />
<table class="table table-bordered">
<tr>
<th>Image</th>
</tr>
<?php
$query = "SELECT * FROM tbl_images ORDER BY id DESC";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
echo '
<tr>
<td>
<img src="data:image/jpeg;base64,'.base64_encode($row['name'] ).'" height="200" width="200" class="img-thumnail" />
</td>
</tr>
';
}
?>
</table>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#insert').click(function(){
var image_name = $('#image').val();
if(image_name == '')
{
alert("Please Select Image");
return false;
}
else
{
var extension = $('#image').val().split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
alert('Invalid Image File');
$('#image').val('');
return false;
}
}
});
});
</script>
Hope someone can help me. Thanks!
Related
I'm following a tutorial by mmtuts on youtube to show how to post comments to a myphpadmin database. All of my code is exactly the same as his, but I'm working from a different starting point becuase I already had a website I was working on and I just wanted to add the new code.
Basically, the video showed the code working flawlessly and my posts do not show up in the database like his did.
https://www.youtube.com/watch?v=4pPGOF5MI4U
".setComments($conn)." on the second document of code is blue instead of white like in the video.
<?php
require 'includes/dbh.inc.php';
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="This is an example of a meta description. This will often show up in search results.">
<meta name=viewport content="width=device-width, initial-scale=1">
<title>TAG</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<div id="headerContainer">
<?php
if (isset($_SESSION['userID'])) {
$id = $_SESSION['userID'];
$sqlImg = "SELECT * FROM profileimg WHERE userid='$id'";
$resultImg = mysqli_query($conn, $sqlImg);
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
if ($rowImg['status'] == 0) {
$filename = "profilepics/profile".$id."*";
$fileinfo = glob($filename);
$fileext = explode(".", $fileinfo[0]);
$fileactualext = $fileext[1];
echo "<div class=userPicture><img src='profilepics/profile".$id.".".$fileactualext."?".mt_rand()."'></div>";
}
else {
echo "<div class='userPicture'><img src='profilepics/noUser.png'></div>";
}
}
echo '
<div class="userName">'. $_SESSION['userUserName'] .'</div>
<div id="logoutForm">
<form action="includes/logout.inc.php" method="post">
<button type="Submit" name="logout-submit">Logout</button>
</form>
</div>
<div class="upload">
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit" name="submit">Profile Image</button>
</form>
</div>
';
}
else {
echo '
<div class="userPicture"><img src="profilepics/noUser.png"></div>
<div class="userName">You are not logged in!</div>
<div id="loginForm">
<form action="includes/login.inc.php" method="post">
<input type="text" name="mailuid" placeholder="Username/E-mail">
<input type="password" name="password" placeholder="Password">
<button type="Submit" name="login-submit">Login</button>
</form>
</div>
<div id="signupForm">
or Signup
</div>
';
}
?>
</div>
<?php
require "header.php";
date_default_timezone_set('America/Chicago');
include 'includes/comments.inc.php';
?>
<div class="homeBody">
<p>Starting Filler</p>
<p>-</p>
<p>-</p>
<p>-</p>
<video width="320" height="240" controls>
<source src="videos/sample.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<?php
echo "<form method='POST' action='".setComments($conn)."'>
<input type='hidden' name='uid' value='Anonymous'>
<input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
<textarea name='message'></textarea><br>
<button type='submit' name='commentSubmit'>Comment</button>
</form>";
?>
<?php
function setComments($conn) {
if (isset($POST['commentSubmit'])) {
$uid = $_POST['uid'];
$date = $_POST['date'];
$message = $_POST['message'];
$sql = "INSERT INTO comments (uid, date, message) VALUES ('$uid', '$date', '$message')";
$result = $conn->query($sql);
}
}
<?php
$servername = "localhost";
$dBUsername = "root";
$dBPassword = "thisisnotmyactualpassword";
$dBName = "tagloginsystem";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
All I want is for the posts to make it into the database.
Try making a separate PHP-file and have your action attribute inside the form tag point to it. Right now it looks like you are running the function in the action attribute. In the PHP-file you can run your PHP function and write the PHP you need.
EX:
<form method='POST' action="includes/comments.php">
I was missing the "_" in $_POST on the 3rd page of code
Im working usign PDO and PHP.
This is my table in Postgre
CREATE TABLE public.img
(
id integer NOT NULL DEFAULT nextval('img_id_seq'::regclass),
nombre bytea
)
When i store the file data i use this method
<?php
$db = new PDO("pgsql:host=localhost;port=5432;dbname=sac;user=postgres;password=insertPass");
if(isset($_POST["insert"]))
{
$file = pg_escape_bytea(addslashes(file_get_contents($_FILES["image"]["tmp_name"])));
$sql = 'INSERT INTO img (nombre) VALUES (?)';
$ISp_Res = $db->prepare($sql);
$ISp_Res->bindParam(1, $file);
$ISp_Res->execute();
}
?>
And in the table the values are
ID nombre
4; "\377\330\377\340\\0\020JFIF\\0\001\001\\0\\0\001\\0\001\\0\\0\377\341\\0\234Exif\\0\\0II*\\0\010\\0\\0\\0\007\\0\\0\001\003\\0\001\\0\\0\\0S\002\\0\\0\001\001\003\\0\001\\0\\0\\0\026\002\\0\\0\022\001\003\\0\001\\0\\0\\0\\0\\0\\0\\02\001\002\\0\024\\0\\0\\ (...)"
And the form that i retrieve the values in my table
<?php
$query = "SELECT * FROM img ORDER BY id DESC";
$db = new PDO("pgsql:host=localhost;port=5432;dbname=sac;user=postgres;password=insertPass");
$result = $db->prepare($query);
$results = $result->execute();
$results = $result->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row) {
echo($row['nombre']);
$dat= pg_unescape_bytea($row['nombre']);
echo "<img src='".$dat."'";
}
?>
However when i try to retrieve the information i just get Resource id #2 and a Warning: pg_unescape_bytea() expects parameter 1 to be string
This is the testView
<script>
$(document).ready(function(){
$('#insert').click(function(){
var image_name = $('#image').val();
if(image_name == '')
{
alert("Please Select Image");
return false;
}
else
{
var extension = $('#image').val().split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
alert('Invalid Image File');
$('#image').val('');
return false;
}
}
});
});
</script>
<?php
$db = new PDO("pgsql:host=localhost;port=5432;dbname=sac;user=postgres;password=insertPass");
if(isset($_POST["insert"]))
{
$file = pg_escape_bytea(addslashes(file_get_contents($_FILES["image"]["tmp_name"])));
$sql = 'INSERT INTO img (nombre) VALUES (?)';
$ISp_Res = $db->prepare($sql);
$ISp_Res->bindParam(1, $file);
$ISp_Res->execute();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Insert and Display Images From Mysql Database in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br /><br />
<div class="container" style="width:500px;">
<h3 align="center">Insert and Display Images From Mysql Database in PHP</h3>
<br />
<form method="post" enctype="multipart/form-data">
<input type="file" name="image" id="image" />
<br />
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-info" />
</form>
<br />
<br />
<table class="table table-bordered">
<tr>
<th>Image</th>
</tr>
<?php
$query = "SELECT * FROM img ORDER BY id DESC";
$db = new PDO("pgsql:host=localhost;port=5432;dbname=sac;user=postgres;password=insertPass");
$result = $db->prepare($query);
$results = $result->execute();
$results = $result->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row) {
echo($row['nombre']);
$dat= pg_unescape_bytea($row['nombre']);
echo "<img src='".$dat."'";
}
?>
</table>
</div>
</body>
</html>
Please tell me where im doing it wrong :(
Don't use addslashes() while inserting.
$target_file = '/path/to/file.jpg';
$img = fopen($target_file, 'r');
$data = fread($img, filesize($target_file));
$file = pg_escape_bytea($data);
While fetching data use
ob_start();
fpassthru($row['nombre']);
$dat= ob_get_contents();
ob_end_clean();
$dat= "data:image/*;base64," . base64_encode($dat);
echo "<img src='".$dat."'";
I have code for image upload and view in php and MySQL. After click on "Submit" button in "imageUpload.php" page image is stored in database. but not displaying in "listImages.php" page. I don't know what's the problem. I see "image not displaying when uploading in php" but its seems different solution for me. here is my code please have a look where i am wrong.
imageUpload.php :
<?php
/* CREATE TABLE IF NOT EXISTS `output_images`
(
`imageId` tinyint(3) NOT NULL AUTO_INCREMENT,
`imageType` varchar(25) NOT NULL DEFAULT '',
`imageData` mediumblob NOT NULL,
PRIMARY KEY (`imageId`)
) */
if(count($_FILES) > 0) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
mysqli_connect("localhost", "root", "");
mysqli_select_db ("test");
$imgData =addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
$sql = "INSERT INTO output_images(imageType ,imageData)
VALUES('{$imageProperties['mime']}', '{$imgData}')";
$current_id = mysqli_query($sql) or die("<b>Error:</b> Problem on Image Insert<br/>" . mysqli_error());
if(isset($current_id)) {
header("Location: listImages.php");
}
}
}
?>
<HTML>
<HEAD>
<TITLE>Upload Image to MySQL BLOB</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<form name="frmImage" enctype="multipart/form-data" action="" method="post" class="frmImageUpload">
<label>Upload Image File:</label><br/>
<input name="userImage" type="file" class="inputFile" />
<input type="submit" value="Submit" class="btnSubmit" />
</form>
</div>
</BODY>
</HTML>
listImages.php :
<?php
$conn = mysqli_connect("localhost", "root", "");
mysqli_select_db("test");
$sql = "SELECT imageId FROM output_images ORDER BY imageId DESC";
$result = mysqli_query($sql);
?>
<HTML>
<HEAD>
<TITLE>List BLOB Images</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<?php
while($row = mysqli_fetch_array($result)) {
?>
<img src="imageView.php?image_id=<?php echo $row["imageId"]; ?>" /><br/>
<?php
}
mysqli_close($conn);
?>
</BODY>
</HTML>
imageView.php :
<?php
$conn = mysqli_connect("localhost", "root", "");
mysqli_select_db("test") or die(mysqli_error());
if(isset($_GET['image_id'])) {
$sql = "SELECT imageType,imageData FROM output_images WHERE imageId=" . $_GET['image_id'];
$result = mysqli_query("$sql") or die("<b>Error:</b> Problem on Retrieving Image BLOB<br/>" . mysqli_error());
$row = mysqli_fetch_array($result);
header("Content-type: " . $row["imageType"]);
echo $row["imageData"];
}
mysqli_close($conn);
?>
this would help you
<a href="imageView.php?image_id=<?php echo $row["imageId"]; ?>">
<img src="<?php echo $row['imagedata']; ?>" alt="my picture" height="128" width="128" />
</a>
it should be
$conn=mysqli_connect("ur_servername_ex_localhost","ur_username","ur_password","ur_db");
mysqli_query($conn, $sql);
I am creating a website for my Computer Science project.
I am also new to PHP/HTML coding.
Basically, the idea is this. I have a login page which either takes you into the website or doesn't let you in. However, I want the website to tell the user that the username/pass isn't correct when the get rejected.
Here is the login page:
<html>
<link rel="stylesheet" type="text/css" href="Style.css">
<body>
<center>
<h1 style="font-size:70px;">FitnessHub<h1>
<p>Enter Username & Password to get started</P>
<form action="Welcome.php" method="post">
<table>
<tr>
<td><input type="text" name="username" placeholder="Username" style="width:400px;height:30px;"></td>
</tr>
<tr>
<td><input type="password" name="password" placeholder="Password" style="width:400px;height:30px;"></td>
</tr>
</table>
<input type="submit" value="Login" style="width:100px;height:30px;">
<br>
</form>
<img src="fitnesshub.png" alt="logo" style="width:400px;height=300px;">
</center>
</body>
</html>
And here is the welcoming page when you successfully login:
<html>
<link rel="stylesheet" type="text/css" href="Style.css">
<body>
<h1> Hello <?php echo $_REQUEST[username] ?> </h1>
<p style="Font-Size:15px;">FitnessCenter can be used to book customers into multiple services<br>
Use the buttons to start using the database
</p>
<?php
$db = new mysqli("127.0.0.1", "root", "root", "fitnessbooking");
$query= $db->query("select Username from users where Username = '$_POST[username]' and Pass = '$_POST[password]'");
if ($query->num_rows ==1){
echo "";
}
else {
header("Location: http://localhost/pages/login.php");
exit;
}
?>
</body>
</html>
As I said, I am no expert at website stuff so please try to explain things in a way I can understand!
Thanks
In the redirection add ?fail=1 to pass the parameter
header("Location: http://localhost/pages/login.php?fail=1");
In the login page add
<?php
if ( isset($_GET['fail']) && $_GET['fail'] == 1 )
{
echo "Try again:)";
}
?>
Do all things in the login page like this.
<?php
session_start();
if(isset($_SESSION['auth'])){
header('Location: logged_in.php');
die();
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$db = new mysqli("127.0.0.1", "root", "root", "fitnessbooking");
if ($db->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $db->prepare('select Username from users where Username = ? and Pass = ?');
$stmt->bind_param('ss', $_POST['username'], $_POST['password']);
$stmt->execute();
if($stmt->num_rows > 0){
$_SESSION['auth'] = true;
header('Location: logged_in.php');
die();
}
else{
$error_message = "Username Or password are invalid";
}
}
?>
<html>
<link rel="stylesheet" type="text/css" href="Style.css">
<body>
<center>
<h1 style="font-size:70px;">FitnessHub<h1>
<p>Enter Username & Password to get started</P>
<?php
//Display the error message
if (isset($error_message)){
echo "<p><strong>$error_message</strong></p>"
}
?>
<form action="Welcome.php" method="post">
<table>
<tr>
<td><input type="text" name="username" placeholder="Username" style="width:400px;height:30px;"></td>
</tr>
<tr>
<td><input type="password" name="password" placeholder="Password" style="width:400px;height:30px;"></td>
</tr>
</table>
<input type="submit" value="Login" style="width:100px;height:30px;">
<br>
</form>
<img src="fitnesshub.png" alt="logo" style="width:400px;height=300px;">
</center>
</body>
</html>
The other page leave like that:
<?php
session_start();
if(!isset($_SESSION['auth'])){
die('Access denied');
}
<html>
<link rel="stylesheet" type="text/css" href="Style.css">
<body>
<h1> Hello User </h1>
<p style="Font-Size:15px;">FitnessCenter can be used to book customers into multiple services<br>
Use the buttons to start using the database
</p>
</body>
</html>
If you want, store the username in the session to have it usable.
Use this sample.
<html>
<link rel="stylesheet" type="text/css" href="Style.css">
<body>
<center>
<?php if((!empty($_GET['login'] )&& ($_GET['login'] == 'false')): ?>
<p>username or password incorrect</P>
<?php endif;?>
<h1 style="font-size:70px;">FitnessHub<h1>
<p>Enter Username & Password to get started</P>
<form action="Welcome.php" method="post">
<table>
<tr>
<td><input type="text" name="username" placeholder="Username" style="width:400px;height:30px;"></td>
</tr>
<tr>
<td><input type="password" name="password" placeholder="Password" style="width:400px;height:30px;"></td>
</tr>
</table>
<input type="submit" value="Login" style="width:100px;height:30px;">
<br>
</form>
<img src="fitnesshub.png" alt="logo" style="width:400px;height=300px;">
</center>
</body>
</html>
And your wellcome page is.
<html>
<link rel="stylesheet" type="text/css" href="Style.css">
<body>
<h1> Hello <?php echo $_REQUEST[username] ?> </h1>
<p style="Font-Size:15px;">FitnessCenter can be used to book customers into multiple services<br>
Use the buttons to start using the database
</p>
<?php
$db = new mysqli("127.0.0.1", "root", "root", "fitnessbooking");
$query= $db->query("select Username from users where Username = '$_POST[username]' and Pass = '$_POST[password]'");
if ($query->num_rows ==1){
echo "";
}
else {
header("Location: http://localhost/pages/login.php?login=false");
exit;
}
?>
</body>
</html>
I want to upload an image and insert it into the database from different page. I want to create an admin panel where you can upload an image to image sider but the image slider is in a different page. It's working when my form method is inside the index.php, but when I put it to my admin.php it's not working. I think I need a GET method?
Can someone give me idea what method, requirements to do that? I'm new to php and sql.
Here is my index.php code this is where I want to show the slide.
<?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=\'index.php\';</script>';
}
?>
<!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 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();
}
?>
and here is my admin.php code this is where i want to upload the image.
<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 index.php this is where i want to show the slide.
and this is my admin.php where i want to upload the image of my image slider.
I solved it myself by putting the php code in my admin.php
<?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>