I want to save the path of an image in my database, these images are generated with html2canvas and are saved in a directory, but when I generate them and save them in my database, a non-existent image name is generated and that is the one that stores me.
This is the code of how the image is saved in the database:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include './save.php';
$file = './images';
$route = $file. "/". $imgName;
$insert = $conexion->query("INSERT INTO images (img) VALUES ('$route')");
if ($insert) {
echo "<script>alert('successfully registered image')</script>";
}
else {
echo '<script>("Ups...Something's wrong")</script>';
}
}
This is the code that decodes the image for me and saves it in the folder:
$image = json_decode(file_get_contents("php://input"));
$image = $image->capture;
$image = str_replace("data:image/png;base64,", "", urldecode($image));
$image = base64_decode($image);
$imgName = "Image_" . uniqid() . ".png";
file_put_contents("images/$imgName", $image);
Related
i want to generate the thumbnail image from the uploaded video but the problem is that the thumbnail image is not generating. The uploaded video goes to the uploads folder but at this place the image is not generating..Please look at the code, and tell me where i am wrong.
public function add_video() { // move_upload_file code
if(!empty($_FILES['video']['name'])){
$tmp_name_array = $_FILES['video']['tmp_name'];
$n_array = $_FILES['video']['name'];
$exp = explode('.', $n_array);
$newnme = date('his').rand().'.'.end($exp);
$raw_name = explode('.', $newnme);
$full_path = base_url('uploads').'/'.$newnme;
$new_path = base_url('uploads').'/';
if(move_uploaded_file($tmp_name_array, "uploads/".$newnme))
{
$full_path = base_url('uploads').'/'.$newnme;
$new_path = base_url('uploads').'/';
print_r(exec("ffmpeg -i ".$full_path." ".$new_path.$raw_name[0].".jpg"));
echo "uploaded Successfully";
}
}else{
echo "not selected any file";
}
}
I want to change the uploaded image filename to a certain name for example:
Original name:city.jpg -> D0000_04042018094730121.jpg (D0000 is kodeDosen and the other is a microtime timestamp.)Here is my php code:uploadDosen.php
<?php
include 'connectdb.php';
if (isset($_POST['upload_Btn'])) {
$target = "uploaddosen/".basename($_FILES['gambar']['name']);
$kodeDosen = $_POST['kodeDosen'];
$namaJurnal = $_POST['namaJurnal'];
$tipePublikasi = $_POST['tipePublikasi'];
$status= $_POST['status'];
$gambar = $_FILES['gambar']['name'];
$sql = "INSERT INTO tbl_publikasi (kodeDosen,gambar,namaJurnal,tipePublikasi,status) VALUES ('$kodeDosen','$gambar','$namaJurnal',
'$tipePublikasi','$status')";
// execute query
mysqli_query($conn, $sql);
if (move_uploaded_file($_FILES['gambar']['tmp_name'],$target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
header("location:uploadTest.php");
}
?>
Instead of using
$target = "uploaddosen/".basename($_FILES['gambar']['name']);
Put your desired name in
$ext = end((explode(".", $_FILES['gambar']['name'])));
$target = "uploaddosen/MYNEWNAME." . $ext
$ext is taking the uploaded file name and getting the file extension. Then adding it together with your new name.
Just change the value of $target to your preferred filename.
You can try:
$extention = explode(".", $_FILES['gambar']['name']);
$extention = end($extention);
$target = $kodeDosen."_".str_replace(array(".", " "), "", microtime() ).".".$extention;
I have been trying to save uploaded images to a folder using PHP. I have been stuck on this because the name of the image saves differently to the database than the folder.
Database:assets/images/profile_pics/john_doe5a153efc8731359393775e3355df0b77n.jpg
Folder: john_doe_original.5a153efc8731359393775e3355df0b77njpeg
include("includes/header2.php");
$profile_id = $user['username'];
$imgSrc = "";
$result_path = "";
$msg = "";
/***********************************************************
0 - Remove The Temp image if it exists
***********************************************************/
if (!isset($_POST['x']) && !isset($_FILES['image']['name']) ){
//Delete users temp image
$temppath = 'assets/images/profile_pics/'.$profile_id.'_temp.jpeg';
if (file_exists ($temppath)){ #unlink($temppath); }
}
if(isset($_FILES['image']['name'])){
/***********************************************************
1 - Upload Original Image To Server
***********************************************************/
//Get Name | Size | Temp Location
$ImageName = $_FILES['image']['name'];
$ImageSize = $_FILES['image']['size'];
$ImageTempName = $_FILES['image']['tmp_name'];
//Get File Ext
$ImageType = #explode('/', $_FILES['image']['type']);
$type = $ImageType[1]; //file type
//Set Upload directory
$uploaddir = $_SERVER['DOCUMENT_ROOT'].'/name/assets/images/profile_pics';
//Set File name
$file_temp_name = $profile_id.'_original.'.md5(time()).'n'.$type; //the temp file name
$fullpath = $uploaddir."/".$file_temp_name; // the temp file path
$file_name = $profile_id.'_temp.jpeg'; //$profile_id.'_temp.'.$type; // for the final resized image
$finalname = $profile_id.md5(time());
$fullpath_2 = "assets/images/profile_pics/".$finalname."n.jpg"; //for the final resized image
//Move the file to correct location
$move = move_uploaded_file($ImageTempName,$fullpath) ;
chmod($fullpath, 0777);
//Check for valid uplaod
if (!$move) {
die ('File didnt upload');
} else {
$imgSrc= "assets/images/profile_pics/".$file_name; // the image to display in crop area
$msg= "Upload Complete!"; //message to page
$src = $file_name; //the file name to post from cropping form to the resize
}
}
if (isset($_POST['Submit'])){
//Insert image into database
$insert_pic_query = mysqli_query($con, "UPDATE users SET profile_pic='$fullpath_2' WHERE username='$userLoggedIn'");
//header("Location: account.php");
}
Thank you for your help. Let me know how I can improve my question as well.
Use $fullpath_2 in your move_uploaded_file(). change upload directiry to $uploaddir = $_SERVER['DOCUMENT_ROOT'] . '/Halpper/';
if (isset($_FILES['image']['name'])) {
/***********************************************************
* 1 - Upload Original Image To Server
***********************************************************/
//Get Name | Size | Temp Location
$ImageName = $_FILES['image']['name'];
$ImageSize = $_FILES['image']['size'];
$ImageTempName = $_FILES['image']['tmp_name'];
//Get File Ext
$ImageType = #explode('/', $_FILES['image']['type']);
$type = $ImageType[1]; //file type
//Set Upload directory
$uploaddir = $_SERVER['DOCUMENT_ROOT'] . '/Halpper/';
//Set File name
$file_temp_name = $profile_id . '_original.' . md5(time()) . 'n' . $type; //the temp file name
$fullpath = $uploaddir . "/" . $file_temp_name; // the temp file path
$file_name = $profile_id . '_temp.jpeg'; //$profile_id.'_temp.'.$type; // for the final resized image
$finalname = $profile_id . md5(time());
$fullpath_2 = "assets/images/profile_pics/" . $finalname . "n.jpg"; //for the final resized image
//Move the file to correct location
if (move_uploaded_file($ImageTempName, $uploaddir . $fullpath_2)) {
chmod($uploaddir . $fullpath_2, 0777);
}
//Check for valid uplaod
if (!$move) {
die ('File didnt upload');
} else {
$imgSrc = "assets/images/profile_pics/" . $file_name; // the image to display in crop area
$msg = "Upload Complete!"; //message to page
$src = $file_name; //the file name to post from cropping form to the resize
}
}
Personally I have used imagecreatefromjpeg
http://php.net/manual/en/function.imagecreatefromjpeg.php
Passed the temp uploaded file directly to this function.
Then this allows me to use imagescale for profile pic sizing.
http://php.net/manual/en/function.imagescale.php
Finally I find file-put-contents is a rather clean way to save the content.
http://php.net/manual/en/function.file-put-contents.php
I'm making an upload application and I have a script that once the images are uploaded they are resized but the original dimensions are stored to be used later on. the index.php should should show the images on the screen.
I've stored the image path instead of a blob on the database and using the 'path' variable to show it on the browser.
The search works but the images are not displaying and I can't find the reason why.
Im new to php/mysql so any help is appreciated on why my images are not showing up.
upload.php
<?php
require_once 'includes/config.inc.php';
require_once 'includes/functions.php';
// Add the heading to output
$output = '<h1>Gallery</h1>';
// Echo the gathered output
echo $output;
// Include the HTML header
include_once 'includes/head.html';
// Check if the form has been submitted...
if (isset($_POST['fileupload'])
&& isset($_POST['title']) && isset($_POST['description'])) {
$title = $_POST['title'];
$description = $_POST['description'];
if (is_uploaded_file($_FILES['userfile']['tmp_name'] )) {
$updir = dirname(__FILE__).'/uploads/';
//$upfilename = $_FILES['userfile']['name'];
$ext=end(explode(".", $_FILES['userfile']['name']));//gets extension
$newname = $updir.$title;
$tmpname = $_FILES['userfile']['tmp_name'];
$newimage = $newname.'.'.$ext;
$path = $newimage;
//if file is an image, upload it
if($_FILES['userfile']['type'] == 'image/jpeg'){
if (move_uploaded_file($tmpname, $newimage)) {
//print if file was uploaded
//echo 'File successfully uploaded';
list($width, $height) = getimagesize($newimage);
//Add values to the DB
$sql = "INSERT INTO Images VALUES(NULL, '$title', '$description', '$width', '$height', '$path')";
$result = mysqli_query($link, $sql);
if(!$result) die ("Database access failed: " . $link->error);
$w = $width;
$h = $height;
resize($newimage, $width, $height);
}
} else {
//print if file failed
echo 'File upload failed';
}
}
//echo debug();
}
// Include the HTML footer
?>
index.php(The sql script is here)
<?php
require_once 'includes/config.inc.php';
require_once 'includes/functions.php';
if (!isset($_GET['page'])) {
$id = 'home'; // display home page
} else {
$id = $_GET['page']; // else requested page
}
switch ($id) {
case 'home' :
include 'uploads.php';
break;
default :
include 'views/404.php';
}
$sql = 'SELECT * FROM Images';
$result = mysqli_query($link, $sql);
if(!$result){
die(mysqli_error($link));
}else{
while($row = mysqli_fetch_array($result)){
echo '<div><a href= "#">
<img src="'.$row['path'].'" width=150 height=150 alt="'.$row['title'].'" /></a></div>';
}
mysqli_free_result($result);
}
/*
Alternative way of showing the right images
$images = glob('uploads/*.jpg');
for($i = 0; $i < count($images); $i++){
list($w,$h) = getimagesize($images[$i]);
$allimages = $images[$i];
echo '<div><a href="'.$allimages.'">
<img src="'.$allimages.'" width="'.$w.'" height="'.$h.'" alt="" /></a>
</div><br/>';
}*/
include_once 'includes/footer.html';
?>
The problem is that you are using dirname(__FILE__) for the start of the path of your image and store that complete path in the database.
According to the manual dirname:
Returns the path of the parent directory.
And __FILE__:
The full path and filename of the file with symlinks resolved.
So you are storing your image using a absolute path on the local file system of the server.
However, that absolute path is not absolute relative to the root of the web-server so the browser will not find the images.
The solution is to use an absolute path when you move the uploaded image, but store a path that is absolute relative to the root of the web-server.
In your case you can probably use the /uploads/ path for that although that would depend on the exact file structure:
...
// no dirname here
$updir = '/uploads/';
//$upfilename = $_FILES['userfile']['name'];
$ext=end(explode(".", $_FILES['userfile']['name']));//gets extension
$newname = $updir.$title;
$tmpname = $_FILES['userfile']['tmp_name'];
$newimage = $newname.'.'.$ext;
$path = $newimage;
//if file is an image, upload it
if($_FILES['userfile']['type'] == 'image/jpeg'){
// only use dirname() here
if (move_uploaded_file($tmpname, dirname(__FILE__) . $newimage)) {
...
You have to add domain of your server to the src attribute of img tag so it'll became an absolute path for users to see the images:
echo '<div><a href= "#">
<img src="'$_SERVER['HTTP_HOST'].$row['path'].'" width=150 height=150 alt="'.$row['title'].'" /></a></div>';
I am trying to display an image that is stored in oracle DB as BLOB data-type. this is my MODEL code
function viewblobData() {
$user = $this->session->userdata('user_logged_in');
$returnLobValue = '';
if (!empty($user)) {
$conn = $this->db->conn_id;
$sql = "SELECT * FROM OP_REG_IMAGE WHERE REG_NO = '$user'";
$stmt = oci_parse($conn, $sql);
oci_execute($stmt)
or die("Unable to execute query<br/>");
while ($row = oci_fetch_assoc($stmt)) {
$returnLobValue = $row['PAT_IMAGE']->load();
header("Content-type: image/jpg");
}
}
return $returnLobValue;
}
and this is for display at view
<?php echo $this->MY_MODEL->viewblobData(); ?>
But its shows "the image http://localhost/..... cannot be displayed because it contains errors"
if I remove the line header("Content-type: image/jpg"); then it shows like below whole page:
�M�t9UYG�G��d���~��5 �V�W��jժ�I�P��l6;��Po�ߖ�]��o�_���v��]o7{���Xr?_� ��bp��F3�s>ߙ�K)��f_�w��9����Z#���i�:�V�Y�h�=�����o���{��px=����o��fk���:>����~u�=��w��~9������y�]^����ٹ_���
Can anyone help?
You can use the image libraries:- e.g
$img = imagecreatefromstring($row['PAT_IMAGE']);
if ($img !== false) {
$image_new_name = 'sig_' . time() . '.png';
$image_path = 'upload/' . $image_new_name;
$image_name = $ROOT_DIR . '/' . $image_path;
if (!file_exists($image_name)) {
imagepng($img, $image_name);
imagedestroy($img);
} else {
$image_new_name = 'new_' . $image_new_name;
$image_path = 'upload/new_' . $image_new_name;
$image_name = $ROOT_DIR . '/' . $image_path;
imagepng($img, $image_name);
imagedestroy($img);
}
This code will generate image from your data to the provided dir. then use that image to display. enjoy. :)