How to send image from main page to another? - javascript

I have been searching for this answer for days and cannot come across an answer. Maybe because i do not understand them and can not apply them to what i am trying to do.
i am using php to save images on the server when the user presses submit and when that happens, i would like the image to appear on the next page in the image src. As you can see that the name of my next page is random but similar to my image name aside from the extensions. So i was wondering if that would play a part in helping me do something? as at the end of my php i go straight to the random stringed page that was created.
function findexts ($filename) {
$filename = $_FILES["file"]["name"];
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
if(isset($_POST['submit'])){
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 3000000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
//echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
$ext = findexts ($_FILES['file']['name']) ;
$newName = generateRandomString();
$fileName=$newName.".".$ext;
while (is_file("upload/" . $fileName)){
$newName = generateRandomString();
$fileName=$newName.".".$ext;
}
$target = "upload/";
move_uploaded_file($_FILES["file"]["tmp_name"],
$target . $fileName);
$newfile = fopen("img/" . $newName.".html", "w") or die("Unable to open file!");
$newImgWeb = $newName.".html";
copy("img/template.html","img/" . $newImgWeb);
fclose($newfile);
header("Location: img/$newImgWeb");
}
} else {
//echo "Invalid File"
}
} else {
}
this is my php and i don't know how i would go about doing it?
my html and php are seperate too, but are linked under the form action="upload_file.php"
<img src="../upload/<?php echo $fileName ?>">
but i'm just getting a bunch of errors, i have no clue on what i should do next. I'm just a beginner and learning a lot through doing this.
Also, i tried doing this in javascript where i would take the url of the current webpage, remove the begining url and leave with the end. So it would be like "adSEvF3A.html" then i removed the ".html" part and from there i couldn't identify which extensions to look for .png .jpg etc. so i couldn't do document.getElementById('image').src=newImg;
Thanks in advance!

I had realised that i needed to put
session_start();
at the begining of the php file that i want to obtain the variable from. When i was working with session_start(); i had done it all wrong, and thought that $_SESSION had to always be declared right below session_start(); i know many of you will think it's stupid to think that. But hey, at least i figured it out.
test1.php
session_start();
$var = "hello.jpg";
$_SESSION['image'] = $var;
the variable that i wanted to declare needed to be above the $_SESSION so that it can be stored inside it.
index.html
<?php
include ('test1.php');
$image = $_SESSION['image'];
?>
<img src="upload/<?php echo $image ?>">
and then it worked.
Thanks CMKanode for helping me!

Related

Image Upload Not Working (Froala Editor)

