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
Related
I've created a website with html and javascript that gets access to your webcam and when users press take photo button a photo is captured. How would I go about directly uploading this to some cloud folder where it is stored?
Thanks
On the page where the button is,:
Create the button which snaps the photo(I don't kbnow how that is done)
<button>Snap photo!</button>
Create a form (invisible form) with the value of anything....anything can be the value just make sure it isn't empty
Use javascript so that when the button is clicked,the form is submitted to a php page
Mke the target of the form be an iframe that you have created so that when they snap the photo,it leads to the same page,without reloading the page]
Here's the code for what I just said:
Snap
</form>
<script>
function rad(){
document.getElementById("crap").submit();
</div>
Make the file handler with this code:
$errors = []; // Store all foreseen and unforseen errors here
$fileExtensions = ['jpeg','jpg','png']; // Get all the file extensions
$fileName = $_FILES['myfile']['name'];
$fileSize = $_FILES['myfile']['size'];
$fileTmpName = $_FILES['myfile']['tmp_name'];
$fileType = $_FILES['myfile']['type'];
$fileExtension = strtolower(end(explode('.',$fileName)));
$uploadPath = $currentDir . $uploadDirectory . basename($fileName);
if (isset($_POST['submit'])) {
if (! in_array($fileExtension,$fileExtensions)) {
$errors[] = "This file extension is not allowed. Please upload a JPEG or PNG file";
}
if ($fileSize > 1000000000) {
$errors[] = "This file is more than 1GB. Sorry, it has to be less than or equal to 1GB";
}
if (empty($errors)) {
$didUpload = move_uploaded_file($fileTmpName, $uploadPath);
if ($didUpload) {
echo basename($fileName) ;
} else {
echo "An error occurred somewhere. Try again or contact the admin";
}
} else {
foreach ($errors as $error) {
echo $error . "These are the errors" . "\n";
}
}
}
?>
The only thing is that this uploads the image to your server not a 'cloud folder' ...but it is a folder just place the cloud folder in your webserver then specify the name of the cloud folder in the$uploadDirectory = "/uploads/"; ie change 'uploads' to the name of your cloud folder....
Hopes this helps
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
all.
I've got a big ask, and I have no idea how to go around it.
I want to make a login / signup form, which creates a directory on the server for each new user. This directory, somewhat obviously, must not be publicly accessible by other users, and must automatically copy / make it's index.php file and subdirectories.
I'm afraid that I won't have much luck, as I've never made any form of encrypted login before, let alone a fancy automated one like this.
No code as of yet. Any help appreciated!
Well you need two things:
1st of all a system that you can create the directory and the files:
1 php (if you don't mind) file to create files:
Example code:
<form action="function-create-new-file.php" method="post">
WHAT IS THE NAME OF YOUR PAGE
<input name="file_name" type="text" />
<br />
KIND OF FILE YOU WISH TO CREATE
<select name="file_ext">
<option value=".php" selected>php</option>
<option value=".html">php</option>
</select>
<br /><br /><br />
<input type="submit" class="btn" name="submit" value="Add Page" />
</form>
This file will create your files and you should include this one to process it:
<?php
if(isset($_POST['submit'])) //has the form been submitted?
{
$file_directory = "./test/"; //the directory you want to store the new file in
$file_name = strip_tags($_POST['file_name']);//the file's name, stripped of any dangerous tags
$file_ext = strip_tags($_POST['file_ext']); //the file's extension, stripped of any dangerous tags
$file = $file_directory.$file_name.$file_ext; //this is the entire filename
$create_file = fopen($file, "w+"); //create the new file
if(!$create_file)
{
die("ERROR, NOT POSSIBLE TO COMPLETE YOUR DESIRED INSTRUCTION");
}
$chmod = chmod($file, 0755); //set the appropriate permissions.
//attempt to set the permissions
if(!$chmod)
{
//error changing the file's permissions
echo("ERROR IN THE PERMISSIONS FOR THIS ACTION, PLEASE CHMOD 0755 THIS FILE AND FOLDERS");
echo "<br /><br /><br /><br /><br /><br /><br />";
include ("footer.php");
}
//defenition of the new page contante self created
if (fwrite
($create_file, "this is the content of your new page!") === FALSE)
{
echo "ERROR IN FILE: ($file)\n";
}
fclose($create_file);
//tell the user that the file has been created successfully
echo "The file was created! Take a look ate your file here - <a href='$file' target='_blank'>$file</a>";
exit; //exit the script
}
else{ //the form hasn't been submitted!
header("Location: function-create-new-file.php"); //redirect the user back to the add file page
exit; //exit the script
}
?>
Now second, you need to create a directory:
<?php
// Desired folder structure
$structure = './depth1/depth2/depth3/';
// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.
if (!mkdir($structure, 0777, true)) {
die('Failed to create folders...');
}
// ...
?>
Please check also this link: How to Create a Directory
Now you need to create the login system for the users. You can do that once again in PHP.
<?php
session_start();
function encode_5t_base64($str)
{
for($i=0; $i<5;$i++)
{
$str=strrev(base64_encode($str));
}
return $str;
}
function jh_password_protection($pass_string)
{
$pass_string = encode_5t_base64($pass_string);
$pass_string = md5($pass_string);
$pass_string = sha1($pass_string);
return $pass_string;
}
function registerUser($user,$pass1,$pass2)
{
$errorText = '';
if ($pass1 != $pass2) $errorText = "Password must be the same";
elseif (strlen($pass1) < 6) $errorText = "Password too short";
$pfile = fopen("some/path/to/store/member/password.php","a+");
rewind($pfile);
while (!feof($pfile))
{
$line = fgets($pfile);
$tmp = explode(':', $line);
if ($tmp[0] == $user)
{
$errorText = "That user already exists"; // check it you made duplicated members
break;
}
}
if ($errorText == '')
{
$userpass = jh_password_protection($pass1);
fwrite($pfile, "\r\n$user:$userpass");
}
fclose($pfile);
return $errorText;
}
function loginUser($user,$pass)
{
$errorText = '';
$validUser = false;
$pfile = fopen("path/to/your/user/page.php","r");
rewind($pfile);
while (!feof($pfile)) {
$line = fgets($pfile);
$tmp = explode(':', $line);
if ($tmp[0] == $user)
{
if (trim($tmp[1]) == trim(jh_password_protection($pass)))
{
$validUser= true;
$_SESSION['userName'] = $user;
}
break;
}
}
fclose($pfile);
if ($validUser != true)
$errorText = "That went wrong"; // failed login message
if ($validUser == true) $_SESSION['validUser'] = true;
else $_SESSION['validUser'] = false;
return $errorText;
}
function logoutUser()
{
unset($_SESSION['validUser']);
unset($_SESSION['userName']);
}
function checkUser()
{
if ((!isset($_SESSION['validUser'])) || ($_SESSION['validUser'] != true))
{
header('Location: path/to/your/user/page.php'); // Your user location
exit();
}
}
?>
Now lets make the login system, first step, create a login page as you desire and place this code under content type tag:
<meta http-equiv="Pragma" content="no-cache">
Sample login system form:
<?php
if ($error == '') {
echo "Welcome";
echo "<a href='./path/to/your/member/area/'>Proceed</a>";
}
else echo " $error ";
?>
<?php if ($error != '') {?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
<br/><br/>
<label>USERNAME</label>
<br/><br/>
<input name="username" type="text">
<br/><br/>
<label>PASSWORD</label>
<br/><br/>
<input name="password" type="password">
<br/><br/>
<input value="LOGIN" name="submitBtn" type="submit">
</form>
<?php }
if (isset($_POST['submitBtn'])){
?>
at the top of your page just include this:
<?php
require_once('file/that/operates/the/login.php');
$error = 'wow that was wrong';
if (isset($_POST['submitBtn'])){
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$error = loginUser($username,$password);}
?>
I think i didnt forgot nothing here, but let me know if that helps.
IMO storing the data in a database instead of files would be cleaner and easier.
However if you really need to go with separate folders here's a solution:
Create a simple login/signup form.
On signup, create the user folder in a parent folder you will name for example uploads.
Then you just have to configure your server (you can achieve this with .htaccess) so that every request to the uploads folder gets redirected to a controller (for example index.php)
In index.php, check that the user is logged in and that the folder he's trying to access belongs to him. If it does, render the requested file, if not, render an error message.
in your php file that handles the register function
after a success registration you should add
mkdir("yourtargetpath/" . $username, 0700);
In 2011, I bought a PHP contact form from codecanyon that uses AJAX to process the form. After reporting my problem to them today, they responded saying that they no longer offer support for their 'old' product (so much for the life time support they generally offer as a rule) ... so they aren't going to help me hence this post on SO.
I would say that this isn't a normal issue but I think it's very important that it gets sorted out - here it is (this is my email to the seller but does explain the problem):
=================
I have an unusual issue with your AJAX Contact Form (you're going to have to read carefully and slowly).
Okay everything works 100% fine BUT ... let me explain (basically this has everything to do with the Captcha and verification of it)
My website has many pages with your online form on each of those pages.
Now I also have a listings page that has links going to all of those pages with forms.
EXAMPLE:
Lets say I am on a listings page (a page with a whole load of links going to other pages) and I right click on Link A to open page A in a new tab ... and then I also right click on Link B to open page B in a new tab. Right, so we have the listings page (that's still opened in front of me) and those 2 other pages that opened up in new tabs (Page A and Page B) ... as explained above, both those pages has your online form.
Now, I fill in both forms and click submit.
The first page that I right clicked to open in a new tab (Page A) - that form's Captcha doesn't work even when I've verified it correctly... however the form's Captcha on Page B does work (like it should). Why is it that the Captcha on Page A (the first page I opened) doesn't work?
I get the feeling that in the whole verification system, because Page B was opened up last, the verification is taking that page's captcha code into account, using that captcha for verification (throughout the session surfing on my website) thus making the Captcha on the first opened page (Page A) to not work.
So what I did as an experiment:
I restarted and did the same thing again, IE: I right clicked Link A to open page A in a new tab ... and then I also right click on Link B to open page B in a new tab.
I filled in Page B's Captcha code in Page A's Captcha verification field and what do you know - there's a match!
So this is my problem because I know when some people surf internet (I do this all the time and maybe you do too), they like to right click links to open them in new tabs so that they can get back to them later after browsing the listings page. So the person may have 6 tabs open in the browser and each of those pages has your online form. If the user wants to submit each of those forms, then he/she will experience the exact problem I am reporting above. They will be able to send through 1 form (the last page that was opened in a new tab) but the other page's Captchas won't work unless they refresh the page ... but most people won't think to do that - instead, they will think somethings wrong with the my website - which I am afraid of.
Is there a solution to this?
I'm not even sure if you've noticed this before?
I hoped I've explained the situation clearly and I'd really appreciate it if you could assist.
=================
Now back to you. What's causing this?
There are 3 files needed for the form to work / process etc (I'm not including the CSS file in this post not the html for the form as I don't think it's necessary).
1) process.php
2) image.php (this is for the captcha)
3) ajax.js
PROCESS.PHP
<?php if (!isset($_SESSION)) session_start();
if(!$_POST) exit;
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$address = "email#example.com";
$bcc = "email#example.com";
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if (isset($_POST['verify'])) :
$posted_verify = $_POST['verify'];
$posted_verify = md5($posted_verify);
else :
$posted_verify = '';
endif;
$session_verify = $_SESSION['verify'];
if (empty($session_verify)) $session_verify = $_COOKIE['verify'];
$error = '';
if(trim($name) == '') {
$error .= '<li>Your name is required.</li>';
}
if(trim($email) == '') {
$error .= '<li>Your e-mail address is required.</li>';
} elseif(!isEmail($email)) {
$error .= '<li>You have entered an invalid e-mail
address.</li>';
}
if(trim($phone) == '') {
$error .= '<li>Your phone number is required.</li>';
} elseif(!is_numeric($phone)) {
$error .= '<li>Your phone number can only contain digits
(numbers and no spaces).</li>';
}
if(trim($comments) == '') {
$error .= '<li>You must enter a message to send.</li>';
}
if($session_verify != $posted_verify) {
$error .= '<li>The verification code you entered is
incorrect.</li>';
}
if($error != '') {
echo '<div class="error_title"><h6><span>Attention!
</span> Please correct the errors below and try again</h6>';
echo '<ul class="error_messages">' . $error . '</ul>';
echo '<div class="close"></div>';
echo '</div>';
} else {
if(get_magic_quotes_gpc()) { $comments = stripslashes($comments); }
$e_subject = 'Booking / Enquiry';
$msg = '<html>
<body style="margin:0; padding:0;">
Name: '.$_POST['name'].'
Email: '.$_POST['email'].'
Contact Number: '.$_POST['phone'].'
Notes: '.$_POST['comments'].'
</body>
</html>';
$msg = wordwrap( $msg, 70 );
$headers = "From: $email\r\nBCC:{$bcc}\r\n" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
$headers .= 'Content-Transfer-Encoding: 8bit'. "\n\r\n" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
echo "<div class='success'>";
echo "<h6>Your Enquiry has been Successfully submitted. </h6>";
echo '<div class="close"></div>';
echo "</div>";
} else {
echo 'ERROR!';
}
}
?>
*Please note that in the process.php code above, I removed a function that seems to validate the email address field - reason why I didn't include it in the code above is because it was heavy with code (would take up a lot of space) and I don't think it's necessary to include
IMAGE.PHP
<?php if (!isset($_SESSION)) session_start(); header("(anti-spam-
content-
type:) image/png");
$enc_num = rand(0, 9999);
$key_num = rand(0, 24);
$hash_string = substr(md5($enc_num), $key_num, 5); // Length of
String
$hash_md5 = md5($hash_string);
$_SESSION['verify'] = $hash_md5;
setcookie("verify", $hash_md5, time()+3600, "/");
session_write_close();
$bgs = array("../../img/1.png","../../img/2.png","../../img/3.png");
$background = array_rand($bgs, 1);
$img_handle = imagecreatefrompng($bgs[$background]);
$text_colour = imagecolorallocate($img_handle, 108, 127, 6);
$font_size = 5;
$size_array = getimagesize($bgs[$background]);
$img_w = $size_array[0];
$img_h = $size_array[1];
$horiz = round(($img_w/2)-
((strlen($hash_string)*imagefontwidth(5))/2),
1);
$vert = round(($img_h/2)-(imagefontheight($font_size)/2));
imagestring($img_handle, $font_size, $horiz, $vert, $hash_string,
$text_colour);
imagepng($img_handle);
imagedestroy($img_handle);
?>
AJAX.JS
jQuery(document).ready(function() {
$('.advertform').submit(function() {
var action = $(this).attr('action');
var form = this;
$('.submit', this).attr('disabled', 'disabled').after(
'<div class="loader"></div>').addClass("active");
$('.message', this).slideUp(750, function() {
$(this).hide();
$.post(action, {
name: $('.name', form).val(),
email: $('.email', form).val(),
phone: $('.phone', form).val(),
comments: $('.comments', form).val(),
verify: $('.verify', form).val()
},
function(data) {
$('.message', form).html(data);
$('.message', form).slideDown('slow');
$('.loader', form).fadeOut('fast', function() {
$(this).remove();
});
$('.submit',
form).removeAttr('disabled').removeClass("active");
});
});
return false;
});
$('.message').on('click', function(){
$('.message').slideUp();
});
});
Looking at the code above, can anyone spot what could be causing this problem? I'm assuming this can has to do with the javascript?
The comments are correct, the validation is failing on some forms because the session only holds the value of the last captcha generated therefore making captchas open in other tabs invalid because their value in the session was overwritten. Because of this, anyone using the same or similar code has this problem.
You can solve it fairly simply by changing the session to store an array of codes instead of just one.
In image.php, change:
$_SESSION['verify'] = $hash_md5;
to:
if (!isset($_SESSION['verify'])) $_SESSION['verify'] = array();
$_SESSION['verify'][$hash_md5] = $hash_md5; // *explantion for this array key later
You can also get rid of the cookie that gets set for the captcha, session storage should be fine.
Then in your form processor, change:
if($session_verify != $posted_verify) {
$error .= '<li>The verification code you entered is incorrect.</li>';
}
to:
if(!array_key_exists($posted_verify, $session_verify)) {
$error .= '<li>The verification code you entered is incorrect.</li>';
}
This should allow you to have multiple forms open in multiple tabs and still be able to submit each one without getting the incorrect captcha error.
Also, another issue with this code is that it doesn't unset the session verify value after a successful post. This means a person could solve one captcha and submit your form an unlimited number of times re-using the old code as long as they don't access image.php again between submissions.
To fix this with the array version, you'll need to unset the session key after the captcha and form is processed.
unset($_SESSION['verify'][$posted_verify]); // remove code from session so it can't be reused
Hope that helps.
I have an idea. Store the captcha values in an array, and keep a counter; both stored in SESSION variables.
So in the form you put a hidden input, and set it to the index.
When we check for captcha, we compare $_SESSION['captcha'][$index] to $_POST['captcha'].
Any time you (the client) open a new window; $index is increased.
We pass that index to image.php through the url; example src="img.php?index=2"
Here is a concept; minimal code to accomplish this.
Open a couple of windows with this page. See what happens
img.php
<?php
session_start();
header("(anti-spam-content-type:) image/png");
$captcha_text = rand(0, 99999);
// we read a "index" from the URL, example: <img src="img.php?index=2">
$index = isset($_GET['index']) ? (int) $_GET['index'] : 0;
if( empty($_SESSION['captcha'])) {
$_SESSION['captcha'] = array();
}
$_SESSION['captcha'][$index] = $captcha_text;
// #see http://php.net/manual/en/function.imagestring.php , first example
$im = imagecreate(100, 30);
$bg = imagecolorallocate($im, 55, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);
imagestring($im, 5, 0, 0, $captcha_text, $textcolor);
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
index.php
<?php
session_start();
// we handle the POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_SESSION['captcha'])) {
if ($_SESSION['captcha'][ $_POST['index'] ] == $_POST['captcha']) {
echo '<h2>correct</h2>';
}
else {
echo '<h2>not correct</h2>';
}
echo '<a href="index.php">Back to form</form>';
// header('location: index.php');
exit;
}
// normal page, with form
if(isset($_SESSION['captcha_index'])) {// index
// set a new index
$_SESSION['captcha_index']++;
}
else {
$_SESSION['captcha_index'] = 0;
}
$captcha_index = $_SESSION['captcha_index'];
echo '
<img src="img.php?index=' . $captcha_index . '">
<form action="" method="post">
<input name="captcha">
<input name="index" type="hidden" value="' . $captcha_index . '">
<input type="submit" value="GO">
</form>
';
// we show what's happening. Obviously you don't want to print this after test phase
$captcha = isset($_SESSION['captcha']) ? $_SESSION['captcha'] : array();
echo '
<br>print_r of $_SESSION[captcha]
<pre>' . print_r($captcha, true) . '<pre>
';
?>
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);
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!