I've been having on and off problems with this. It's very inconsistent. I have a form where there is a title (input), short description (input), full description (textarea) and images uploads. (All relevant code below).
After pressing submit on the form, a PHP script is run to handle the file uploads. Before each file is moved from its temporary location, it goes through a series of if statements to be validated. If it fails the validation stage, the else statement of that condition is applied and a PHP session, 'reason', is set to a word depending on the issue. (i.e $_SESSION['reason']="invalidfile'). The user is then redirected back to the form page where, depending on what 'reason' is set to, the user is shown a specific error. The first validation condition works (check all the fields have been filled in). However, none of them work after that one. Except for the fact that sometimes they do.
Any help on this issue would be much appreciated. It may also be useful to know that, sometimes, in Chrome, the images upload but the page never redirects further to the confirm page. This never happens in Microsoft Edge.
HTML Form - Title, Short Description, Full Description, Image Files
// If there is a file uploaded when you redirect back from the confirm page and 'return' is set in the header.
if(isset($_SESSION['file'])){
// For every image uploaded:
for($i = 0; $i < count($_SESSION['file']['destination']); $i++){
// Delete the image because the user is forced to reupload them anyway.
unlink($_SESSION['file']['destination'][$i]);
}
// Unset the 'file' session now we don't need it anymore
unset($_SESSION['file']);
header("Location: index.php?page=createproject");
}
?>
<h1>Create Project</h1>
<p>Go back</p>
<form action="index.php?page=createprojectstorefiles" method="post" enctype="multipart/form-data">
<p>Project Title: <input type="text" name="title" maxlength="35" autocomplete="off"
<?php
if(isset($_SESSION['project_details'])){
echo "value='".$_SESSION['project_details']['title']."'";
}
?>
/></p>
<p>Project Images: <input type="file" name="file[]" accept=".png, .jpg, .jpeg" multiple/></p>
<p><label for="textarea" style="vertical-align: top; margin-right: 5px;">Short Descritption: </label><textarea name="short_description" rows="4" cols="60" maxlength="80" style="resize: none;"><?php
if(isset($_SESSION['project_details'])){
echo $_SESSION['project_details']['short_description'];
}
?></textarea></p>
<p><label for="textarea" style="vertical-align: top; margin-right: 5px;">Full Story: </label><textarea name="long_description" rows="15" cols="125" maxlength="5000" style="resize: none;"><?php
if(isset($_SESSION['project_details'])){
echo $_SESSION['project_details']['long_description'];
}
?></textarea></p>
<?php
// If a reason has been sent for the form not working and the user hasn't been logged out.
if(isset($_SESSION['reason'])){
// If a 'reason' has been sent for not logging in.
if(isset($_SESSION['reason'])){
// Tell the user the reason.
if($_SESSION['reason']=="noinput"){
echo "<p><font color='red'><span class='error'>You can't leave any boxes blank</span></font></p>";
} elseif($_SESSION['reason']=="invalidfile"){
echo "<p><font color='red'><span class='error'>The file must be a '.jpg', '.jpeg' or '.png'</span></font></p>";
} elseif($_SESSION['reason']=="uploaderror"){
echo "<p><font color='red'><span class='error'>There was an error uploading your image!</span></font></p>";
} elseif($_SESSION['reason']=="filetoolarge"){
echo "<p><font color='red'><span class='error'>Your file is too large. The max file size is 500MB</span></font></p>";
} elseif($_SESSION['reason']=="success"){
header("Location: index.php?page=createprojectconfirm");
} else{
echo "<p><font color='red'><span class='error'>Something went wrong in validation, contact a network administrator</span></font></p>";
}
// Once the user has been told, unset the session.
unset($_SESSION['reason']);
// Otherise, presume that it's due to an incorrect username or password.
} else{
echo "<p><font color='red'><span class='error'>Something went wrong in validation, contact a network administrator</span></font></p>";
}
}
?>
<p><button type="reset">Reset Form</button> <button type="submit" name="createproject">Preview Project</button></p>
</form>
PHP Script - Validate and move the uploaded files from the temp folder
// Make sure no reason is set.
if(isset($_SESSION['reason'])){
unset($_SESSION['reason']);
}
if(isset($_SESSION['file'])){
unset($_SESSION['file']);
}
// If the create project form has been submitted:
if(isset($_POST['createproject'])){
// Set all of the variables for the other text boxes in a session called 'project_details'.
$_SESSION['project_details']['title'] = $_POST['title'];
$_SESSION['project_details']['short_description'] = $_POST['short_description'];
$_SESSION['project_details']['long_description'] = $_POST['long_description'];
// If all of the fileds have been filled in:
if(!empty($_POST['title']) && $_FILES['file']['error'][0]=='UPLOAD_ERR_OK' && !empty($_POST['short_description']) && !empty($_POST['long_description'])){
// Count the number of files uploaded.
$fileCount = count($_FILES['file']['name']);
$_SESSION['file']['count'] = $fileCount;
// Do for every uploaded file.
for($i = 0; $i < $fileCount; $i++){
// Set all of the variables for the file upload (file $i).
$file = $_FILES['file'];
$_SESSION['file']['name'] = $_FILES['file']['name'][$i];
$_SESSION['file']['tmpName'] = $_FILES['file']['tmp_name'][$i];
$_SESSION['file']['size'] = $_FILES['file']['size'][$i];
$_SESSION['file']['error'] = $_FILES['file']['error'][$i];
$_SESSION['file']['type'] = $_FILES['file']['type'][$i];
$fileExt = explode(".", $_SESSION['file']['name']);
$_SESSION['file']['actualExt'] = strtolower(end($fileExt));
$allowed = array("jpg", "jpeg", "png");
// If the file type is allowed:
if(in_array($_SESSION['file']['actualExt'], $allowed)){
// If there was no error uploading the file:
if($_SESSION['file']['error'] == 0){
// If the file isn't too large:
if($_SESSION['file']['size'] < 500000){
// Move the file from the temporary location to the new destination and set $_SESSION['reason'] to success so the page redirects to the confirm page. This shouldn't have to be neccesary to make it work but it is. No body on earth knows why.
$fileNameNew = uniqid("", true).".".$_SESSION['file']['actualExt'];
$_SESSION['file']['destination'][$i] = "projects/uploads/".$fileNameNew;
move_uploaded_file($_SESSION['file']['tmpName'], $_SESSION['file']['destination'][$i]);
// Otherwise, inform the user.
} else{
for($i = 0; $i < count($_SESSION['file']['destination']); $i++){
// Delete the image because the user is forced to reupload them anyway.
unlink($_SESSION['file']['destination'][$i]);
}
$_SESSION['reason']="filetoolarge";
header("Location: index.php?page=createproject");
exit();
}
// Otherwise, inform the user.
} else{
for($i = 0; $i < count($_SESSION['file']['destination']); $i++){
// Delete the image because the user is forced to reupload them anyway.
unlink($_SESSION['file']['destination'][$i]);
}
$_SESSION['reason']="uploaderror";
header("Location: index.php?page=createproject");
exit();
}
// Otherwise, inform the user.
} else{
for($i = 0; $i < count($_SESSION['file']['destination']); $i++){
// Delete the image because the user is forced to reupload them anyway.
unlink($_SESSION['file']['destination'][$i]);
}
$_SESSION['reason']="invalidfile";
header("Location: index.php?page=createproject");
exit();
}
}
// After all the files have been uploaded, if the header function doesn't work, use the session method to redirect to the complete page.
if(!header("Location: index.php?page=createprojectconfirm")){
$_SESSION['reason']="success";
exit();
}
// Otherwise, inform the user.
} else{
$_SESSION['reason']="noinput";
header("Location: index.php?page=createproject");
exit();
}
} else{
header("Location: index.php?page=admin");
exit();
}
The issue lied in the first block of code. At the top there is an if statement to unset the session 'file' if the user has returned from the preview page. This contains a condition of if 'file' is set when loading the page. This scenario could also exist not just when the user has returned from the preview page because they choose to but also if there was an error. This if statement then reloads the page thus clearing the 'reason' session and the error doesn't show.
I fixed it by editing the conditions of the if statement. By adding a check to make sure that the 'reason' session hasn't been set i.e, there was no error but the user chose to return:
if(isset($_SESSION['file']) && !isset($_SESSION['reason'])){
// For every image uploaded:
for($i = 0; $i < count($_SESSION['file']['destination']); $i++){
// Delete the image because the user is forced to reupload them anyway.
unlink($_SESSION['file']['destination'][$i]);
}
// Unset the 'file' session now we don't need it anymore
unset($_SESSION['file']);
header("Location: index.php?page=createproject");
}
Related
In my project, i have a login page with verification code.
Some verification code of login page is like:
<form class="form-login" action="index.php" method="post">
<input type="text" name="code" class="form-control" placeholder="verification code">
<img id="codeImg" src="create_code.php" alt="not clear, another" style="cursor: pointer; vertical-align:middle" onClick="create_code()">
</form>
In create_code.php, some code about creating verification code is like:
session_start();
header("Content-type: image/png");
$str = "1,2,3,4,5,6,7,8,9,a,b,c,d,f,g";
$list = explode(",", $str);
$cmax = count($list) - 1;
$verifyCode = '';
for ( $i=0; $i < 5; $i++ ){
$randnum = mt_rand(0, $cmax);
$verifyCode .= $list[$randnum];
}
$_SESSION['code'] = $verifyCode; // stor verifycode in session
In index.php, I need to check the inpu verifycode and session verifycode, some code is like:
session_start();
if(!isset($_GET['log_out']) && ($_POST['code'] != $_SESSION['code']))
{
echo "verifycode is wrong!<br />" . "<meta http-equiv='refresh' content='2;url=index.html'>";
die();
}
But unlucky, it is fail. I have found there is nothing in $_SESSION['code']。$_SESSION['code'] should be a value, but a blank instead.
besides, it worked OK a few days ago, but it fails today. I have no changed any code, it seems nothing wrong, who can help me ?
I have solved this problem。 My Linux server disk space is 100%. When I deleted some files, it works Ok. Is there some session log file can print prompt message ?
Edit 2 : I notices user can upload unlimited files and can take all disk space, how to prevent that?
Edit: since no one answered this question, is there a source I could read to get my answer???
I have a contact form. There are three inputs. I used a jQuery plugin for uploading files. This plugin adds another form element and uploads files by ajax.
I'm kind of beginner but this code is for a customer and a real job so I want to make sure it's safe!
in my view:
<form action="" method="post" enctype="multipart/form-data" >
<input type="text" name="name" />
<input type="number" name="phone" />
<textarea name="enquiry" rows="10" ></textarea>
<div id="upload-div">
<div id="extraupload">Upload</div>
<input type="hidden" name="count" value="0" id="count"/>
<input type="submit" />
$(document).ready(function()
{
var uploadObj = $("#extraupload").uploadFile({
url:"/uplod_url",
fileName:"file",
onSuccess:function(files,data,xhr,pd)
{
data = jQuery.parseJSON(data);
if(data.status == 'success') {
var count = $('#count').val() * 1 + 1;
for(var i=0; i<data.files.length; i++) {
$('<input type="hidden" name="file_'+count+'" value="'+data.files[i]+'">').insertBefore('#extraupload');
$('#count').val(count);
count++;
}
}
},
});
});
</script>
each successful upload,will add one to input count value
and will append an hidden input with the value of uploaded file name.
In php I check for file type and change file name:
upload_url.php:
if ($_FILES['file']['type']=='image/jpeg' || $_FILES['file']['type']=='image/pjpeg') {
$ext = '.jpg';
}
elseif ($_FILES['file']['type']=='image/png') {
$ext = '.png';
}
elseif ($_FILES['file']['type']=='application/pdf') {
$ext = '.pdf';
}
else {
echo json_encode('Only images and pdf files are allowed!');
die();
}
$fileName = md5(uniqid());
$fileName = $fileName.$ext;
move_uploaded_file($_FILES["file"]["tmp_name"], 'image/tmp'.$fileName);
$result = array('status'=> 'success','files' => $fileName);
echo json_encode($result);
After changing the file's name to a unique hash, I save that in a tmp folder.
then when the main form is submitted this is what happens:
//validation method: if that file exists in tmp folder
if(isset($this->request->post['count']) && is_numeric($this->request->post['count'])) {
for($i=1; $i<=$this->request->post['count']; $i++ ) {
if(isset($this->request->post['file_'.$i])){
if(!file_exists('image/tmp/'.$this->request->post['file_'.$i])){
//throw error
}
} else{
//throw error
}
}
}
// hidden input count can only be integer
if(isset($this->request->post['count']) && !is_numeric($this->request->post['count'])) {
//throw error
}
and then mailing the file and saving file name in database(I did not include database part because I'm kind of sure it's ok)
//by every submition delete files in tmp folder older than 1 day
$oldFiles = glob($tmp_dir."*");
$now = time();
foreach ($oldFiles as $oldFile) {
if (is_file($oldFile)) {
if ($now - filemtime($oldFile) >= 60 * 60 * 24) {
unlink($oldFile);
}
}
}
$mail = new Mail();
//Mail Setting and details deleted
//if there's any file uploaded
if($this->request->post['count'] != 0) {
//unique directory for every form submition
$dir_path = 'image/submitted/'.uniqid();
mkdir($dir_path, 0764, true);
//for all hidden inputs move file from tmp folder to $dir_path
for ($i=1; $i <= $this->request->post['count']; $i++) {
$file = $this->request->post['file_'.$i];
rename('image/tmp'.$file, $dir_path.'/'.$file);
$mail->AddAttachment($dir_path.'/'.$file);
}
}
$mail->send();
now my question is: Is it safe this way? especially when I append hidden inputs with file's name and get the number of uploaded files from hidden input count??
This code already works, but I think this might be a security issue.
Thanks a lot for your patience and sorry for my poor english!
ps: I use opencart
There is the general misconception that in AJAX applications are more secure because it is thought that a user cannot access the server-side script without the rendered user interface (the AJAX based webpage). XML HTTP Request based web applications obscure server-side scripts, and this obscurity gives website developers and owners a false sense of security – obscurity is not security. Since XML HTTP requests function by using the same protocol as all else on the web (HTTP), technically speaking, AJAX-based web applications are vulnerable to the same hacking methodologies as ‘normal’ applications.
I'm looking to return to the previous page after a file upload and have "file uploaded successfully" on the upload page.
In upload.php at the top I have placed
sesssion_start();
And at the end of the file upload script I have placed
$_SESSION['upload_success'] = TRUE;
header("Location: stream.php");
Now I know i need to put some code into the html document but unsure what needs to go in. Below is my html form script
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="90000000" />
Select video to upload:
Please choose a file: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
I know it is going to be something similar to this but unsure how or where I would place it.
session_start();
if (isset($_SESSION['upload_success']) && $_SESSION['upload_success']) {
echo "File uploaded successfully";
}
If someone could walk me through adding the HTML code into the correct place I will be very greatful
After the comments i amend my php code to look like this.
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
sesssion_start();
$target_path = "upload/";
$target = $target_path . basename($_FILES['uploadedfile']['name'] );
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'] , $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name'] ). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
$_SESSION['upload_success'] = TRUE;
header("Location: stream.php");
exit();
And the syntax inside the stream.php to:
<?phpsession_start();
if (isset($_SESSION['upload_success']) && $_SESSION['upload_success']) {
echo "File uploaded successfully";
}
?>
Thanks,
Mark
Nota: You also cannot use echo and header together because that would considered as outputting before header, so we'll just use a session array as the message and the header to redirect to "upload_form.php", then show the respective message on that page afterwards.
Use session_destroy() also to destroy any previous sessions.
Sidenote: Use two seperate files.
HTML form: call this "upload_form.php"
<?php
session_start();
session_destroy();
?>
<form action="stream.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="90000000" />
Select video to upload:
Please choose a file: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File">
</form>
<?php
if(isset($_SESSION['upload_success'])){
echo $_SESSION['upload_success'];
}
else{
echo "Please select a file.";
}
?>
PHP (file 2): call this "stream.php"
<?php
session_start();
$target_path = "upload/";
$target = $target_path . basename($_FILES['uploadedfile']['name'] );
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'] , $target))
{
$_SESSION['upload_success'] = "File successfully uploaded.";
header("Location: upload_form.php");
exit;
}
else {
$_SESSION['upload_success'] = "Sorry, there was a problem uploading your file.";
header("Location: upload_form.php");
exit;
}
Edit:
Modify and add the following after if(move_uploaded_file...
if(isset($_FILES['uploadedfile']) && !empty($_FILES['uploadedfile'])){
$target_path = "upload/";
$target = $target_path . basename($_FILES['uploadedfile']['name']);
}
Your code works fine, but you should remove session['upload_success'] with unset function after you do echo success message.
try
unset( $_SESSION['upload_success'])
in stream.php right after
echo "File uploaded successfully";
update :
if you want to work all these on a single page, You can simply do it like below:
if(isset($_SESSION['upload_success']) and $_SESSION['upload_session'])
{
//echo success message
//remove session
}
if(isset($_POST['file'])){
//upload process , if it was successfull make seesion true...
}
else {
//show form
}
For a quick solution, you could use Ravi Kusuma's jQuery File Upload Plugin or an AJAX solution to do this.
Another alternative, though, to those proposed above is to programmatically construct / output an HTML form with some javascript, and get it to POST a message to stream.php:
CAVEAT: I haven't tried this myself, but I can't think why it wouldn't work. Would someone please confirm my sanity? -- Tested it myself: it works.
<?php
//upload.php
//Do file upload stuff, then:
$out = '
<form id="frmUpOkay" action="stream.php" method="post">
<input name="upMsg" value="Upload Successful" />
</form>
<script type="text/javascript">
$(function(){
$("#frmUpOkay").submit();
});
</script>
';
echo $out;
?>
You must also add this bit to the top of the stream.php file:
<?php
if ( isset($_POST['upMsg']) && isset($_POST['upMsg']) != '' ){
$upMsg = $_POST['upMsg']; //you should sanitize this input
}else{
$upMsg = '';
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div>
Your normal website content is here.<br>
<br>
Upload message: <?php echo $upMsg; ?> <br>
<br>
</div>
</body>
Notes:
Above code uses jQuery, so you would need the jQuery library included on your upload.php page (as shown above).
Placing
$_SESSION['upload_success'] = TRUE;
header("Location: stream.php");
At the end, I believe, would set true no matter what actually happened with the file's upload the reason being, there is not a condition being checked.
Unless the script has an exit command when it fails, it will eventually get to the part where it says: "Set the upload success as true and then go to stream.php" rather than saying, "If the upload is successful, set the upload success as true and then go to stream.php"
I would try:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
if($_FILES['uploadedfile']['size'] == 0)//In other words, if no file was selected.
{
$_SESSION['upload_success'] = 4;//File wasn't selected
header("Location: stream.php");
exit();
}
if(!file_exists('upload/' . basename($_FILES['uploadedfile']['name'])))
{
$_SESSION['upload_success'] = (move_uploaded_file($_FILES['uploadedfile']['tmp_name'],'upload/' . basename($_FILES['uploadedfile']['name'])) ? 1 : 2);
}
elseif(file_exists('upload/' . basename($_FILES['uploadedfile']['name'])))
{
$_SESSION['upload_success'] = 3;
}
header("Location: stream.php");
exit();
?>
Now in stream.php where you have your if statement that displays the message do this instead:
<?php
session_start();
switch (#$_SESSION['upload_success']) {
case 1:
echo "File uploaded successfully";
break;
case 2:
echo "Sorry, there was a problem uploading your file.";
break;
case 3:
echo "A file with that name already exists!";
break;
case 4:
echo "You must select a file to upload!";
break;
}
unset($_SESSION['upload_success']);
?>//So if you reload stream.php yet another time no messages will be displayed again for no reason. ie. none of the cases will match an unset variable.
Last, you cannot echo (or do any type of output meant to be viewed by a user) before you header(Location: "somepage.php");
The page will switch before the user can read the output.
The way your code is currently written in your question you could have the following happen:
The server echos "Sorry, there was a problem uploading your file", which will never be seen by the user.
$_SESSION['upload_success'] is then set to TRUE, which is obviously not in agreement with #1.
It then sends the user to stream.php where a success message is
displayed.
An alternate, lazier way with less useful scenario descriptions to also fix your problem would be to do this instead (in upload.php):
else
{
die("Sorry, there was a problem uploading your file.");
}
Hope that helps!
When I go to myserver index and upload and image from there using the interface, it works fine. But as soon as I try to enter the path myself, like:
http://myserver/upload.php?image['name']=F:\Bilder\6.jpg
it gives me an error that all fields are required. But I have to upload images like this, because I plan to implement it in an app that I'm making. Thing is, that I'm not that well acquainted with php.
here is the upload.php
<?php
session_start();
require("includes/conn.php");
function is_valid_type($file)
{
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$TARGET_PATH = "images/";
$image = $_FILES['image'];
$image['name'] = mysql_real_escape_string($image['name']);
$TARGET_PATH .= $image['name'];
if ( $image['name'] == "" )
{
$_SESSION['error'] = "All fields are required";
header("Location: index.php");
exit;
}
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
header("Location: index.php");
exit;
}
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
header("Location: index.php");
exit;
}
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
$sql = "insert into Avatar (filename) values ('" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
exit;
}
else
{
header("Location: index.php");
exit;
}
?>
and the index.php
<?php
if (isset($_SESSION['error']))
{
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p>
<label>Avatar</label>
<input type="file" name="image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<input type="submit" id="submit" value="Upload" />
</p>
the problem lies in
if ( $image['name'] == "" )
$image has no value there.
You are doing a get request so if you would like to know what the image variable is you should use
$_GET['image']
Another thing is that you are doing $image = $_FILES['image'];
$_FILES will only be available from a post request.
Uploading files can not be done in the way you are doing now by a parameter from a GET request.
If you need to POST stuff to a web form (as opposed to GETting, which is what you're doing here), you can't just specify the data to be POSTed as part of the URL.
Have a look at those HTTP methods (GET and POST) to understand the difference.
In your app, what you need to do is POST stuff to the URL. Depending on which tools you use to program, you should look into how to send data via POST.
Also, try to see if an implementation of curl (or libcurl) is available to your development platform.
That simply wont work since you cannot upload an image by sending $_GET[] variables through the url.
As you can see in the upload.php page you got, the file is retrieved in the php page through a $_FILES['image'].
If you change that to $_GET['image'] and retry to post the link with the get variable you suggest, you probably will be able to see the path to your file but it will only be as a string type and not an actual uploaded file object.
So basically I have a site in which certain members are allowed to upload images (comic pages) to their own image galleries (to a specific comic). I have a successful image uploading script that I used to upload profile/avatar images for each member, but now that I want to upload files to a more specific place I'm having a little trouble.
Here's what I have so far:
(This is what appears at the top of the page)
<?php
session_start();
$toplinks = "";
if (isset($_SESSION['id'])) {
// Put stored session variables into local php variable
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '' . $username . ' •
Account •
Log Out';
} else {
$toplinks = 'Register • Login';
}
?>
(This is the uploading script)
<?php
// Here we run a login check
if (!isset($_SESSION['id'])) {
echo 'Please log in to access your account';
exit();
}
// Place Session variable 'id' into local variable
$id = $_SESSION['id'];
// Process the form if it is submitted
if ($_FILES['uploadedfile']['tmp_name'] != "") {
// Run error handling on the file
// Set Max file size limit to somewhere around 120kb
$maxfilesize = 400000;
// Check file size, if too large exit and tell them why
if($_FILES['uploadedfile']['size'] > $maxfilesize ) {
echo "<br /><br />Your image was too large. Must be 400kb or less, please<br /><br />
click here to try again";
unlink($_FILES['uploadedfile']['tmp_name']);
exit();
// Check file extension to see if it is .jpg or .gif, if not exit and tell them why
} else if (!preg_match("/\.(gif|jpg|png)$/i", $_FILES['uploadedfile']['name'] ) ) {
echo "<br /><br />Your image was not .gif, .jpg, or .png and it must be one of those three formats.<br />
click here to try again";
unlink($_FILES['uploadedfile']['tmp_name']);
exit();
// If no errors on the file process it and upload to server
} else {
// Rename the pic
$newname = ""; //numbers only, so they show up sequentially
// Set the direntory for where to upload it, use the member id to hit their folder
// Upload the file
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], "comics/$comicid/".$newname)) {
echo "Success, the image has been uploaded and will display to visitors!<br /><br />
Click here to return to your profile edit area";
exit();
} else {
echo "There was an error uploading the file, please try again. If it continually fails, contact us by email. <br /><br />
Click here to return to your profile edit area";
exit();
}
} // close else after file error checks
} // close if post the form
?>
Ideally, I would like to be able to upload an image like this: comics/comic_id/chapter_id/uploaded_file.extension
With the user profile image uploader, I was able to grab the $ID from the $_Session['id'] variable, but with the comics, I don't really know how to grab that information and use it to set the comic_id directory (chapter_id will be selected on the form so I'm not too worried about that one).
Any thoughts?
You can upload a file to wherever you choose. This will save the comic in a folder of its id and chapter, but retaining the filename. If you wanted to use the comic id as the filename I am sure you can work that out.
$basepath = "/home/path/to/www/comics/member_" . $member_id . "/";
function construct_path($chapter_id,$comic_id)
{
$saveimagepath = $basepath . $comic_id . $chapter
}
if (!isset($_SESSION['id'])) {
echo 'Please log in to access your account';
exit();
}
// Place Session variable 'id' into local variable
$id = $_SESSION['id'];
// Process the form if it is submitted
if ($_FILES['uploadedfile']['tmp_name'] != "") {
// Run error handling on the file
// Set Max file size limit to somewhere around 120kb
$maxfilesize = 400000;
// Check file size, if too large exit and tell them why
if($_FILES['uploadedfile']['size'] > $maxfilesize ) {
echo "<br /><br />Your image was too large. Must be 400kb or less, please<br /><br />
click here to try again";
unlink($_FILES['uploadedfile']['tmp_name']);
exit();
// Check file extension to see if it is .jpg or .gif, if not exit and tell them why
} else if (!preg_match("/\.(gif|jpg|png)$/i", $_FILES['uploadedfile']['name'] ) ) {
echo "<br /><br />Your image was not .gif, .jpg, or .png and it must be one of those three formats.<br />
click here to try again";
unlink($_FILES['uploadedfile']['tmp_name']);
exit();
// If no errors on the file process it and upload to server
} else {
// Rename the pic
$newname = $saveimagepath . $_FILES['uploadedfile']['tmp_name'];
//numbers only, so they show up sequentially
// Set the direntory for where to upload it, use the member id to hit their folder
// Upload the file
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $newname)) {
echo "Success, the image has been uploaded and will display to visitors!<br /><br />
Click here to return to your profile edit area";
exit();
} else {
echo "There was an error uploading the file, please try again. If it continually fails, contact us by email. <br /><br />
Click here to return to your profile edit area";
exit();
}
} // close else after file error checks
} // close if post the form
?>
The $_SESSION variable is available at any site you started with session_start(). So if the id is set right after the login, you can access this value at any other page in the same way with $_SESSION['id']. Make sure that the value of id won't kill your filesystem or leads to security issues!