I have read the Froala Help Docs over 10 times now. I still can't get it to work :(
When I click the upload icon in my editor and select an image to upload, nothing happens. The dialog box that asks you to choose an image pops up, and after selecting the image, it dismisses but nothing happens on the page afterwards.
It's definitely something wrong with my code. However, I can't figure out what it is.
My view page:
<textarea id="edit" name="message"> </textarea>
My js:
$(function() {
$('#edit').editable({
height: 400,
imageUploadURL: '/assets/upload_image.php',
imageUploadParams: {id: "edit"},
imageUploadParams: {id: "edit"},
placeholder: "Write something...",
inlineMode: false
})
});
My upload_image.php file:
<?php
// Allowed extentions.
$allowedExts = array("gif", "jpeg", "jpg", "png");
// Get filename.
$temp = explode(".", $_FILES["file"]["name"]);
// Get extension.
$extension = end($temp);
// An image check is being done in the editor but it is best to
// check that again on the server side.
// Do not use $_FILES["file"]["type"] as it can be easily forged.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES["file"]["tmp_name"]);
if ((($mime == "image/gif")
|| ($mime == "image/jpeg")
|| ($mime == "image/pjpeg")
|| ($mime == "image/x-png")
|| ($mime == "image/png"))
&& in_array($extension, $allowedExts)) {
// Generate new random name.
$name = sha1(microtime()) . "." . $extension;
// Save file in the uploads folder.
move_uploaded_file($_FILES["file"]["tmp_name"], getcwd() . "http://localhost/assets/uploads/" . $name);
// Generate response.
$response = new StdClass;
$response->link = "http://localhost/assets/uploads/" . $name;
echo stripslashes(json_encode($response));
}
What I have tried to fix this issue:
In upload_image.php, I have replaced the upload folder path (original: http://localhost/assets/uploads/ to just uploads and created an uploads folder in that directory. Still no luck.
I have tried placing all the files together in the same folder but no luck.
Any help is highly appreciated.
I have gone through the same issue and I am sharing working code for you.
index.php
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/froala_editor.css">
<style>
body {
text-align: center;
}
div#editor {
width: 81%;
margin: auto;
text-align: left;
}
</style>
</head>
<body>
<div id="editor">
<form method="post">
<textarea id='edit' name='edit' style="margin-top: 30px;" placeholder="Type some text">
<h1>Textarea</h1>
<p>The editor can also be initialized on a textarea.</p>
</textarea>
<input name="submit" type="submit">
</form>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="js/froala_editor.min.js"></script>
<script type="text/javascript" src="js/plugins/image.min.js"></script>
<script>
$(function() {
$('#edit').froalaEditor({
height: 300
})
});
</script>
</body>
</html>
upload_image.php
<?php
// Allowed extentions.
$allowedExts = array("gif", "jpeg", "jpg", "png");
// Get filename.
$temp = explode(".", $_FILES["file"]["name"]);
// Get extension.
$extension = end($temp);
// An image check is being done in the editor but it is best to
// check that again on the server side.
// Do not use $_FILES["file"]["type"] as it can be easily forged.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES["file"]["tmp_name"]);
/* if you want to check extension of a file, then please remove the below if condition */
/*if ((($mime == "image/gif")
|| ($mime == "image/jpeg")
|| ($mime == "image/pjpeg")
|| ($mime == "image/x-png")
|| ($mime == "image/png"))
&& in_array($extension, $allowedExts)) {*/
// Generate new random name.
$name = sha1(microtime()) . "." . $extension;
// Save file in the uploads folder.
move_uploaded_file($_FILES["file"]["tmp_name"], getcwd() . "/uploads/" . $name);
// Generate response.
$response = new StdClass;
$response->link = "http://localhost/test/editor-3/html/uploads/" . $name;
echo stripslashes(json_encode($response));
//}
?>
Now Open included javascript file image.min.js and just find and change the imageUploadURL parameter to url of your upload_image.php file, in my case, it is:
imageUploadURL: "http://localhost/test/editor-3/html/upload_image.php",
I am going to add an answer here because for one Froala's documentation is terrible. I had experienced multiple issues with both image and file uploads and spent many hours going crazy till after a few weeks I finally figured out the issue and hope this can help someone else.
First
fileAllowedTypes: ['*']
documentation
The following Froala specifies that this option will allow any file type to be uploaded...wrong. The thing that Froala is not telling you is that in order to be able to upload any file type you have to specify the extension of the file as well as the MIME-type. If you don't reguardless of this option it will not work. It will only allow PDF and TXT.
What to do
When you download the Froala SDK you need to head over to
wysiwyg-editor-php-sdk-master/lib/FroalaEditor/File.php //for File upload
and
wysiwyg-editor-php-sdk-master/lib/FroalaEditor/Image.php //for Image upload
In those files you will see something like
'allowedExts' => array('zip', 'txt', 'pdf'),
'allowedMimeTypes' => array(
'text/plain',
'application/pdf',
'application/zip'
)
This is where you need to add your extensions and MIME-types that you want to allow. You must specify both the extension and MIME-type of the file.
If you are having trouble finding the MIME-type of a particular file just use this site.
I am guessing that this might apply to other languages as well or at least be a similar solution but I can confirm this for php
Hope this helps someone out in the future.

PHP redirect after form processing

I've been staring at code too long however when I used a simple script to save a form with:
endif;
header('Location: http:/mysite.com/evo/codesaveindex.php');
?>
at the end the page redirected back to itself just fine, however now I have a longer script here I can't quite figure out where or how to code my redirect:
<?php
session_start();
$directory = 'users/'.$_SESSION['username'].'/';
//here you can even check if user selected 'Delete' option:
if($_POST['Action'] == "DELETE"){
$file_to_delete = $_POST['CodeList'];
if(unlink($directory.'/'.$file_to_delete))
echo $file_to_delete." deleted.";
else
echo "Error deleting file ".$file_to_delete;
}
if($_POST['Action'] == "SAVE"){
// If a session already exists, this doesn't have any effect.
session_start();
// Sets the current directory to the directory this script is running in
chdir(dirname(__FILE__));
// Breakpoint
if( empty($_SESSION['username']) || $_SESSION['username'] == '' ) echo 'There is no session username';
if( empty($_POST['CodeDescription']) || $_POST['CodeDescription'] == '' ) echo 'There is no POST desired filename';
// This is assuming we are working from the current directory that is running this PHP file.
$USER_DIRECTORY = 'users/'.$_SESSION['username'];
// Makes the directory if it doesn't exist
if(!is_dir($USER_DIRECTORY)):
mkdir($USER_DIRECTORY);
endif;
// Put together the full path of the file we want to create
$FILENAME = $USER_DIRECTORY.'/'.$_POST['CodeDescription'].'.txt';
if( !is_file( $FILENAME ) ):
// Open the text file, write the contents, and close it.
file_put_contents($FILENAME, $_POST['Code']);
endif;
}
?>
may be you should use querystring variable while redirecting.
if($_POST['Action'] == "DELETE") {
$file_to_delete = $_POST['CodeList'];
if(unlink($directory.'/'.$file_to_delete)) {
header('Location: http:/mysite.com/evo/codesaveindex.php?deleted=1&file='.$file_to_delete);
} else {
header('Location: http:/mysite.com/evo/codesaveindex.php?deleted=0& file='.$file_to_delete);
}
}
In codesaveindex.php:
if(isset($_GET['deleted'])&& $_GET['deleted']==1) {
echo $file_to_delete." deleted.";
} elseif(isset($_GET['deleted'])&& $_GET['deleted']==0) {
echo "Error deleting file ".$file_to_delete;
}
You can't redirect if the page after html has been outputted.
You need to either use output buffering or redirect using javascript,
or organise it so that the redirect happens before the html is shown.
i have a class written for such thing, should be very easy to use class.route.php
simply do this where you want to redirect: route::redirect('page', http_status);

