create clickable link in php - php

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.

Related

Image won't change when replaced

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

PHP file show download link after renamed upload

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>";

order number as file name wordpress/woocommerce

I'm using wordpress with woocommerce and I've installed a plugin for file uploads, which put into checkout page, when the order was placed. I need this uploader to change the name of uploaded file to the order number current placed. see the picture...
Order Number as file name by upload
This put in woocommerce order number in the front-end site
<?php echo $order->get_order_number(); ?>
In functions.php I have this code as test to handle with file name by uploading:
add_filter('wfu_before_file_upload', 'wfu_before_file_upload_handler', 10, 2);
function wfu_before_file_upload_handler($file_path, $file_unique_id) {
// separate file name from file path
$only_filename = basename($file_path);
$only_filepath = substr($file_path, 0, - strlen($only_filename));
// separate file extension from file name
$dot_pos = strrpos($only_filename, ".");
if ( $dot_pos ) {
$ext_part = substr($only_filename, $dot_pos);
$name_part = substr($only_filename, 0, $dot_pos);
}
// add timestamp to the end of name_part
$current_datetime = gmdate("U");
$only_filename = $name_part . "-" . gmdate("YmdHis", $current_datetime) . $ext_part;
// return the full file path
$file_path = $only_filepath . $only_filename;
return $file_path;
}
This is actually from the plugin developer as example, how to handle file name of uploaded file with wordpress filter.
I would like to make $current_order_number instead of $current_datetime but how I can then get the current order number from database? I've tried following:
$order = get_order_number();
$current_order_number = $order;
$new_filename = $current_order_number . $ext_part;
// return the full file path
$file_path = $only_filepath . $new_filename;
return $file_path;
But it's not working. I still get error message by uploading the file. Any ideas what I'm doing wrong?
Thank you.
Tomas

PHP dynamic zip file creation crashes with non-image filetypes. (wp)

I have a function that takes uploaded files (WORDPRESS) and adds them to a (newly created) zip file.
every new file is added to the zip (if is not yet created - the first file will create one ) and also to a comment with the list of the files.
function Ob99_generate_zip_file($meta) {
// we always need post_id , right ?
if( isset($_GET['post_id']) ) {
$post_id = $_GET['post_id'];
} elseif( isset($_POST['post_id']) ) {
$post_id = $_POST['post_id'];
}
//setting some more variables.
$file = wp_upload_dir();// take array
$file2 = wp_upload_dir();//debug
$zipname = $file['path'].'file.zip'; // set zip file name
$file = trailingslashit($file['basedir']).$meta['file'];// construct real path
// Without this next condition the function dies. WHY ??
list($orig_w, $orig_h, $orig_type) = #getimagesize($file); // not help to comment
if (!$orig_type == IMAGETYPE_GIF || !$orig_type == IMAGETYPE_PNG|| !$orig_type == IMAGETYPE_JPEG) {
//why other filetypes not working ??
return ;
}
$zip = new ZipArchive; // initiatte class
$zip->open($zipname , ZipArchive::CREATE); // open buffer
$new_filename = substr($file,strrpos($file,'/') + 1); //we do not need nested folders
$zip->addFile($file,$sitename.'/'.$new_filename); // we add the file to the zip
if (file_exists($zipname)){
$comment = $zip->getArchiveComment(); // if the file already exist read the comment
}
else { // if not - let´s give it a cool retro header
$comment_head = '*********************************'. PHP_EOL ;
$comment_head .= '****** <<< FILE CONTENT >>> *****'. PHP_EOL ;
$comment_head .= '*********************************'. PHP_EOL ;
}
$comment = $comment_head . $comment ;// add header before comment
$comment = $comment . PHP_EOL . PHP_EOL . $meta['file'] ; // add new file name
$zip->setArchiveComment($comment); // and comment
$zip->addFromString('filelist.txt', $comment); // create txt file with the same list
$zip->close()or die('can not create zip file'.$file.print_r($meta).'---- DEBUG SEPERATOR ---- '.print_r($file2)); // FINISHED or DIE with debug
}
My problem : if I try to upload any file other than an image - the function will DIE .
I have added a condition for checking imagetype - but I would like to know why it is crashing and how to make it work without said condition ...
Does the zip function have any problems with PDF , doc or anyother ? is that a wordpress problem ?
The problem section seems to be where you're asking PDFs, etc. their image size. Why don't you try:
$image_size = getimagesize($file);
if($image_size===false)
{
// This is not an image
// Do what you want to PDFs, etc.
}
else
{
// This is an image
// Find out image type, dimensions, etc.
}

