This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
How can I get useful error messages in PHP?
(41 answers)
Closed 9 years ago.
Im trying to build an image upload for my site, I have the following only nothing is output at all, yet my page renders okay? Can anybody see where I may be going wrong?\
//if they DID upload a file...
if($_FILES['profile_image']['name'])
{
//if no errors...
if(!$_FILES['profile_image']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['profile_image']['tmp_name']); //rename file
if($_FILES['profile_image']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['profile_image']['tmp_name'], 'uploads/'.$new_file_name);
$message = 'Congratulations! Your file was accepted.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['profile_image']['error'];
}
}
else {
echo 'success';
}
<form method="post" action="./process-signup.php" enctype="multipart/form-data" >
<input type="file" class="profile_image text-input" name="profile_image" placeholder="Upload a picture"/><br />
<input type="submit" id="signup-com-btn" value="Complete Signup" />
</form>
In you PHP script, you have assigned the variable $message to different values, on different stages, like this:
$message = 'Oops! Your file\'s size is to large.';
$message = 'Congratulations! Your file was accepted.';
$message = 'Ooops! Your upload triggered the following error:
but you are not actually echoing it out, so you are not getting any message.
SO, I would recommend echoing it, obviously.
Related
This question already has answers here:
The 3 different equals
(5 answers)
Closed 2 years ago.
A seemingly simple question, but i'm not getting what is wrong with this one.
I have a file upload button that passes ?upload=success in the URL.
I want to show a message when upload is completed; however, even when $upload is not set, I still get the message printed.
Here's the code:
$upload = "";
echo "Upload status: ".$upload;
if ($upload = "success") {
echo "<h3>Upload completed <br></h3>";
} else {
echo "";
}
I don't get why:
when $upload is set to "" the if statements go through and prints the string;
when I complete an upload and I have ?upload=success, the echo "Upload status: ".$upload; return nothing ( and obviously the Upload completed message still gets printed)
Thanks to anybody that will spend a minute to help me :)
Your are using assignment = instead of comparison ==
if ($upload == "success") {
echo "<h3>Upload completed <br></h3>";
} else {
echo "";
}
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!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Wierd... I'm getting that the file was successfully uploaded but in the real world... nothing is uploaded...
Here is my code :
<?php
if
(
move_uploaded_file
(
$_FILES['myUploadedFile']['tmp_name'],
'gangina/'.$uploadedFile=basename($_FILES['myUploadedFile']['name'])
)
)
{
echo "The file ".$uploadedFile." has been uploaded";
}
else
{
echo "There was an error uploading the file, please try again!";
}
?><!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<form action="#" method="POST" enctype="multipart/form-data">
<input name="myUploadedFile" type="file">
<input type="submit" value="Upload">
</form>
</body>
</html>
Small tweak needed here :)
You need to split this up:
if (move_uploaded_file
(
$_FILES['myUploadedFile']['tmp_name'],
'gangina/'.$uploadedFile=basename($_FILES['myUploadedFile']['name'])
)) {
// ...
Instead, do:
$uploadedFile = basename($_FILES['myUploadedFile']['name']);
if (move_uploaded_file
(
$_FILES['myUploadedFile']['tmp_name'],
'gangina/' . $uploadedFile
)) {
// ...
When you do 'gangina/'.$uploadedFile=basename($_FILES['myUploadedFile']['name']) you're actually appending the declaration of $uploadedFile to gangina/, not the value of $uploadedFile. So this would in fact be evaluated to something like gangina/1 because the declaration of $uploadedFile succeeds, gives true, which is evaluated to 1.
You also need to check that the webserver (normally user www-data on linux) has the rights to create new files in the gangina folder (and that that folder actually exists). Under Windows this usually isn't an issue, unless you installed Xampp under Program Files.
Also have a look at this example code on php.net. That shows how to perform all necessary checks to give more precise feedback to the user when handling a file upload in PHP.
Give your submit button a name e.g. name="uploadImage"
<?php
function uploadImage($image,$ftp_file){
// Path and file name
$imgUrl = "gangina/".$image;
if (file_exists($imgUrl)){
$temp = str_ireplace('gangina/', '', $image);
$imgUrl = "gangina/". rand(1,99999).$temp;
}
$img = str_ireplace('gangina/', ' ', $imgUrl);
// Run the move_uploaded_file() function here
if(move_uploaded_file($ftp_file, $imgUrl)){
$results = "image successfully uploaded";
} else {
$results = 'Could not upload image';
}
return $results;
}
if(isset($_POST['uploadImage']{
$imgurl = $_FILES['ImageName']['name'];
$temp = $_FILES['ImageName']['tmp_name'];
//uploading image
uploadImage($imgurl, $temp);
}
?>
This question already has answers here:
how to check if a $_FILE is set in php?
(5 answers)
Closed 8 years ago.
I have an input type ="file" in a form that upload images (multiple images) and other inputs (from textareas) .
I need that, if the user didn't choose any images, I don't want to excecute the upload image.
This because if I use the site from Ipad, the script give me error because he didn't find anything in the file-input[], also if I don't want to upload images.
So I wanna check if the file-input[] is empty or not, so the problem from Ipad will be solved (I hope).
This is the html
<div id="file-ins-immagini">
<div class="et-form-ins">Immagini allegate</div>
<input type="file" name="file-input[]" id="file-input" value="" class="file" multiple>
</div>
And this is the code of the insert in php ('invia' is the name of the submit button of my form)
if (isset($_POST['invia']) && $_POST['invia'] == "Inserisci")
{
$messaggiocaso = "";
$infoimages = array_combine($_FILES["file-input"]['name'], $_FILES["file-input"]['tmp_name']); // recuperiamo e uniamo le informazionei sulle immagini
foreach ($infoimages as $k => $v)
{
$nomefile = strtolower($k);
if(!empty($nomefile))
{
if (filesize($v) < $peso_file)
{
$estensionefile = pathinfo($nomefile, PATHINFO_EXTENSION);
if (in_array(strtolower($estensionefile), $estensioni))
{
if (is_uploaded_file($v))
{
if(!file_exists("$uploadDIR/$next_id"))
{
mkdir("$uploadDIR/$next_id",0777,true);
}
if (!move_uploaded_file($v, "$uploadDIR/$next_id/$nomefile"))
{
$messaggiocaso = urlencode("Impossibile l'inserimento del caso. Impossibile spostare il file $k");
header("location:tabella.php".'?msgcasoerrato='.$messaggiocaso);
exit;
}
else
//the rest of the code
I tryied with
if (isset($_POST['invia']) && $_POST['invia'] == "Inserisci" && !empty($_POST['file-input[]']))
and !empty($_POST['file-input']
but in these cases, the upload don't work anymore on pc.
So how can I check if file-input is empty?
if ($_FILES['file_input']){
foreach($_FILES['file_input']['name'] as $k=>$v){
if(!empty($_FILES['file_input']['name'][$k])){
if($_FILES['file_input']['size'][$k]>0){
// all ok, can be moved ..
}
}
}
}
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!