image retrieval from directory and session variable issues - php

I have a problem when retrieving the images from a directory on my server, so what the main sequence is: in a page (multiupload.php) I added the input, allowed the image to be previewed and when the user submitted, a new directory with their session id would be created, the images would then be stored in the unique directory and the page would then be directed to (drag.php). The newly loaded page has a canvas with different divs to controls filters that are attached to that canvas. My problem lies with retrieving the image with the specified s_id as a directory name from one page to the other.
Q: Am i retrieving session variables properly? or using them appropriately?
This is the necassary snippets from multiupload.php's upload script.
<?php
$dir_id = session_id(md5(uniqid()));
session_start($dir_id);
$path = "uploads/";
$dir = $path.$dir_id;
$path = $path.$dir_id."/";
if (file_exists($dir)) {
system('/bin/rm -rf ' . escapeshellarg($dir));
} else {
mkdir($path);
chmod($path, 0722);
}
$_SESSION["id"] = $dir_id;
$_SESSION["directory"] = "/" . $dir;
$_SESSION["path_name"] = $path;
?>
I define the directory, whole path and the id for the directory. I would like to retrieve the id in the next page, but it's not doing it correctly.
and this is the retrieval code from drag.php
$realPath = 'uploads/'. echo $_SESSION['id'];
$handle = opendir(dirname(realpath(__FILE__)).$realPath;
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
echo '<img src="uploads/'.$file.'" border="0" />';
}
}
My end result is that I would like all images to be drawn on the page. For now I would like them to be drawn anywhere aslong as they're visible.
If my question isn't clear, feel free to edit or comment where I should change. If you need more code or information, please let me know.
Please modify your code to this code:
<?php
$dir=$_SESSION['id'];
$realPath = '/uploads/'.$dir;
$handle = opendir(dirname(realpath(__FILE__)).$realPath);
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
echo '<img src="'.$realPath.'/'.$file.'" border="0" width="200" />';
}
}
?>
I have use this code an I get the o/p like this:
<?php
$dir_id = session_id(md5(uniqid()));
session_start();
$path = "uploads/";
$dir = $path.$dir_id;
$path = $path.$dir_id."/";
if (file_exists($dir)) {
system('/bin/rm -rf ' . escapeshellarg($dir));
} else {
mkdir($path);
chmod($path, 0722);
}
$_SESSION["id"] = $dir_id;
$_SESSION["directory"] = "/" . $dir;
$_SESSION["path_name"] = $path;
?>
In any file.php, which u need get session:
<?php
session_start();
$realPath = 'uploads/'.$_SESSION['id'];
$handle = opendir(dirname(realpath(__FILE__)).$realPath;
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
echo '<img src="uploads/'.$file.'" border="0" />';
}
}
?>
I advice to you read that: http://www.w3schools.com/php/php_sessions.asp when i was started with php 6 years ago - it was rly helpful
session_start does not take any argument. It's just to put a cookie and to read the session variables. (exposed in $_SESSION). You have to use session_start() on every pages to be able to read the $_SESSION variables.
this will give only image file from directory using session variable.
<?php
$dir=$_SESSION['id'];
$realPath = '/uploads/'.$dir;
$handle = opendir(dirname(realpath(__FILE__)).$realPath);
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
if(fnmatch('*.jpg', $file) || fnmatch('*.png', $file) || fnmatch('*.jpeg', $file)){
echo '<img src="'.$realPath.'/'.$file.'"/>';
}
}
}
?>

