I am trying to prevent from uploading image before form submit using summernote editor.
The code I was using (jquery/ajax) worked well for uploading image, but it was uploading image instantly when I add it to editor.
This was not desired behavior for me, 'couse if user add image to editor and then decide to close tab/close browser or go to another address, image will be stored on server - so I would like to upload image only when submit button is clicked (until then, it should be there only as preview).
I use following code which is parsing base64 coded image from editor, decoding and uploading to server.
it works fine when adding new article or updating article without adding new image into it.
Example : if article has 2 old images allready, and I add 1 more image then its trying to reupload that old images again, but old images are decoded so it doesn't upload them and inserting an undefined link into the editor.
I tried to validate with the server using :
if(file_exists($filename)){
echo 'Already exist';
}
But had no luck to make it work.
Here is my code :
if(strpos($submitted_content, '<img') !== false && strpos($submitted_content, ';base64') !== false) {
$doc = new DOMDocument();
$doc->loadHTML($submitted_content);
$tags = $doc->getElementsByTagName('img');
foreach($tags as $tag) {
// Get base64 encoded string
$srcStr = $tag->getAttribute('src');
$base64EncData = substr($srcStr, ($pos = strpos($srcStr, 'base64,')) !== false ? $pos + 7 : 0);
$base64EncData = substr($base64EncData, 0, -1);
// Get an image file
$img = base64_decode($base64EncData);
// Get file type
$dataInfo = explode(";", $srcStr)[0];
$fileExt = str_replace('data:image/', '', $dataInfo);
// Create a new filename for the image
$newImageName = str_replace(".", "", uniqid("img_", true));
$filename = $newImageName . '.' . $fileExt;
$file = '../uploads/large/' . $filename;
// Save the image to disk
$success = file_put_contents($file, $img);
$imgUrl = 'http://localhost/haber/uploads/large/' . $filename;
// Update the forum thread text with an img tag for the new image
$newImgTag = '<img src="' . $imgUrl . '" />';
$tag->setAttribute('src', $imgUrl);
$tag->setAttribute('data-original-filename', $tag->getAttribute('data-filename'));
$tag->removeAttribute('data-filename');
$submitted_text = $doc->saveHTML(); //This is the result of the editor to add database
}
Any help will be appricated! Thanks.
Solution :
I just needed to add if statement under foreach and take $submitted_text = $doc->saveHTML(); out of foreach, it works like a charm now.
if(preg_match('/data:image/', $srcStr)){}
if you want to add images to database, you can collect $filename to array $arr = array(); and implode or foreach in to database.
Can be used for all editors.
Related
This question already has answers here:
How to prevent Browser cache for php site
(7 answers)
Closed 3 years ago.
I am trying to give my wordpress site a randomly pulled "About the Author" image in my footer.
My first solution was to create an array, name them each aboutAuthor[x].jpg and generate a random number for x.
That works just fine, but I was looking for a solution that didn't involve me having to rename files and adding a line of code every time I decide to add a new image to the folder.
I found a solution on this site: http://photomatt.net/scripts/randomimage
He provides some php code
<?php
$folder = '';
$exts = 'jpg jpeg png gif';
$files = array();
$i = -1;
if ('' == $folder)
$folder = './';
$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
foreach ($exts as $ext) {
if (preg_match('/\.' . $ext . '$/i', $file, $test)) {
$files[] = $file;
++$i;
}
}
}
closedir($handle);
mt_srand((double) microtime() * 1000000);
$rand = mt_rand(0, $i);
header('Location: ' . $folder . $files[$rand]);
?>
Then I simply place that php file in the directory in question and call it in place of an image
<img src="/imgDirectory/rotate.php">
The only problem with this is that my browser is caching the resulting random image.
With a normal reload or clicking a link to a new page, I get the same image.
With a hard reload, I get a new one, like I want.
Oddly, in the sample on his website, it works as expected with a normal reload.
So what is the best way to achieve what I'm looking for?
Here is the solution
1) Create new div:
<div class="randomAuthor" id="randomAuthor"> </div>
2) Move image source
<img src="/imgDirectory/rotate.php">
to a separate PHP or html file, example author.php:
3) Load author.php into div "randomAuthor" using
ajax code:
$(document).ready(function(){
$('#randomAuthor').load("author.php");
});
This way on each refresh the $(document).ready(function(){..... will get triggerd which in turn will trigger rotate.php file thus you will get new image each time you open your page or refresh it.
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.
So I am creating a new folder everytime if folder not exists using mdkir.
$dir_name = '../../assets/contestant_double/'.$event_id.'eventPortfolio/';
if(!is_dir($dir_name)){
mkdir('../../assets/contestant_double/'.$event_id.'eventPortolfio/', 0777, true);
}
Now I am trying to update my uploaded image on that folder. And its working fine when i look on that designated directory
$static_name = $event_id."d".$getThed1d2."_contestant_";
$extension = pathinfo($name, PATHINFO_EXTENSION);
$theRealName = $static_name.$lastDigit.".".$extension;
echo $theRealName;
But when i try to get the image why is it still showing up the old image instead the new one?
<img class="img_here_edit" src="../assets/contestant_double/'.$event_id.'eventPortfolio/'.$soc_sql['images'].'" width="100%" >
I doubt but I'm not sure that its on my new created directory mdkir which has 0777 because those of my code are working fine in my other regular folder? How do i solve this
use unlink(''); function to old image it will solve your problem
Why not delete the old image and create and upload a new image with the same name?.
Try sending a random id at the end of image url to get the latest image like this :
<img class="img_here_edit" src="../assets/contestant_double/'.$event_id.'eventPortfolio/'.$soc_sql['images'].'?'.time().'" width="100%" >
what you see is the picture on browser cache, so you have to clear cache of browser. however, you wont do that every time you replace a picture either your users, it is too tedious and unpractical. I had same sutation and what i did was the follown. create filename + time().jpg like this.
So by the time i was going to replace old picture, i loaded from folder, delete it an then place new one. look...
function uploadphoto( $id, $ref ) {
$find = $ref.'_';
$data = $_POST[ 'image' ];
list( $type, $data ) = explode( ';', $data );
list( , $data ) = explode( ',', $data );
$data = base64_decode( $data );
$imageName = $ref.'_'.time().'.jpg'; // new picture name
foreach(glob('uploads/'.$find.'*.*') as $filename){
$localizacion = $_SERVER['DOCUMENT_ROOT'].'/'. $filename ;
chmod('./uploads', 0777);
unlink($localizacion);
}
file_put_contents( 'uploads/' . $imageName, $data );
}
I'm trying to load images from a http url but they won't display in my generated pdf.
$this->layout = '//layouts/pdftemplate';
$pdf = Yii::app()->toPDF->mpdf();
$pdf->shrink_tables_to_fit = 1;
$pdf->defaultfooterline = false;
$stylesheet = file_get_contents(Yii::app()->basePath.'/../webroot/admin/themes/admin/css/formbuilder-print.css');
$pdf->WriteHTML($stylesheet, 1);
$pdf->WriteHTML($_POST['html_string']);
$pdf->Output(sys_get_temp_dir()."/test.pdf", 'F');
I'm passing the html to the php function in an ajax call. The images are on Amazon CloudFront.
Update
Thanks to Asped and Latheesan Kanes I got the issue resolved. I also used PHP's DOMDocument class to replace the image urls with the local copy of the image. This is for future reference if anyone also runs into a similar issue
$doc = new DOMDocument();
#$doc->loadHTML($_POST['html_string']);
$imgs = $doc->getElementsByTagname('img');
foreach ($imgs as $img){
$src = $img->getAttribute('src');
$name = explode('?', basename($src));
$name = $name[0];
$tmp = sys_get_temp_dir().'/'.$name;
copy($src, $tmp);
$img->setAttribute('src', $tmp);
}
$html = $doc->saveHTML(); // you can write this to the pdf. $pdf->WriteHTML($html);
I had a similar issue once displaying an SVG file in the pdf.. it would not work. Then I converted it to a PNG (on the fly), stored locally in a temp folder, and passed the temporary file to mDPF, which helped.
UPDATE - Actually now I remember I didn't even had to convert it, I just had to store it locally in a temp folder..
having a big trouble trying to make this blob saved to a file and load it as an image.
Using SQLite Manager (Firefox Add-on) I was able to "Save As" a file with the content of my image BLOB. The result is a strange (for me) code.
Since I canĀ“t post the "source of the file", I'm attaching one png with the example.
In my Mac, the saved file has no extention but I can view the image it produces as thumbnail.
So I'm trying to achieve the same result saving one file, but all I get is a 16 bytes document I can't read...
$pic = fopen('pics/thumbnails/pic_'.$id.'', 'w');
fwrite($pic, base64_encode($theFile));
fclose($pic);
* EDIT *
$theFile = shell_exec("sqlite3 AddressBookImages.sqlitedb 'select data from ABThumbnailImage where record_id = ".$id."'");
if($theFile != '') {
file_put_contents('pics/thumbnails/pic_'.$id.'.jpg', $theFile);
}
Try to use (b for binary)
$pic = fopen('pics/thumbnails/pic_'.$id.'', 'wb');
I find a solution to this, but its very slow, I'm posting a new question to ask help for improve this.
$sql2 = shell_exec("sqlite3 ".$endereco_iphone."".$db_pics." 'select hex(data) from ABThumbnailImage where record_id = ".$id."'");
//
if($sql2 !='' && $sql2 != 'NULL') {
$img = '';
foreach(explode("\n",trim(chunk_split($sql2,2))) as $h) {
$img .= chr(hexdec($h));
}
if(file_put_contents('pics/thumbnails/pic_'.$id.'.jpg', $img)) {
$cnt .= "<img class='pics' src='pics/thumbnails/pic_".$id.".jpg' width='30px' height='30px'></img>";
}
} else {
$cnt .= "<div class='pics'></div>";
}