For loop over named folder to read each .txt filename and contents

The script below takes a named file that resides in the "myplugin" folder (the folder that the script itself resides in) and runs file_get_contents() on it to load the contents into memory, then does some preprocessing on the contents before finally inserting it as a post into the WordPress database via the wp_insert_post method.
$my_post3 = array();
$my_post3['post_title'] = 'Privacy Policy';
if(file_exists(ABSPATH.'/wp-content/plugins/myplugin/pages/privacy_policy.txt'))
{
$my_privacy_policy = file_get_contents(ABSPATH.'/wp-content/plugins/myplugin/pages/privacy_policy.txt');
}
else
{
$my_privacy_policy = "";
}
$my_post3['post_content'] = addslashes($my_post3_replace);
$my_post3['post_type'] = 'page';
$my_post3['post_status'] = 'publish';
wp_insert_post($my_post3);
This method works pretty good. However, this method forces me to write a different routine for every file I want to use as the basis of a new page.
What I would like to do instead, is create a folder called "pages" and place my .txt files in that, then run a for loop on the contents of the folder, creating a new page for each file in the folder. I'd like to use the file name (minus the .txt extension) as the name of the page.
For example, the pages folder may have these files:
About Us.txt
Contact Us.txt
And the routine would result in the creation of two new pages in WordPress site, one called "About Us" containing the content found in that file. The other page would of course be "Contact Us" with the contents of that file.
In this way, I can just drop an unlimited number of named and prepopulated .txt files into that folder and when I activate my plugin, it creates those pages.
I just need some help with the for loop and how to reference the folder and files.
I will also have a folder called "posts", which will do the same for posts that this routine does for pages.
Thanks in advance for your help and suggestions.
Update based on #clientbucket answer:
DEFINE ('PAGES', './pages/');
$directory_pages = new DirectoryIterator(PAGES);
foreach ($directory_pages as $files) {
if ($files_pages->isFile()) {
$file_name_page = $files_pages->getFilename();
$my_page_content = file_get_contents(PAGES. $file_name_page);
$my_page['post_content'] = addslashes($my_page_content);
$my_page['post_title'] = $file_name_page;
$my_page['post_type'] = 'page';
$my_page['post_status'] = 'publish';
wp_insert_post($my_page);
}
}
DEFINE ('POSTS', './posts/');
$directory_posts = new DirectoryIterator(POSTS);
foreach ($directory_posts as $files_posts) {
if ($files_posts->isFile()) {
$file_name_post = $files_posts->getFilename();
$my_post_content = file_get_contents(POSTS. $file_name_post);
$my_post['post_content'] = addslashes($my_post_content);
$my_post['post_title'] = $file_name_post;
$my_post['post_type'] = 'post';
$my_post['post_status'] = 'publish';
$post_id = wp_insert_post($my_post);
stick_post($post_id);
}
}
Fatal error: Uncaught exception 'UnexpectedValueException' with message 'DirectoryIterator::__construct(./pages/) [directoryiterator.--construct]: failed to open dir: No such file or directory' in C:\xampplite\htdocs\mytestsite\wp-content\plugins\myplugindirectory\myplugin.php:339
Line 339 is here > $directory_pages = new DirectoryIterator(PAGES);
Here is another way you could try.
DEFINE ('PAGES', './pages/'); //Define the directory path
$directory = new DirectoryIterator(PAGES); //Get all the contents in the directory
foreach ($directory as $files) { //Check that the contents of the directory are each files and then do what you want with them after you have the name of the file.
if ($files->isFile()) {
$file_name = $files->getFilename();
$my_page = file_get_contents(PAGES. $file_name); //Collect the content of the file.
} else {
//Insert nothing into the $my_privacy_policy variable.
}
echo $my_page; // Do what you want with the contents of the file.
}
From the PHP manual here:
http://php.net/manual/en/function.glob.php
They provide this solution for finding all text files in a directory:
<?php
foreach (glob("*.txt") as $filename) {
echo $filename . "\n";
}
?>
Given this example, your actual request is to be able to create a file based on the name in another directory. I'll leave the hard work to you - but this is a simple implementation:
<?php
$source_dir = "/your/directory/with/textfiles";
$target_dir = "/directory/to/create/files/in";
foreach (glob($source_dir . DIRECTORY_SEPARATOR . "*.txt") as $filename) {
$filepart = explode('.',$filename);
file_put_contents($target_dir . DIRECTORY_SEPARATOR . $filepart[0] . ".php");
}
?>

Categories