Hello my PHP script i have set up uploads files via a html form.
I'm hoping to show a download link / open file link after the upload but the problem is a section of the PHP script I'm using renames the file on upload
//Create full filename including path
if ($random_name_enable = true) {
// Generate random filename
$tmp = str_replace(array('.', ' '), array('', ''), microtime());
if (!$tmp || $tmp == '') {
$out['error'][] = "File must have a name";
}
$newname = $tmp . '.' . $ext;
} else {
$newname = $name . '.' . $ext;
}
enter code here
This results in me not knowing how show a download link with the renamed uploaded file via the php solution below
The upload webpage / site is located at https://beta.filez.ml
as you can see if you try to upload a basic image is does not show the renamed download link, I need to figure out a way to get the PHP script to show a link after the rename of the upload shown below.
The Full PHP file is here for anyone interested in picking it apart
https://gist.github.com/burnsyboo/b9a9512807fc031dc9a7
Why not use Ajax? when upload is done, echo new file name that you generated, ajax takes that name and then append anchor with href with file name that you got from php and add download attribute to anchor so it downloads file when pressed
http://www.w3schools.com/tags/att_a_download.asp
Solution was to just above the $newname variable add global $newname; then at the top of the page i did $newname "";
Then where the success message was displayed i did this
$message = "<style>.php-success { color: darkgreen; font-weight: 400; font-size: 20px; }</style><p class='php-success'>File successfully Uploaded<br><br>Click here to open</p>";
Related
I'm using summernote as the text editor in a backend. The text and images stored must then be displayed in the pages of the frontend.
The editor and the upload images works, but the problem is to recover the images in the frontend because of the path.
I need to use the absolute path in the img-upload.php file but it doesn't seem to accept it.
img-upload.php
if(empty($_FILES['file']))
{
exit();
}
$errorImgFile = "./img/img_upload_error.jpg";
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
$destinationFilePath = '../../images/img-uploads/'.$newfilename ;
if(!move_uploaded_file($_FILES['file']['tmp_name'], $destinationFilePath)){
echo $errorImgFile;
}
else{
echo $destinationFilePath;
}
with the relative path works:
$destinationFilePath = '../../images/img-uploads/'.$newfilename ;
but in this way not:
$path = 'http://localhost/sites/my-site/';
$destinationFilePath = $path.'images/img-uploads/'.$newfilename ;
I don't see any error.
Thanks
You have probably figured it out by now...
It seems Summernote does not render images from absolute paths, but the closest you can get is to specify the file from the root path, like:
$path = '/sites/my-site/';
$destinationFilePath = $path.'images/img-uploads/'.$newfilename ;
Results in something like: '/sites/my-site/images/img-uploads/filename.jpg'
If you save this to your database, you can render your images anywhere on your site using this rooth path address for the files.
I suggest you to use Ckfinder or Fileman with Ckeditor. I made a repository for that. Go check it out.
https://github.com/senocak/Laravel-CKEDITOR-CKFINDER-usage
I am working with wordpress -> contact form 7 and saving the data with contact form 7 to database extension plugin.
The plugin has filters to modify data before saving into database. ([Like This Page])1
now i wanted to save the file into different folder on the server and output link to that file into the admin panel. i used the filter like this.
function cfdbFilterSaveFile($formData) {
// CHANGE THIS: CF7 form name you want to manipulate
$formName = 'DemoReport';
// CHANGE THIS: upload field name on your form
$fieldName = 'Report';
// CHANGE THIS: directory where the file will be saved permanently
$uploaddir = '/home2/username/public_html/example.com/report/wp-content/uploads/reports/';
$urlDir = 'http://example.com/report/wp-content/uploads/reports/';
if ($formData && $formName == $formData->title && isset($formData->uploaded_files[$fieldName])) {
// make a copy of data from cf7
$formCopy = clone $formData;
// breakdown parts of uploaded file, to get basename
$path = pathinfo($formCopy->uploaded_files[$fieldName]);
// directory of the new file
$newfile = $uploaddir . $path['basename'];
// check if a file with the same name exists in the directory
if (file_exists($newfile)) {
$dupname = true;
$i = 2;
while ($dupname) {
$newpath = pathinfo($newfile);
$newfile = $uploaddir . $newpath['filename'] . '-' . $i . '.' . $newpath['extension'];
if (file_exists($newfile)) {
$i++;
} else {
$dupname = false;
}
}
}
// make a copy of file to new directory
copy($formCopy->uploaded_files[$fieldName], $newfile);
// save the path to the copied file to the cfdb database
$formCopy->posted_data[$fieldName] = $newfile;
$path = pathinfo($newfile);
$filelink = '<a href=' . $urlDir . $path['basename'] . '>' . $path['basename'] . '</a>';
$formCopy->posted_data[$fieldName . '-url'] = $filelink;
// delete the original file from $formCopy
unset($formCopy->uploaded_files[$fieldName]);
return $formCopy;
}
return $formData; }
add_filter('cfdb_form_data', 'cfdbFilterSaveFile');
Now with this code the file is saved into the folder on the server as expected but i am not able to output the clickable link to the saved file in the admin panel tables. In place of clickable links the full url is there. As in the screenshot.
ScreenShot
The output is coming as full URL (as marked 1 in screenshot), while i want the url to output as a link to the file (something like 2 in screenshot). I tried to use echo() and sprintf but got php syntex error.
Thanks for the suggestions. I have found alternate way to output links. What I have to do is output the form submission data on a webpage and convert links clickable by javascript as suggested by #Ovidash ... That is a acceptable workaround for my issue. Thanks for all the suggestions.
I have a piece of code to upload a picture and save it in a folder and the path in a databaseand show it on the webpage. Funny enough, upon uploading the picture for the first time, the image will show on the webpage and with change when I upload a new picture. But when I close the page, reopen it another day and decide to change the picture, the one of the webpage won't change even if i refresh the page but the one in the folder will change.
Here's my code
<?php
$sql2 = "SELECT Picture_HD FROM detailss WHERE Idn_nom = '$Indnum'";
require('connect.php');
$addr = "";
$addr = mysqli_query($conn, $sql2);
if ($addr) {
$locat = $addr->fetch_row();
$locat = (string)$locat[0];
} else {
$locat = "Pictures/default1.png";
}
mysqli_close($conn);
echo "<div id = 'Img'>";
echo "<img src = '" . $locat . "' alt = 'Passport picture/Headshot' style = 'width:80px; height:80px;'/>";
echo "</div>";
?>
Your browser is caching the image.
If you want to prevent the browser to cache the image just add a random parameter at the end of the url.
echo "<img src = '" . $locat . "?t=" . time() . "' alt = 'Passport picture/Headshot' style = 'width:80px; height:80px;'/>";
If your image is changing in your folder but you are seeing the old one on the webpage it's likely a caching issue, clear your browser cache (ctrl+f5 plus this is kinda broken so doesn't always work - so best to go into browser settings to do it, or open a private window after ctrl+f5) and if not the clear server level cache.
The best way to do this is to delete the existing image right before uploading the new one with the same file name
// define variables used for file name from session variable username the directory and extension by exploding the file name from the post method from a form with a metadata type
//set new file name to username from session variable
$filename = $_SESSION['username']
// set directory of files
$dir = "img/";
// set extension variable to file extension after posted from form
$ext=strtolower(end(explode('.',$_FILES['importimg']['name'])));
// new file upload name with existing extension
$upload_file = $dir . $filename . "." . $ext;
// delete file
// find all files with the same name any extension using variable defined above etc .txt, .php, .gif, .jpg, etc. then delete it
foreach (glob("img/$filename.*") as $deletefile) {
// unlink is used to delete the file and delete the cache of the file
unlink($deletefile);
}
// upload image
// upload file with type posted from metadata in form and upload it as your new file name using upload_file variable
if (move_uploaded_file($_FILES['importimg']['tmp_name'], $upload_file)) {
// successful upload of file add code for msg or sql query etc name to users table and redirect to profile page
echo "Successfully uploaded your file.";
} else {
// upload error show message
echo "There was an error uploading your file.";
}
Enjoy
I am trying to display the image that i have uploaded and moved to the desired location. Here is the code below.
if(isset($_FILES['image']))
// image upload from upload.html
{
session_start();
$_SESSION['str'];
$_SESSION['img'];
$image = basename($_FILES["image"]["name"]);
move_uploaded_file($_FILES['image']['tmp_name'], $_SESSION['str'].'_5'.$_SESSION['img']);
//I am trying to display the uploaded pic
echo '<img src= "$image"/>';
}
The image is stored at the location $_SESSION['str']. How can i display this uploaded image.
You're using the wrong path to show the image. You're using the orginal name of the image $_FILES["image"]["name"] that was uploaded and then you use the move_uploaded_file function to move and save the file as $_SESSION['str'].'_5'.$_SESSION['img'] so that doesn't match (can't see how your session variables are created).
Also, is the location where you save the uploaded file to accessable by the client side? Move the file in the public area of your web application.
Update
I now understand from your comment that you want to save the file in a private location and then show that file in a <img> element in some HTML template.
I changed the example code to embed the uploaded image into the HTML with base64.
You can use this function for creating the embed code. I took it from the answer from this question How to embed images...
function dataUri($file, $mime)
{
$contents = file_get_contents($file);
$base64 = base64_encode($contents);
return 'data:' . $mime . ';base64,' . $base64;
}
So then you can use it like:
session_start();
// absolute path including the path to the public folder
$image_dest_path = './public/img/' . $_SESSION['str'] . '_5' . $_SESSION['img'];
// move file to server location
move_uploaded_file($_FILES['image']['tmp_name'], $image_dest_path);
// imbed the image into the HTML.
echo '<img src= "' . dataUri($image_dest_path, 'image/jpg') . '"/>';
First of you say the location is stored in $_SESSION['str'] but you try to place an image with the value of basename($_FILES["image"][""name]).
Second; you should be using session_start() at the top of your page.
Third; in order to use a variable in a string, you need to use double quotes (") in stead of single quotes ('). Like so:
echo "<img src='$_SESSION['str']">;
But I'd use this:
echo '<img src="'. $_SESSION['str'] .'" >';
Also, are you sure you're not getting any errors? If you don't see any try placing this at the top of your file:
error_reporting(E_ALL);
ini_set('display_errors', 1);
iam assuming that $_SESSION['str'] session variable is the path till the folder where the image is stored
Use the below code, give the complete url of the image:
echo "<img src = '".$_SESSION['str'].DIRECTORY_SEPARATOR.$image."'"." />";
how to call the node js method in angular js?
I am not real good at reading the code for uploading images via php/ajax so i am hoping a php guru can help me out. I am trying to take the image file name and if it has spaces in it then replace those spaces with an underscore "_"
The php code for uploading is this:
$file_name = ( isset($_REQUEST['ax-file-name']) && !empty($_REQUEST['ax-file-name']) )?$_REQUEST['ax-file-name']:'';
$currByte = isset($_REQUEST['ax-start-byte'])?$_REQUEST['ax-start-byte']:0;
if($is_ajax)//Ajax Upload, FormData Upload and FF3.6 php:/input upload
{
//we get the path only for the first chunk
$full_path = ($currByte==0) ? checkFileExits($file_name, $upload_path):$upload_path.$file_name;
//Just optional, avoid to write on exisiting file, but in theory filename should be unique from the checkFileExits function
$flag = ($currByte==0) ? 0:FILE_APPEND;
//formData post files just normal upload in $_FILES, older ajax upload post it in input
$post_bytes = isset($_FILES['Filedata'])? file_get_contents($_FILES['Filedata']['tmp_name']):file_get_contents('php://input');
//some rare times (on very very fast connection), file_put_contents will be unable to write on the file, so we try until it writes
while(#file_put_contents($full_path, $post_bytes, $flag) === false)
{
usleep(50);
}
//delete the temporany chunk
if(isset($_FILES['Filedata']))
{
#unlink($_FILES['Filedata']['tmp_name']);
}
//if it is not the last chunk just return success chunk upload
if($isLast!='true')
{
echo json_encode(array('name'=>basename($full_path), 'size'=>$full_size, 'status'=>1, 'info'=>'Chunk uploaded'));
}
}
else //Normal html and flash upload
{
$isLast = 'true';//we cannot upload by chunks here so assume it is the last single chunk
$full_path = checkFileExits($file_name, $upload_path);
$result = move_uploaded_file(str_replace(" ", "_",$_FILES['Filedata']['tmp_name']), $full_path);//make the upload
if(!$result) //if any error return the error
{
echo json_encode( array('name'=>basename($full_path), 'size'=>$full_size, 'status'=>-1, 'info'=>'File move error') );
return false;
}
}
I've already tried the following (with str_replace(" ", "_", $nameoffile):
$post_bytes = isset($_FILES['Filedata'])? file_get_contents(str_replace(" ", "_",$_FILES['Filedata']['tmp_name'])):file_get_contents('php://input');
That seems to do nothing to rename it. So where am i missing it at?
The problem in your code is , you are trying to rename the temporary name of image file not the actual name
move_uploaded_file(str_replace(" ", "_",$_FILES['Filedata']['tmp_name']), $full_path);//make the upload
So you have to remove the str_replace from temporary name and append this to actual name like this.
move_uploaded_file($_FILES['Filedata']['tmp_name'], str_replace(" ", "_",$full_path));//make the upload
Hope it clarifies your doubt.