I've create a table where I've saved images through "LongBLOB". I need to show those images.
i can save images in my sql but when i want to read and display them i have a problem,
"can not be displayed because it contains errores"
im usi8ng this code to save the image to my sql table
<?php
$username = "root";
$password = "";
$host = "localhost";
$database = "imgtest";
$link = mysql_connect($host, $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database);
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$namee = $_FILES['image']['name'];
mysql_query("INSERT INTO image(cap,image) VALUES ('$namee','$data')");
}
?>
and im using this code to read and display the image from my sql table
<?php
$con=mysqli_connect("localhost","root","","imgtest");
$wich=$_POST['wich'];
$resoult=mysqli_query($con,"SELECT * FROM image WHERE id LIKE '$wich'");
$imgd = $_GET['img'];
$row = mysqli_fetch_array($resoult);
$image = $row['image'];
header("content-type:image/jpeg");
echo $image;
?>
anyone can help me with this??
It is strongly advised to store images within your file structure (a directory on your server, cloud server, or other accessible location) and only keep a reference such as a url, file name or path path in the database in order to recreate a link or path to the actual image. It is a bad practice to keep images in a database.
Why are you using mysql_ library - it is deprecated.
You need to store binary data. Use prepared statements. In that way you get back binary data.
From 2 you can dump addslashes. That is the root of the problem
Related
I am working on a school project that let users upload video files to a server. Server will compress the video using ffmpeg and store the file in upload folder. Other users will be able to stream the uploaded videos.
My question is how do i retrieve the video that ffmpeg generated and store the link in the database?
i am using this code but it only retrieve path of the original video.
$filePath = dirname(__FILE__);
partial code of Upload.php
$target_dir = "upload/"; //where you want to upload the files to
$target_file = $target_dir.basename($_FILES['file']['name']);
$fileType = pathinfo($target_file, PATHINFO_EXTENSION);
$newFileName = $target_dir.sha1(pathinfo(basename($_FILES['file']['name']), PATHINFO_FILENAME)).'-'.time().'.'.$fileType;
move_uploaded_file($_FILES['file']['tmp_name'], $newFileName);
$unique_id = rand(1000000,9999999);
shell_exec("C:\\ffmpeg\\bin\\ffmpeg.exe -i ".$newFileName." -vcodec libx264 -crf 20 \"upload\\{$newFileName}\" > logfile.txt 2>&1");
/// save information into database
$username = "root";
$password = "";
$hostname = "localhost";
$dbname = "test_database";
//connect to the database
$dbc = mysqli_connect($hostname, $username, $password, $dbname) or die ("could not connect to the database");
//execute the SQL query and return records
$result = mysqli_query($dbc, "INSERT INTO `viewvideo` (`vID`, 'video_id`, `video_link`) VALUES ('', '".$unique_id."', '".$newFileName."')");
if(!$result){echo mysqli_error($dbc); }
echo $result;
/*
declare in the order variable
$result = mysqli_query($dbc, $sql); //order executes
if($result){
echo("<br>Input data is succeed");
} else{
echo("<br>Input data is fail");
}
*/
//close the connection
mysqli_close($dbc);
output
Remember to move the uploaded file to a directory of your choice. A way to prevent files overwriting each other is creating a new name for it. Do this when the upload is a success.
Properly uploading & adding the video to the database
$target_dir = "video/"; //where you want to upload the files to
$target_file = $target_dir.basename($_FILES['file']['name']);
$fileType = pathinfo($target_file, PATHINFO_EXTENSION);
$newFileName = $target_dir.sha1(pathinfo(basename($_FILES['file']['name']), PATHINFO_FILENAME)).'-'.time().'.'.$fileType;
move_uploaded_file($_FILES['file']['tmp_name'], $newFileName);
After that you'll have to create a table & insert two core things; a unique/token generated ID for the video and the $newFileName path.
You can either use a function which generates a token/id which includes alpha-numeric characters or something simple as this
$unique_id = rand(1000000,9999999);
Lets consider you have a table videos with 3 columns; vID, video_id & video_link
vID should be an auto incrementing INT. video_id would be a INT and the video_link a TEXT type.
After that it's SQL.
$result = mysqli_query($db_connection, "INSERT INTO `videos` (`vID`, video_id`, `video_link`) VALUES ('', '".$unique_id."', '".$newFileName."'");
if(!$result){echo mysqli_error($db_connection); }
Retrieving it would be something like this. Be sure to add this on another page. Let's consider stream.php as the page's name for streaming the video.
if(isset($_GET['id'])){
$id = trim($_GET['id']);
//check if it exists
$result = mysqli_query($db_connection , "SELECT `video_id`, `video_link` FROM `videos` WHERE `video_id`='".$id."'");
$count = mysqli_num_rows($result);
//does it exist?
if($count>0){
//exists, so fetch it in an associative array
$video_arr = mysqli_fetch_assoc($result);
//this way you can use the column names to call out its values.
//If you want the link to the video to embed it;
echo "Video Link: ".$video_arr['video_link'];
}else{
//does not exist
}
}
And finally, creating a link to it: http://your-website.com/stream.php?id=video id here
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);
I have searched a lot on about this but I did not find solution.
I have images in a directory in server. And I want to upload those images ( Not Just image Paths) to MySQL database using longblob with PHP.
I know that storing images in the database is not recommended but that is the requirement of my project so I want use this method.
Please suggest me, How can I do that?
Thanks to all.
<?php
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("your databse name");
// 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'];
$name=$_POST['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 image2 ";
$query .= "(image,name) VALUES ('$data','$name')";
$results = mysql_query($query, $con);
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
// Close our MySQL Link
mysql_close($con);
?>
Here's the code:
<?php
// For use in creating individual page
$tpl_file = "submission.php";
$tpl_path = "templates/";
$submissions_path = "submissions/";
// For use in querying submitter name
$username = $_GET['username'];
session_start();
$_SESSION['username'] = $username;
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$name = $_POST['name'];
$filename = $_POST['filename'];
$submitter = $username;
list($width, $height) = getimagesize("$filename");
$type = exif_imagetype($_POST['filename']);
$checkuser = mysql_query("SELECT filename FROM images WHERE filename='$filename'");
$filename_exist = mysql_num_rows($checkuser);
if($filename_exist > 0){
echo "I'm sorry but this image has already been submitted. Please feel free to try another.";
unset($filename);
include 'upload.php';
exit();
}
if (exif_imagetype($_POST['filename']) == IMAGETYPE_GIF) {
echo "Sorry, but we can't accept GIFs. Please feel free to try uploading another.";
unset($filename);
include 'upload.php';
exit();
}
$query = "INSERT INTO images (name, filename, submitter, width, height, type)
VALUES('$name', '$filename', '$submitter', '$width', '$height', $type)";
mysql_query($query) or die(mysql_error());
mysql_close();
echo "Thanks for your submission!<br/> Upload another <a href='/~lyons/upload.php'>here</a>!";
$tpl = file_get_contents($tpl_path.$tpl_file);
$php_file_name = $name.".php";
$fh = fopen($submissions_path.$php_file_name, "w");
fwrite($fh, $tpl);
fclose($fp);
?>
When a user submits a picture, it is supposed to automatically create a page based on a template. Here's the code for the template:
<html>
<title><?php echo $name; ?></title>
<head>
</head>
<body>
<h1><?php echo $name ?></h1>
Posted by: <?php echo $username ?>
<br/>
<img src="<?php echo $filename ?>"/>
</body>
</html>
As you might have already guessed, I want it to put in values for name, username, and filename that were derived in the first script where they submit the picture. However, it seems they don't carry over. The page is created, but where ever it's supposed to echo the values for the variables, it is blank. How can I include the values for those variables that I want to use in the created page?
Thanks in advance to whoever can help me.
I would suggest using a string like %name%, %username% etc. to mark placeholders for variables.
Then, before writing to the file, try something like this:
$tpl = preg_replace("(%([a-z_][a-z0-9_]*)%)ie",'$$1',$tpl);
This will find, for example, %filename% and replace it with the contents of the variable $filename.
Look up PHP Sessions
It is a built-in feature to PHP used for exactly what you're doing.
Sessions store data on a per-user basis however, so if you're wanting other people to see the variables, you're going to have to use either a database or saving to a file.
Here is the site.
I have the submit page, and a form action to a page that queries the submission info into my database. I'll include that code below. What I want to do, is have it create an individual page for each submission. However, I'm getting tons of errors when I try to upload. It uploads but it definitely doesn't create new page. the I have a template form which I'll show you, but first, here's the upload page:
<?php
// For use in creating individual page
$tpl_file = "submission.php";
$tpl_path = "/~lyons/templates/";
$submissions_path = "/~lyons/submissions";
// For use in querying submitter name
$username = $_GET['username'];
session_start();
$_SESSION['username'] = $username;
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$name = $_POST['name'];
$filename = $_POST['filename'];
$submitter = $username;
list($width, $height) = getimagesize("$filename");
$type = exif_imagetype($_POST['filename']);
$checkuser = mysql_query("SELECT filename FROM images WHERE filename='$filename'");
$filename_exist = mysql_num_rows($checkuser);
if($filename_exist > 0){
echo "I'm sorry but this image has already been submitted. Please feel free to try another.";
unset($filename);
include 'upload.php';
exit();
}
if (exif_imagetype($_POST['filename']) == IMAGETYPE_GIF) {
echo "Sorry, but we can't accept GIFs. Please feel free to try uploading another.";
unset($filename);
include 'upload.php';
exit();
}
$query = "INSERT INTO images (name, filename, submitter, width, height, type)
VALUES('$name', '$filename', '$submitter', '$width', '$height', $type)";
mysql_query($query) or die(mysql_error());
mysql_close();
echo "Thanks for your submission!<br/> Upload another <a href='/~lyons/upload.php'>here</a>!";
$placeholders = array("{name}", "{filename}", "{username}");
$tpl = file_get_contents($tpl_path.$tpl_file);
$new_member_file = str_replace($placeholders, $data, $tpl);
$php_file_name = $username.".php";
$fp = fopen($submissions_path.$php_file_name, "w");
fwrite($fp, $new_submission_file);
fclose($fp);
?>
And here's the template file (submission.php)
<html>
<title>{name}</title>
<head>
</head>
<body>
<h1>{name}</h1>
Posted by: {username}
<br/>
<img src="{filename}"/>
</body>
</html>
It looks like you might have a path issue. When you use the path "/~lyons" you may not be pointing to the directory you want. Try making the changes below:
// For use in creating individual page
$tpl_file = "submission.php";
//$tpl_path = "/~lyons/templates/";
$tpl_path = "templates/";
And then please post the new error message(s), if any.
To help you in debugging, try turning error reporting and error display on.
// add after <?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
Opening the file is probably failing, for better error control try this:
$fp = #fopen($submissions_path.$php_file_name, "w");
if (!$fp) {
die('Failed to open file! Reason: ' . $php_errormsg);
}
I think your paths are incorrect, most likely the following 2 lines need to be changed to use a full path.
// change
$tpl_path = "/~lyons/templates/";
$submissions_path = "/~lyons/submissions";
// to
$tpl_path = $_SERVER['DOCUMENT_ROOT'] . "/~lyons/templates/";
$submissions_path = $_SERVER['DOCUMENT_ROOT'] . "/~lyons/submissions";
When you go to open the file, it is trying to open /~lyons/templates/ which is a directory that does not exist, it is probably something like /home/lyons/public_html/templates/ or /home/something/public_html/~lyons/templates or /usr/local/apache2/htdocs/~lyons/templates etc. $_SERVER['DOCUMENT_ROOT'] should fill in the correct value, but in few cases you may need to manually set the correct path and prepend it to your $tpl_path and $submissions_path.
**save the "submission.php" in root folder**
`$tpl_file = "submission.php";`
**create "templates/`" folder in root folder**
`$tpl_path = "templates/";`