I am trying to insert image in my database using php and then display it using another php file.. but I am having problem while displaying it..
Through this code I am trying to insert image in my database this is stored in photography.php:
<?php
$servername = "********";
$username = "*******";
$password = "*******";
// Create connection
$conn = new mysqli($servername, $username, $password,"*****");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name=$_POST['name'];
//$file=$_FILES['userfile'];
if(isset($_POST['submit']))
{
if($name!=""){
$imgData =addslashes (file_get_contents($_FILES['userfile']['tmp_name']));
$insert="Insert into photograph_submission(Name,Photograph,names) values('".$name."','".$imgData."', '".$_FILES['userfile']['name']."')";
header('Location: thank.html');
if($conn->query($insert)===FALSE){
echo "Error: " . $insert . "<br>" . $conn->error;
}
echo "<meta http-equiv='refresh' content='0'>";
}
else{
$message = "Please enter all * marked details..\\nTry again.";
echo "<script type='text/javascript'>alert('$message'); window.location = 'http://reflux.in/photography.html';</script>";
echo "<meta http-equiv='refresh' content='0'>";
}
}
//echo"<h1>Seems you have not entered all details<a href='http://reflux.in/photography.html'>Click to submit again</a></h1>";
?>
and through this I am trying to display image..... this is stored in display.php:
<?php
$servername = "***********";
$username = "*************";
$password = "**********";
// Create connection
$conn = new mysqli($servername, $username, $password,"u932729557_main");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$insert="Select Photograph from photograph_submission where Name='Umang Bajaj'";
if($conn->query($insert)===FALSE){
echo "Error: " . $insert . "<br>" . $conn->error;
}
$result = $conn->query($insert);
header("data:image/png;base64");
$row= $result->fetch_assoc();
echo base64_encode( $row['Photograph'] );
// echo '<img src="data:image/jpg;base64,'.base64_encode( $row['Photograph'] ).'"/>';
?>
When I open refux.in/display.php it doesnot display image...
I'll show you my example for create uploadImage and getImage
Upload image file
<?php
$target_dir = "uploadSlike/";
$target_file = $target_dir . basename($_FILES["UploadSlike"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["UploadSlike"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["UploadSlike"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["UploadSlike"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["UploadSlike"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
GetImage
<?php
$id = $_GET['id'];
// do some validation here to ensure id is safe
$link = mysql_connect("localhost", "alex", "alex");
mysql_select_db("alex");
$sql = "SELECT avatar FROM users WHERE id=$id";
$result = mysql_query("$sql");
$row = mysql_fetch_assoc($result);
mysql_close($link);
header("Content-type: image/jpeg");
echo $row['avatar'];
?>
And then you can call in page where is $_SESSION['userid']
<div class="avatar"><img src="img/'.$image.'" />';</div>
Related
I found this code and it all works file uploads to the correct folder that is fine.
image - is main image that works it inserts one image name into the database field.
but when i try to insert all the names of the files uploaded in images field it only inserts the last file name.
$imageDirectory = "img/cars/" . $resultget->id . "";
$newDirName = generateRandomString(10);
$targetDir = $imageDirectory."/";
if (!file_exists($targetDir)) {
mkdir($targetDir, 0777, true);
} else {
$targetDir = $imageDirectory."/";
}
// Count total files
$fileCount = count($_FILES['the_file']['name']);
// Iterate through the files
for($i = 0; $i < $fileCount; $i++){
$target_dir = $imageDirectory."/";
$target_file = $target_dir . basename($_FILES["the_file"]["name"][$i]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["the_file"]["tmp_name"][$i]);
if($check !== false) {
//echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
$errorTxt = "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
$errorTxt = "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
// if ($_FILES["new_young"]["size"] > 500000) {
// $errorTxt = "Sorry, your file is too large.";
// $uploadOk = 0;
// }
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$errorTxt = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
$temp = explode(".", $_FILES["the_file"]["name"][$i]);
$newfilename = str_replace( '.', '', strval( microtime( true ) ) ) . '.' . end( $temp );
$target_file = $target_dir . $newfilename;
if (file_exists($target_file)) {
$errorTxt = "Sorry, file already exists.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
// if everything is ok, try to upload file
echo $errorTxt;
} else {
if (move_uploaded_file($_FILES["the_file"]["tmp_name"][$i], $target_file )) {
$checking = $resultget->images;
$checkimage = $resultget->image;
if(empty($checkimage)) {
$sqlimage = "UPDATE individual_cars SET image = '$newfilename' WHERE id = '$image_id'";
mysqli_query($mysqli, $sqlimage) or die(mysqli_error($mysqli));
}
foreach (array($newfilename) as $filename) {
if(empty($checking)) {
echo implode(',', $filename);
$sqlimage = "UPDATE individual_cars SET images = '" . implode(',', $filename) . "' WHERE id = '" . $resultget->id . "'";
mysqli_query($mysqli, $sqlimage) or die(mysqli_error($mysqli));
} else {
echo implode(',', $filename);
$sqlimage = "UPDATE individual_cars SET images = '," . implode(',', $filename) . "' WHERE id = '" . $resultget->id . "'";
mysqli_query($mysqli, $sqlimage) or die(mysqli_error($mysqli));
}
}
} else {
$errorTxt = "Sorry, there was an error uploading your file.";
}
}
}
Im checking images if empty because if a file name is already in that field i want it to continue so like this
example: 12345.png is already in there so if its not empty i want 12345.png, 54321.png and so on.
but its only inserting the last image name
sorry this is my first time posting.
How can i upload a video ? i did this with a image file but is not working with a video one only showing "error"
<?php
session_start();
if( !isset($_SESSION["username"]) ){
echo "<p id='errors'>Por favor, loguese, si no es redireccionado haga click <a href='log.php'>aqui</a></p>";
header("location: log.php");
}else{
};
$img = $_GET["fileToUploadv"];
$target_dir = "video/";
$target_file = $target_dir . basename($_FILES["fileToUploadv"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUploadv"]["tmp_name"]);
if($check !== false) {
$uploadOk = 1;
} else {
echo "The file is not an image!.";
$uploadOk = 0;
}
}
// Check if file already exists
// Check file size
// Allow certain file formats
if($imageFileType != "mp4" && $imageFileType != "mp4" ) {
echo "Only use a .JPG file.";
$uploadOk = 0;
}
if (file_exists($target_file)) {
unlink("video/video.mp4");
unlink("video/video.avi");
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Error.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUploadv"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUploadv"]["name"]). " has been uploaded.";
rename("video/".basename( $_FILES["fileToUploadv"]["name"]), "video/video.mp4");
rename("video/".basename( $_FILES["fileToUploadv"]["name"]), "video/video.avi");
} else {
echo "Error.";
}
}
?>
this script have filetouploadv that is with a form input to upload mp4 or avi that is html
<form id="formimg" method="post" action="uploadvideo.php" enctype="multipart/form-data">
<label for="uploadimgg">
<p id="selectimg">Please select a MP4 or AVI file to upload.</p>
<i class="fas fa-upload"></i>
</label>
<input id="uploadimgg" type="file" name="fileToUploadv" accept="video/mp4,video/avi">
<input class="hideshowsub" id="submitpho" type="submit">
</form>
should change the name to video and upload to video/ but is not working ...move_uploaded_file because that reutrn false and do the "error" message
<?php
require("config.php");
$sql = "SELECT * FROM inventario";
$result = mysqli_query($link, $sql);
echo("<table>");
echo("<tr>");
echo ("<th class='midtable'>"."Username"."</th>");
echo ("<th class='midtable'>"."Password"."</th>");
echo ("<th class='midtable'>"."</th>");
echo ( "</tr>");
while ($row = mysqli_fetch_array($result))
{
echo("<tr>");
echo("<td><div class='data'>".$row['username']."</div><div class='edit'><input type='text' name='usrname' value='".$row['username']."'></div></td>"."<td><div class='data'".$row['password']."<div class='edit'><input type='text' name='password' value='".$row['password']."'></div></td>"."<td>"."<i class='fas fa-edit'></i>"."<i class='fas fa-trash-alt'></i>"."</td>" );
echo("</tr>") ;
}; ?>
and then using jQuery hide the class data and show the class edit elements in the row and a submit button to update the values in the DB... and perhaps update just that row...
You can't upload videos because of this:
if($check !== false)
Turn it from false to true:
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUploadv"]["tmp_name"]);
if($check !== true) {
$uploadOk = 1;
} else {
echo "The file is not an image!.";
$uploadOk = 0;
}
}
Here is my code for image upload and inserting data into a Database, but it is not working properly, and also not showing any errors.
<?php
if(isset($_Post['submitbtn']))
{
$target_dir = "Resources/images/users/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
if (file_exists($target_file))
{
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if (file_exists($target_file))
{
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" )
{
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0)
{
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
}
else
{
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))
{
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
}
else
{
echo "Sorry, there was an error uploading your file.";
}
}
$qur = "insert into users values ('"+$_Post['Id']+"','"+$_Post['firstname']+"','"+$_Post['lastname']+"','"+$_Post['email']+"','"+$_Post['Password']+"','"+'shopkeeper'+"','"+$target_file+"')";
if(mysqli_query($con,$qur))
{
echo "Data Saved";
}
else
{
die("Connection failed: " . mysqli_error());
}
}
?>
I've made a plug-in for WordPress.
With this plug-in the admin can upload an image.
The problem is when i upload an image with space in it's name it don't show in the GUI.
I think the best way to fix this is to change the name from the image before uploading it.
This is the code in the admin page:
if (isset($post_array['add'])) {
// Save images
$tmp = explode(".", $afbeelding["name"]);
$time = time();
$name = $time . '.' . end($tmp);
$_FILES['afbeelding']['name'] = $name;
$check = getimagesize($_FILES["afbeelding"]["tmp_name"]);
if ($check !== false) {
//echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "Dit is geen afbeelding.";
$uploadOk = 0;
}
// Upload afbeelding
$projecten->upload($_FILES['afbeelding']);
// Save project
$result = $projecten->save($post_array);
if ($result) {
// Save was succesfull
$add = TRUE;
} else {
// Indicate error
$error = TRUE;
}
And this is the function for the image upload:
public function upload($afbeelding) {
$target_dir = IVS_CANVAS_PLUGIN_INCLUDES_UPLOAD_IMGS_DIR;
// $target_file = $target_dir . basename($afbeelding["name"]);
$target_file = $target_dir . $name;
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, deze afbeelding bestaat al.";
$uploadOk = null;
}
// Check file size
if ($afbeelding["fileToUpload"]["size"] > 500000) {
echo "Sorry, je afbeelding is te groot.";
$uploadOk = null;
}
// Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
echo "Sorry, alleen JPG, JPEG, PNG & GIF files zijn toegestaan.";
$uploadOk = null;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == null) {
echo "Sorry, je afbeelding is niet geüpload.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($afbeelding["tmp_name"], $target_file)) {
echo "De afbeelding " . basename($afbeelding["name"]) . " is geüpload.";
} else {
echo "Sorry, er ging iets fout tijdens het uploaden.";
}
}
return $uploadOk;
}
this is the save function:
public function save($input_array) {
global $wpdb;
// Insert query
$wpdb->query($wpdb->prepare("INSERT INTO `" . $wpdb->prefix . "ivs_canvas_tabel`
( `naam`, `level`, `beschrijving`, `afbeelding`, `status`)" .
" VALUES ( '%s', '%s', '%s', '%s', '%s');", $input_array['naam'], $input_array['level'], $input_array['beschrijving'], $_FILES['afbeelding']['name'], $input_array['status']));
// Error ? It's in there:
if (!empty($wpdb->last_error)) {
$this->last_error = $wpdb->last_error;
return FALSE;
}
return TRUE;
}
I have been messing with this for a few days now but can't figure it out.
I hope someone can help me!
The solution is in this line of code:
if (move_uploaded_file($afbeelding["tmp_name"], $target_file)) {
The Variable $target_file is the destination where your file should be uplaoded to. As you can see, its defined by the folowing line in your code:
$target_file = $target_dir . basename($afbeelding["name"]);
All you have to do is to adapt this line. What I like to do is using the timestamp for the image name.
$tmp = explode(".", $afbeelding["name"]);
$time = time();
$name = $time . '.' . end($tmp);
$target_file = $target_dir . $name;
I need to upload 3 details which are: Description, Number, and Image
The query does succeed, however I am having 2 different rows instead of a single row.
Please refer to the image:
For some reason the first row is skipping the ../uploads/ path, and applied on the bottom row as shown above.
Kindly find my PHP code, maybe there's something which I'm missing out.
<?php
$prov = json_decode(file_get_contents("php://input"));
require_once("connection.php");
$connection = connectToMySQL();
$proverbDescription = $prov->proverbDescription;
$proverbNumber = $prov->proverbNumber;
$imgPath = $prov->imgPath;
$target_dir = "../uploads/";
$target_file = $target_dir . basename($_FILES["imgPath"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["imgPath"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["imgPath"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["imgPath"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["imgPath"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
echo($proverbDescription);
echo($proverbNumber);
echo($imgPath);
$query = "INSERT INTO tbl_proverb (proverbDescription, proverbNumber, imgPath) VALUES ('$proverbDescription', '$proverbNumber', '$target_file')";
$result = mysqli_query($connection, $query)
or die("Error in query: ". mysqli_error($connection));
if(mysqli_affected_rows($connection) > 0){
$success = true;
}else{
$success = false;
}
?>
Thanks and Regards,
Hurka