Can't Upload Image from froala editor

I'm using XAMPP as the server and well i can't seem to upload the image like the documentation of the editor showed me... here is the link:
http://editor.froala.com/server-integrations/php-image-upload
I already investigated about the problem and normaly they all say is the link that's not correct because you need to put the absolute url there , but even that doesn't seem to work.
Here is the code:
JS
$(document).ready(function(){
$('textarea').editable({inlineMode: false, height:200, imageUploadURL: 'upload_image.php', imageErrorCallback: function (data) {
// Bad link.
console.log(data);
}
});
});
upload_image.php:
<?php
// Allowed extentions.
$allowedExts = array("gif", "jpeg", "jpg", "png");
// Get filename.
$temp = explode(".", $_FILES["file"]["name"]);
// Get extension.
$extension = end($temp);
// An image check is being done in the editor but it is best to
// check that again on the server side.
// Do not use $_FILES["file"]["type"] as it can be easily forged.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES["file"]["tmp_name"]);
if ((($mime == "image/gif")
|| ($mime == "image/jpeg")
|| ($mime == "image/pjpeg")
|| ($mime == "image/x-png")
|| ($mime == "image/png"))
&& in_array($extension, $allowedExts)) {
// Generate new random name.
$name = sha1(microtime()) . "." . $extension;
// Save file in the uploads folder.
move_uploaded_file($_FILES["file"]["tmp_name"], "C:\ xampp\htdocs\Swaggy\img\ " . $name);
// Generate response.
$response = new StdClass;
$response->link = "/swaggy/img/" . $name;
echo stripslashes(json_encode($response));
}
When i try to upload an image he forms an img tag in the editor in base 64 and then dissapears. The debugger shows me that the file upload_image.php has a 200 status and the error that shows me from console is this :
Object {code: 4, message: "Parsing response failed"}
It looks there is a problem with the PHP from your server and the response can't be parsed. You should check with Firebug what is the response from the server when you try to upload an image. finfo_file function for instance is available only starting with PHP 5.3. If your version is older this is the problem most probably.

Multi-Step Form with File Upload

I have a multi-step form. What I want to achieve here is to allow user to upload a file (with some validation using jquery.validate plugin) and store the file to mySQL database.
Previously, I wasnt using multi-step form design (a one-page per step design instead) and therefore when user clicked the "submit" button, I would have if(isset($_POST['submit'])) and $_FILES to validate the file through PHP. Below is the PHP code that will be triggered when user clicked "submit" button .
if(isset($_POST['submit']))
{
$allowedExts = array("mov", "mp4", "mpeg", "wmv");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "video/quicktime") || ($_FILES["file"]["type"] == "video/mp4") || ($_FILES["file"]["type"] == "video/mpeg") || ($_FILES["file"]["type"] == "video/x-ms-wmv")) && in_array($extension, $allowedExts) && (!empty($_POST["title"])) && (!empty($_POST["description"])))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
// check if the file already exist in Uploaded folder
if (file_exists("uploaded/".$_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"]." already exists. ";
}
else
{
echo "<br />".$_FILES["file"]["name"]." has been uploaded! <br /><br />";
echo "Upload: ".$_FILES["file"]["name"]."<br />";
echo "Type: ".$_FILES["file"]["type"]."<br />";
echo "Size: ".($_FILES["file"]["size"] / 1024)." kB<br />";
echo "Stored in: "."uploaded/".$_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], "uploaded/".$_FILES["file"]["name"]);
$name = $_FILES["file"]["name"];
$url = ""; //some URL
mysql_query("INSERT INTO video (name, title, description, url) VALUES ('$name', '$title', '$description', '$url')") or die(mysql_error());
}
}
}
else
{
if (!empty($_POST["description"]) && (!empty($_POST["title"])))
{
echo "Invalid file";
}
}
}
But now, since I have change my design to multi-step form, this logic seems not working anymore. This is my fiddle.
I was thinking to change the "Upload" button type from type="button" to type="submit"so that I can use my old PHP logic to process the file and upload to database, however this causes my multi-step form to stop going to the next step.
Any brilliant ideas or suggestions?
If you want to avoid page reloads, you could try posting the form through a hidden iframe and then reading the response on load. As far as I know this should work in all browsers
<iframe name="target_iframe">..</iframe>
<form target="target_iframe">..</form>
Check out How do you post to an iframe?
If you're happy dropping support for older browsers you can post files using ajax. Maybe check out using html5 for file upload with ajax and jquery

Categories

Resources