Code below works fine without PRG, BUT i want PRG because i really hate refresh-repost. Though, i did not foresee that problem: i assume that if i dont upload my images immediately with post, get wont find any files to move from temp folder to server folder (they are deleted immediately after post i guess?).
Now, since images should be uploaded before filtered anyway (using server sided languages), i had an idea of uploading without using PRG, and then using a session state like a temp file that will include all the submit info in order just to destroy it and get refresh-repost free... well, its not working. I know it uploads only the correct files, BUT i cant get any $vars out of it, resulting in being unable to show my $error variables / warnings for users.
So... how do i get two birds with one shot php gurus?
trying to figure out if 'fake' sessions can work:
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_POST['submit_pic'])) {
$countfiles = count($_FILES['image']['name']);
$target_dir = "../images/";
$error_array = array();
$upload_array = array();
$eupload_array = array();
for($i=0;$i<$countfiles;$i++) {
$filename = $_FILES['image']['name'][$i];
$target_file = $target_dir.$filename;
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$check = getimagesize($_FILES["image"]["tmp_name"][$i]);
if($check !== false) {
$uploadOk = 1;
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
array_unshift($error_array, "Image $filename is not JPG, JPEG, PNG or GIF.");
$uploadOk = 0;
}
} else {
array_unshift($error_array, "File $filename is not an image.");
$uploadOk = 0;
}
if (file_exists($target_file)) {
array_unshift($error_array, "Image $filename already exists.");
$uploadOk = 0;
}
if ($_FILES["image"]["size"][$i] > 500000) {
$u = 1;
array_unshift($error_array, "Image $filename is too large.");
$uploadOk = 0;
}
if ($uploadOk == 0) {
array_unshift($eupload_array, "Sorry, image $filename was not uploaded.");
} else {
if (move_uploaded_file($_FILES['image']['tmp_name'][$i], $target_file)) {
array_unshift($upload_array, "Image $filename has been uploaded.");
} else {
array_unshift($eupload_array, "Sorry, $filename there was an error uploading your file.");
}
}
}
}
if(strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0) {
$_SESSION['postdata'] = $_FILES;
header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
exit;
}
if( isset($_SESSION['postdata'])) {
$_FILES = $_SESSION['postdata'];
unset($_SESSION['postdata']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel='stylesheet' href='../assets/style.css'/>
<title>CMS TEST</title>
</head>
<body>
<div class='container'>
<a href='add_picture.php' id='logo'><h2>Add Picture</h2></a>
<br/>
<small class='test_warning' style='color:#B83333'>
❶ Images should be JPG, JPEG, PNG or GIF format extentions. <br/>
❷ Images should not be above 500KB size.<br/>
❸ Please try to rename images before uploading for easier use.
</small> <br/><br/>
<form action='add_picture.php' method="post" enctype="multipart/form-data">
<input type="file" name="image[]" id="image" class="custom-file-input" multiple required/><br/><br/><br/>
<input type="submit" value="Upload" name="submit_pic"/>
</form>
<?php if (!empty($upload_array)) { ?>
<small style='color:#00FF00'>
<?php echo '<br/><br/>', implode("<br/>",$upload_array), '<br/>'; ?>
</small>
<?php }?>
<?php if (!empty($eupload_array)) { ?>
<small style='color:#aa0000'>
<?php echo '<br/><br/>', implode("<br/>",$eupload_array), '<br/>'; ?>
</small>
<?php }?>
<?php if (!empty($error_array)) { ?>
<small style='color:#aa0000'>
<?php echo implode("<br/>",$error_array), '<br/>'; ?>
</small>
<?php }?>
<br/><br/>
<a href='index.php'>← Back</a>
<br/>
</div>
<a class='logout' href='logout.php'>Logout</a>
</body>
</html>
<?php
} else {
header('Location:index.php');
}
?>
'proper one':
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if( strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0) {
$_SESSION['postdata'] = $_FILES;
header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
exit;
}
if( isset($_SESSION['postdata'])) {
$_FILES = $_SESSION['postdata'];
$countfiles = count($_FILES['image']['name']);
$target_dir = "../images/";
$error_array = array();
$upload_array = array();
$eupload_array = array();
for($i=0;$i<$countfiles;$i++) {
$filename = $_FILES['image']['name'][$i];
$target_file = $target_dir.$filename;
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$check = getimagesize($_FILES["image"]["tmp_name"][$i]);
if($check !== false) {
$uploadOk = 1;
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
array_unshift($error_array, "Image $filename is not JPG, JPEG, PNG or GIF.");
$uploadOk = 0;
}
} else {
array_unshift($error_array, "File $filename is not an image.");
$uploadOk = 0;
}
if (file_exists($target_file)) {
array_unshift($error_array, "Image $filename already exists.");
$uploadOk = 0;
}
if ($_FILES["image"]["size"][$i] > 500000) {
$u = 1;
array_unshift($error_array, "Image $filename is too large.");
$uploadOk = 0;
}
if ($uploadOk == 0) {
array_unshift($eupload_array, "Sorry, image $filename was not uploaded.");
} else {
if (move_uploaded_file($_FILES['image']['tmp_name'][$i], $target_file)) {
array_unshift($upload_array, "Image $filename has been uploaded.");
} else {
array_unshift($eupload_array, "Sorry, $filename there was an error uploading your file.");
}
}
}
unset($_SESSION['postdata']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel='stylesheet' href='../assets/style.css'/>
<title>CMS TEST</title>
</head>
<body>
<div class='container'>
<a href='add_picture.php' id='logo'><h2>Add Picture</h2></a>
<br/>
<small class='test_warning' style='color:#B83333'>
❶ Images should be JPG, JPEG, PNG or GIF format extentions. <br/>
❷ Images should not be above 500KB size.<br/>
❸ Please try to rename images before uploading for easier use.
</small> <br/><br/>
<form action='add_picture.php' method="post" enctype="multipart/form-data">
<input type="file" name="image[]" id="image" class="custom-file-input" multiple required/><br/><br/><br/>
<input type="submit" value="Upload" name="submit_pic"/>
</form>
<?php if (!empty($upload_array)) { ?>
<small style='color:#00FF00'>
<?php echo '<br/><br/>', implode("<br/>",$upload_array), '<br/>'; ?>
</small>
<?php }?>
<?php if (!empty($eupload_array)) { ?>
<small style='color:#aa0000'>
<?php echo '<br/><br/>', implode("<br/>",$eupload_array), '<br/>'; ?>
</small>
<?php }?>
<?php if (!empty($error_array)) { ?>
<small style='color:#aa0000'>
<?php echo implode("<br/>",$error_array), '<br/>'; ?>
</small>
<?php }?>
<br/><br/>
<a href='index.php'>← Back</a>
<br/>
</div>
<a class='logout' href='logout.php'>Logout</a>
</body>
</html>
<?php
} else {
header('Location:index.php');
}
?>
Besides temp pictures not existing between post get requests, also the variables are deleted from refreshing and i could not use them inside my html to show errors.
So i tried to play around with sessions even more, i moved the pic upload code to post, created some sessions to store my error arrays, and then at get i recreated my error arrays from the sessions i created for them.
Problem solved, pics are filtered, errors displaying, PRG is working.
Gosh... i just started with php there are soooo many things i dont understand D:
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if( strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0) {
$_SESSION['postdata'] = $_FILES;
$error_array = array();
$upload_array = array();
$eupload_array = array();
$countfiles = count($_FILES['image']['name']);
$target_dir = "../images/";
for($i=0;$i<$countfiles;$i++) {
$filename = $_FILES['image']['name'][$i];
$target_file = $target_dir.$filename;
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$check = getimagesize($_FILES["image"]["tmp_name"][$i]);
echo $_FILES["image"]["tmp_name"][$i];
if($check !== false) {
$uploadOk = 1;
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
array_unshift($error_array, "Image $filename is not JPG, JPEG, PNG or GIF.");
$uploadOk = 0;
}
} else {
array_unshift($error_array, "File $filename is not an image.");
$uploadOk = 0;
}
if (file_exists($target_file)) {
array_unshift($error_array, "Image $filename already exists.");
$uploadOk = 0;
}
if ($_FILES["image"]["size"][$i] > 500000) {
$u = 1;
array_unshift($error_array, "Image $filename is too large.");
$uploadOk = 0;
}
if ($uploadOk == 0) {
array_unshift($eupload_array, "Sorry, image $filename was not uploaded.");
} else {
if (move_uploaded_file($_FILES['image']['tmp_name'][$i], $target_file)) {
array_unshift($upload_array, "Image $filename has been uploaded.");
} else {
array_unshift($eupload_array, "Sorry, $filename there was an error uploading your file.");
}
}
}
$_SESSION['error_array'] = $error_array;
$_SESSION['upload_array'] = $upload_array;
$_SESSION['eupload_array'] = $eupload_array;
header("Location:add_picture.php");
exit;
}
if( isset($_SESSION['postdata'])) {
$error_array = $_SESSION['error_array'];
$upload_array = $_SESSION['upload_array'];
$eupload_array = $_SESSION['eupload_array'];
unset($_SESSION['postdata']);
unset($_SESSION['error_array']);
unset($_SESSION['upload_array']);
unset($_SESSION['eupload_array']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel='stylesheet' href='../assets/style.css'/>
<title>CMS TEST</title>
</head>
<body>
<div class='container'>
<a href='add_picture.php' id='logo'><h2>Add Picture</h2></a>
<br/>
<small class='test_warning' style='color:#B83333'>
❶ Images should be JPG, JPEG, PNG or GIF format extentions. <br/>
❷ Images should not be above 500KB size.<br/>
❸ Please try to rename images before uploading for easier use.
</small> <br/><br/>
<form action='add_picture.php' method="post" enctype="multipart/form-data">
<input type="file" name="image[]" id="image" class="custom-file-input" multiple required/><br/><br/>
<input type="submit" value="Upload" name="submit_pic"/>
</form>
<?php if (!empty($upload_array)) { ?>
<small style='color:#00FF00'>
<?php echo '<br/><br/>', implode("<br/>",$upload_array), '<br/>'; ?>
</small>
<?php }?>
<?php if (!empty($eupload_array)) { ?>
<small style='color:#aa0000'>
<?php echo '<br/><br/>', implode("<br/>",$eupload_array), '<br/>'; ?>
</small>
<?php }?>
<?php if (!empty($error_array)) { ?>
<small style='color:#aa0000'>
<?php echo implode("<br/>",$error_array), '<br/>'; ?>
</small>
<?php }?>
<br/><br/>
<a href='index.php'>← Back</a>
<br/>
</div>
<a class='logout' href='logout.php'>Logout</a>
</body>
</html>
<?php
} else {
header('Location:index.php');
}
?>
When uploading images from my website into the designated folder I can see the file in the directory, but cannot open the files nor display them on the webpage.
EDIT This is an issue with my permissions, when trying to open the file in various programs I am receiving permission denied errors.
include('header.php');
$message = "";
$user_id=$_SESSION['user']['user_id'];
$images = getImageCount($user_id);
if(!isset($_SESSION['user']))
{
$_SESSION['message'] = "You must be logged in to manage your images";
header("Location:login.php");
}else if($_SESSION['user']['type'] == INCOMPLETE_USER)
{
$_SESSION['message'] = "You must create a profile to upload images";
header("Location:create_profile.php");
}else if($_SESSION['user']['type'] == DISABLED_CLIENT)
{
$_SESSION['message'] = "Your profile has been disabled";
header("Location:login.php");
}else if($_SERVER['REQUEST_METHOD'] == 'POST')
{
print_r($_FILES);
$user_folder="./profiles/". $user_id;
echo "test";
$file=$_FILES['uploadfile'];
//go to the profile table an SELEECT images FROM profiles WHERE user_id =
if ($images <= MAXIMUM_IMAGES)
{
if ($file['error']!=0)
{
$_SESSION['message']= "Upload Failed!";
}
else if ($_FILES['uploadfile']['type'] != "image/pjpeg" && $_FILES['uploadfile']['type'] != "image/jpeg")
{
$message = "Error! image file must be a'". DEFAULT_FILE_TYPE."'";
}
else if ($file['size'] > MAX_FILE_SIZE)
{
$message = "Error! File must be smaller than '".MAX_FILE_SIZE."' bytes";
}
else
{
$directory = "./profiles/".$user_id;
echo $directory;
//echo $user_folder;
if (!is_dir("profiles/".$user_id))
{
mkdir("profiles/".$user_id, intval( 0777, 8 ), true);
echo 2;
}
$temp_name=$file["tmp_name"];
$new_count = $images + 1;
$file_name=$user_id."_".$new_count;
echo $file_name;
$full_file_name ="profiles/".$user_id."/".$file_name. ".jpg";
move_uploaded_file($temp_name ,$full_file_name);
pg_execute($conn,"update_images",array ($new_count,$_SESSION['user']['user_id']));
}
}
else
{
$message = "Error! no more than " .MAXIMUM_IMAGES . "picture can be uploaded";
}
}
else if (!empty($_POST['submit_changes']))
{
echo "Fail";
$images= $_SESSION['profile']['images'];
}
?>
<form id="uploadform" enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php echo $message; ?>
<strong>Select image for upload: </strong>
<input name="uploadfile" type="file" id="uploadfile" />
<input type="submit" value="Upload New Image" />
<img src="profiles/sault/saultl_4.jpg" alt = "Sault"/>
</form>
<?php
include('footer.php');
?>
I think you did not set the right permission to the folder, just try it in this way:
if (!is_dir("profiles/".$user_id))
{
mkdir("profiles/".$user_id, intval( 0777, 8 ), true);
}
If this do not work we would need some more detailed information in order to help you!
So I looked almost every question and tried to work to show my image using the php script below. But it doesn't work. I also tried to see if GD library is enabled with PHPInfo() and it is working as well. I am very new to PHP but can't seem to get this working. Thanks for your help!
EDIT: I get a broken image icon after I click on upload a doc button.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_FILES['photo'])
&& is_uploaded_file($_FILES['photo']['tmp_name'])
&& $_FILES['photo']['error'] == UPLOAD_ERR_OK) {
foreach ($_FILES['photo'] as $key => $value) {
echo "$key : $value<br />";
}
if($_FILES['photo']['type'] == 'image/jpeg') {
$tmp_img = $_FILES['photo']['tmp_name'];
$image = imagecreatefromjpeg($tmp_img);
header('Content-Type: image/jpeg');
imagejpeg($image,NULL);
imagedestroy($image);
} else {
echo "Uploaded file ewas not a jpg image.";
}
echo "no photo uploaded.";
}
}
?>
<form enctype="multipart/form-data" action="book.php" method="post">
<input type="file" name="photo">
<input type="submit" value="upload a doc">
</form>
You can try add die(); after imagedestroy($image); to prevent any other output except image data. Also change imagejpeg($image,NULL); to imagejpeg($image);.
You cannot access to image direcly with tmp_name. Firstly you should save the image to the server and after that you can use with imagecreatefromjpeg
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_FILES['photo'])
&& is_uploaded_file($_FILES['photo']['tmp_name'])
&& $_FILES['photo']['error'] == UPLOAD_ERR_OK) {
if($_FILES['photo']['type'] == 'image/jpeg') {
$tmp_img = $_FILES['photo']['tmp_name'];
$uniq_name = uniqid().".".explode(".",$tmp_img)[1];
move_uploaded_file($_FILES['photo']['tmp_name'],$uniq_name);
$image = imagecreatefromjpeg($uniq_name);
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
} else {
echo "Uploaded file ewas not a jpg image.";
}
echo "no photo uploaded.";
}
}
?>
<form enctype="multipart/form-data" action="book.php" method="post">
<input type="file" name="photo">
<input type="submit" value="upload a doc">
</form>
I think the problem lies with the echo and the output strings after the PHP section (HTML code). Remove the foreach loop and output HTML only if it is a new page or if something is wrong.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_FILES['photo'])
&& is_uploaded_file($_FILES['photo']['tmp_name'])
&& $_FILES['photo']['error'] == UPLOAD_ERR_OK) {
if($_FILES['photo']['type'] == 'image/jpeg') {
$tmp_img = $_FILES['photo']['tmp_name'];
$image = imagecreatefromjpeg($tmp_img);
header('Content-Type: image/jpeg');
imagejpeg($image,NULL);
imagedestroy($image);
exit; // Add this to stop the program here.
} else {
echo "Uploaded file was not a jpg image.";
}
} else {
echo 'No file was sent.';
}
}
?>
<form enctype="multipart/form-data" action="book.php" method="post">
<input type="file" name="photo">
<input type="submit" value="upload a doc">
</form>
And one other thing, if you code using Notepad, be sure that there are no hidden characters at the beginning of your file.
I'm sure there is a simple solution that I just can't see.
I have a form for uploading stuff.
When the script completes it uses Header('Location: admin.php?success') and a if($_GET['success']) { echo WOOHOO SUCCESS } type message before the rest of the script is run.
The problem with this is that is you want to upload 2 files at once you can't because the first part of the script is executed and nothing else. I then considered using a boolean value to set true or false and display a message from that but that also failed.
I'd like to be able to upload several files in succession and receive a success message for each one.
Many thanks.
relevant PHP:
if(isset($_GET['success']) && empty($_GET['success'])){
echo '<h2>File Upload Successful! Whoop!</h2>';
} else{
if(empty($_POST) === false){
//check that a file has been uploaded
if(isset($_FILES['myTrainingFile']) && !empty($_FILES['myTrainingFile']['tmp_name'])){
file stuff...
if(in_array($fileExt, $blacklist) === true){
$errors[] = "File type not allowed";
}
}
if(empty($errors) === true){
//run update
move file stuff...
}
}
$comments = htmlentities(trim($_POST['comments']));
$category = htmlentities(trim($_POST['category']));
$training->uploadDocument($fileName, $category, $comments);
header('Location: admin.php?success');
exit();
} else if (empty($errors) === false) {
//header('Location: messageUser.php?msg=' .implode($errors));
echo '<p>' . implode('</p><p>', $errors) . '</p>';
}}
}
?>
You need to loop through the $_FILES super-global array and then upload each file.
Here's a working example to give you a better idea.
<?php
$upload_dir= './uploads';
$num_uploads = 2;
$max_file_size = 51200;
$ini_max = str_replace('M', '', ini_get('upload_max_filesize'));
$upload_max = $ini_max * 1024;
$msg = 'Please select files for uploading';
$messages = array();
if(isset($_FILES['userfile']['tmp_name']))
{
for($i=0; $i < count($_FILES['userfile']['tmp_name']);$i++)
{
if(!is_uploaded_file($_FILES['userfile']['tmp_name'][$i]))
{
$messages[] = 'No file uploaded';
}
elseif($_FILES['userfile']['size'][$i] > $upload_max)
{
$messages[] = "File size exceeds $upload_max php.ini limit";
}
elseif($_FILES['userfile']['size'][$i] > $max_file_size)
{
$messages[] = "File size exceeds $max_file_size limit";
}
else
{
if(#copy($_FILES['userfile']['tmp_name'][$i],$upload_dir.'/'.$_FILES['userfile']['name'][$i]))
{
$messages[] = $_FILES['userfile']['name'][$i].' uploaded';
}
else
{
$messages[] = 'Uploading '.$_FILES['userfile']['name'][$i].' Failed';
}
}
}
}
?>
<html>
<head>
<title>Multiple File Upload</title>
</head>
<body>
<h3><?php echo $msg; ?></h3>
<p>
<?php
if(sizeof($messages) != 0)
{
foreach($messages as $err)
{
echo $err.'<br />';
}
}
?>
</p>
<form enctype="multipart/form-data" action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" />
<?php
$num = 0;
while($num < $num_uploads)
{
echo '<div><input name="userfile[]" type="file" /></div>';
$num++;
}
?>
<input type="submit" value="Upload" />
</form>
</body>
</html>
Hope this helps!
I use the Following code to upload a single file .With This code I can Upload a single file to the database .I want to make multiple files uploaded by selecting multiple files in a single input type file.What Changes should i make in the code to make it upload multiple files?
<?PHP
INCLUDE ("DB_Config.php");
$id=$_POST['id'];
$fileTypes = array('txt','doc','docx','ppt','pptx','pdf');
$fileParts = pathinfo($_FILES['uploaded_file']['name']);
if(in_array($fileParts['extension'],$fileTypes))
{
$filename = $_FILES["uploaded_file"]["name"];
$location = "E:\\test_TrainingMaterial/";
$file_size = $_FILES["uploaded_file"]["size"];
$path = $location . basename( $_FILES['uploaded_file']['name']);
if(file_exists($path))
{
echo "File Already Exists.<br/>";
echo "Please Rename and Try Again";
}
else
{
if($file_size < 209715200)
{
$move = move_uploaded_file( $_FILES["uploaded_file"]["tmp_name"], $location . $_FILES['uploaded_file']['name']);
$result = $mysqli->multi_query("call sp_upload_file('".$id."','" . $filename . "','".$path."')");
if ($result)
{
do {
if ($temp_resource = $mysqli->use_result())
{
while ($row = $temp_resource->fetch_array(MYSQLI_ASSOC)) {
array_push($rows, $row);
}
$temp_resource->free_result();
}
} while ($mysqli->next_result());
}
if($move)
{
echo "Successfully Uploaded";
}
else
{
echo "File not Moved";
}
}
else
{
echo "File Size Exceeded";
}
}
}
else
{
echo " Invalid File Type";
}
?>
The Html That is used is
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file" id="uploaded_file" style="color:black" /><br/>
</form>
Basically you need to add to input name [] brackets and attribute "multiple"
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file[]" multiple="true" id="uploaded_file" style="color:black" /><br/>
</form>
Now all uploaded file will be available via
$_FILES['uploaded_file']['name'][0]
$_FILES['uploaded_file']['name'][1]
and so on
More info at
http://www.php.net/manual/en/features.file-upload.multiple.php