Adding more file extensions to existing code - php

so I am editing some code that was already there and I can't figure how to add additional extensions to it so that files other than PDF can be uploaded, any clues? I would like to add jpeg, docx, doc, xls, and wps.
<?php
$lastname=$_POST['mylastname'];
$firstname=$_POST['myfirstname'];
$asuid=$_POST['#'];
$ftype=$_POST['ftype'];
$dkServerConn = mysql_connect("#", "#", "#") or die("no way");
mysql_select_db("#", $dkServerConn) or die("Cannot connect to the DB!");
$sql1 = "SELECT * FROM scholnumber";
$dkResultSet1 = mysql_query($sql1,$dkServerConn) or die(mysql_error());
$checkIt=0;
while ($dkROWrecord1 = mysql_fetch_array($dkResultSet1,MYSQL_BOTH))
{
$checkIt=$dkROWrecord1['filenumber'];
}
$checkIt2=$checkIt+1;
$sql2="Update scholnumber set filenumber='".$checkIt2."'";
$dkResultSet2 = mysql_query($sql2,$dkServerConn) or die(mysql_error());
echo "<html>
<head>
<title>Uploading Information</title>
<style> body { font-family:arial; font-size:14px } </style>
</head>
<body><table cellpadding='5' align='center' width='55%'><tr><td><p> </p>
<img src='#'><br />
<img src='#'><br />
<span style='font-family:arial;font-size:14pt'> 2013-2014 Privately Funded Scholarship Application</span>
<h3><br/>";
// File validation -->
$allowedExts = array("pdf","docx","doc","wps");
$extension = end(explode(".", $_FILES["file"]["name"]));
if (($_FILES["file"]["type"] == "application/pdf")
&& in_array($extension, $allowedExts)){
if ($_FILES["file"]["error"] > 0){
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else{
echo "<p />Submission successful.<p />
Your submission has been received. If you have loaded all of your documents, you can close this browser. Your scholarship application is complete.<p />";
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists. ";
}
else{
$ext = substr($_FILES['file']['name'], strpos($_FILES['file']['name'],'.'), strlen($_FILES['file']['name'])-1);
$docName = $checkIt.$ext;
move_uploaded_file($_FILES["file"]["tmp_name"],"upload/" . $docName);
// echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
elseif($_FILES["file"]["type"] == "application/pdf"){
}
else{
echo "<hr> <p /> >>>>>> INVALID FILE <<<<<<<< <p /> <p />";
}
// End of the validation
$sql3="insert into scholfile (filename, lastname, firstname, asuid, ftype) values ('$checkIt', '$lastname', '$firstname', '$asuid', '$ftype')";
$dkResultSet3 = mysql_query($sql3,$dkServerConn) or die(mysql_error());
$sql6="select * from scholarships where asuid='".$asuid."'";
$dkResultSet6 = mysql_query($sql6,$dkServerConn) or die(mysql_error());
while ($dkROWrecord6 = mysql_fetch_array($dkResultSet6,MYSQL_BOTH))
{
$email=$dkROWrecord6['email'];
}
$from="Scholarships";
$fromem="scholarships##.edu";
$subjectStudent = "Thank you for your supporting documentation.";
$messageStudent="Hello, ".$firstname. " -<p />
We have received your ".$ftype.". <p />
<hr />
If you have any questions, please contact the Financial Aid and Scholarships Office at 870-972-2310 or reply to this email.
<p />
Thank you for your submission.<br />Financial Aid and Scholarships Office";
//Email Information
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "To:" .$firstname. "<" . $email. ">\r\n";
$headers .= "From:" . $from . "<". $fromem . ">\r\n";
mail($email, $subjectStudent, $messageStudent, $headers);
?>
<p /> <p />
If you have another document to submit, please <a href='fileupload.php'>click here.</a><p />
Thank you!<p /></body></html>

I am not certain that my answer is correct because I haven't done this myself yet, but here is something for you to try. (Untested)
Your code restricts the file type for upload documents here:
if (($_FILES["file"]["type"] == "application/pdf") && in_array($extension, $allowedExts)){
Change the File Validation part of your code to:
// File validation -->
$allowedExts = array("pdf","docx","doc","wps","jpg"); //Added jpg
//Get Filename Extension into var (your code - unchanged)
$extension = end(explode(".", $_FILES["file"]["name"]));
//Create array of acceptable file types:
// Sources: (1) http://filext.com/file-extension/DOC and (2) http://php.net/manual/en/function.mime-content-type.php
$doctype = array("application/msword","application/doc","appl/text","application/vnd.msword","application/vnd.ms-word","application/winword","application/word","application/x-msw6","application/x-msword");
$xltype = array("application/vnd.ms-excel","application/msexcel","application/x-msexcel","application/x-ms-excel","application/vnd.ms-excel","application/x-excel","application/x-dos_ms_excel","application/xls");
$jpgtype = array("image/jpeg","image/jpg","image/jp_","application/jpg","application/x-jpg","image/pjpeg","image/pipeg","image/vnd.swiftview-jpeg","image/x-xbitmap");
$wpstype = array("application/vnd.ms-works","application/x-msworks-wp","zz-application/zz-winassoc-wps","text/plain");
//Combine them into one array:
$allowedFT = array_merge($doctype, $xltype, $jpgtype, $wpstype);
//Get this file's file type into var
$ft = $_FILES["file"]["type"];
//NOW DO THE BIG TEST
if (in_array($ft, $allowedFT) && in_array($extension, $allowedExts)){

I don't know about others but from my point of view, you code seems to only allow pdf uploads.
First I would add to the allowed extensions array:
$allowedExts = array("pdf","docx","doc","wps", "jpeg", "xls");
I would then change this line:
if (($_FILES["file"]["type"] == "application/pdf")
to:
$allowedMIMETypes = array(
"application/pdf", //for pdf
"application/vnd.openxmlformats-officedocument.wordprocessingml.document", //for docx
"application/msword", //for doc
"application/vnd.ms-works", //for wps, I think you should also paste the other in the link to
"image/jpeg", //for jpeg, again, there are other mime-types to add to
"application/excel", //for xls, again there are other mime-types to add from the sources
);
//then check if the type is in the array
if (in array($_FILES["file"]["type"],$allowedMIMETypes)) {
The sources for the file types:
http://hul.harvard.edu/ois/systems/wax/wax-public-help/mimetypes.htm
What is a correct mime type for docx, pptx etc?
http://lwp.interglacial.com/appc_01.htm
http://dotwhat.net/wps/32

Related

PHP image type application/png

For some reason the image type displays as "application/png" in IE 7 and Edge but "image/png" in Chrome and Firefox. I've tried several different images, jpegs do the same thing. Is this normal? Should I include an or statement to account for the "application/png"? Or am I doing something wrong?
if ((($screenshot_type == 'image/gif') || ($screenshot_type == 'image/jpeg') ||
($screenshot_type == 'image/pjpeg') || ($screenshot_type == 'image/png')) &&
(($screenshot_size > 0) && ($screenshot_size <= GW_MAXFILESIZE))) {
if ($_FILES['screenshot']['error'] == 0) {
// Move the file to the targe upload folder
$target = GW_UPLOADPATH . $screenshot;
if (move_uploaded_file($_FILES['screenshot']['tmp_name'], $target)) {
// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die('Unable to connect to databse');
// Write the data to the database
$query = "INSERT INTO guitarwars VALUES (0, NOW(), '$name', '$score', '$screenshot')";
mysqli_query($dbc, $query)
or die('Unable to complete query');
// Confirm success with the user
echo '<p>Thanks for adding your new high score!</p>';
echo '<p><strong>Name:</strong> ' . $name . '<br>';
echo '<strong>Score:</strong> ' . $score . '</p>';
echo '<img src="' . GW_UPLOADPATH . $screenshot . '" alt="Score image" /></p>';
echo '<p><< Back to high scores</p>';
// Clear the score data to clear the form
$name = "";
$score = "";
$screenshot = "";
mysqli_close($dbc);
}
else {
echo '<p class="error">Sorry, there was a problem uploading your screen shot image.</p>';
}
}
}
else {
echo '<p class="error">The screen shot must be a GIF, JPEG, or PNG image file no ' .
'greater than ' . (GW_MAXFILESIZE / 1024) . ' KB in size.<br>' . $screenshot_size . '<br>' . $screenshot_type . '</p>';
}
Different browsers and operating systems supply different mime-types. You should perhaps instead just use http://php.net/getimagesize on the uploaded file, and switch on $getimagesizeresult[2] with cases for IMG_PNG, IMG_JPG, IMG_GIF and apply an appropriate mime type on your own.

Sending image attachment

I have a PHP form, i'm trying to send an image from it as an attachment. I already fixed few things in my code.
I'm not sure if it will send the image (because I had some problems with it)
The problem is that nothing is even shown in the page (when I the script below is ran) when I open it on the server as index.php not even the button
Here is the code:
<?php
include_once("functions.php");
// Process
$action = isset($_POST["action"]) ? $_POST["action"] : "";
if (empty($action))
{
// Send back the contact form HTML
$output = "<form action='#' style='display:none'>
<input type='file' id='image' name='image' maxlength=50>";
}
require("class.phpmailer.php");
$Email_to = "someone#gmail.com"; // the one that recieves the email
$email_from = "someone#someone.net";
$dir = "uploads/$filename";
chmod("uploads",0777);
function uploadImage($image)
{
if ((($_FILES["image"]["type"] == "image/gif")
|| ($_FILES["image"]["type"] == "image/jpeg")
|| ($_FILES["image"]["type"] == "image/pjpeg")
|| ($_FILES["image"]["type"] == "image/jpg")
|| ($_FILES["image"]["type"] == "image/png"))
&& ($_FILES["image"]["size"] < 2097152)
&& (strlen($_FILES["image"]["name"]) < 51))
{
if ($_FILES["image"]["error"] > 0)
{
echo "Return Code: " . $_FILES["image"]["error"];
}
else
{
echo "Upload: " . $_FILES["image"]["name"] . "<br />";
echo "Type: " . $_FILES["image"]["type"] . "<br />";
echo "Size: " . ($_FILES["image"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["image"]["tmp_name"] . "<br />";
if (file_exists("images/" . $_FILES["image"]["name"]))
{
echo $_FILES["image"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["image"]["tmp_name"],
"images/" . $_FILES["image"]["name"]);
}
}
}
else
{
echo "Invalid file";
}
$filename = $_FILES["image"]["type"];
$dir = "uploads/$filename";
chmod("uploads",0777);
$success = copy($_FILES[images][tmp_name], $dir);
if ($success)
{
echo " Files Uploaded Successfully<BR>";
SendIt();
}
}//end of upload func'
function SendIt() {
//
global $attachments,$Email_to,$Email_msg,$email_subject,$email_from;
$mail = new PHPMailer();
$mail->IsSMTP();// send via SMTP
$mail->Host = "localhost"; // SMTP servers
$mail->SMTPAuth = false; // turn on/off SMTP authentication
$mail->From = $email_from;
$mail->AddAddress($Email_to);
$mail->AddReplyTo($email_from);
$mail->WordWrap = 50;// set word wrap
//now Attach all files submitted
$mail->AddAttachment("uploads"."/".$_FILES["image"]["type"]);
$mail->IsHTML(false);// send as HTML
}
?>
Thank you in advance!
For problem 1:
Try to send a mail with that class without any variables put into it. So just make some procedural code sending a mail to your own address and see if it arrives.
For problem 2:
You are putting some text into $output but you are never outputting $output.

Sending an image as attachment in a php form [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
i have a php form, i'm trying to get an image from it as an attachment, i did some fixing to my code
1. i'm not sure if it will send the image (because i had some problams with it)..
2. the problam is that noting is even shown in the page when i open it in the server as index.php
not even the button...
here is the code:
<?php
include_once("functions.php");
// Process
$action = isset($_POST["action"]) ? $_POST["action"] : "";
if (empty($action))
{
// Send back the contact form HTML
$output = "<form action='#' style='display:none'>
<input type='file' id='image' name='image' maxlength=50>";
}
require("class.phpmailer.php");
$Email_to = "someone#gmail.com"; // the one that recieves the email
$email_from = "someone#someone.net";
$dir = "uploads/$filename";
chmod("uploads",0777);
function uploadImage($image)
{
if ((($_FILES["image"]["type"] == "image/gif")
|| ($_FILES["image"]["type"] == "image/jpeg")
|| ($_FILES["image"]["type"] == "image/pjpeg")
|| ($_FILES["image"]["type"] == "image/jpg")
|| ($_FILES["image"]["type"] == "image/png"))
&& ($_FILES["image"]["size"] < 2097152)
&& (strlen($_FILES["image"]["name"]) < 51))
{
if ($_FILES["image"]["error"] > 0)
{
echo "Return Code: " . $_FILES["image"]["error"];
}
else
{
echo "Upload: " . $_FILES["image"]["name"] . "<br />";
echo "Type: " . $_FILES["image"]["type"] . "<br />";
echo "Size: " . ($_FILES["image"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["image"]["tmp_name"] . "<br />";
if (file_exists("images/" . $_FILES["image"]["name"]))
{
echo $_FILES["image"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["image"]["tmp_name"],
"images/" . $_FILES["image"]["name"]);
}
}
}
else
{
echo "Invalid file";
}
$filename = $_FILES["image"]["type"];
$dir = "uploads/$filename";
chmod("uploads",0777);
$success = copy($_FILES[images][tmp_name], $dir);
if ($success)
{
echo " Files Uploaded Successfully<BR>";
SendIt();
}
}//end of upload func'
function SendIt() {
//
global $attachments,$Email_to,$Email_msg,$email_subject,$email_from;
$mail = new PHPMailer();
$mail->IsSMTP();// send via SMTP
$mail->Host = "localhost"; // SMTP servers
$mail->SMTPAuth = false; // turn on/off SMTP authentication
$mail->From = $email_from;
$mail->AddAddress($Email_to);
$mail->AddReplyTo($email_from);
$mail->WordWrap = 50;// set word wrap
//now Attach all files submitted
$mail->AddAttachment("uploads"."/".$_FILES["image"]["type"]);
$mail->IsHTML(false);// send as HTML
}
?>
Thank you in advance!
To join an image to an e-mail, you need to create a MIME e-mail, a simple mail() won't suffice. Gazillions of modules handle that, but PEAR's Mail_Mime would typically be already available in your environment.

PHP / HTML uploading script not working right

I'm pretty new in PHP (don't have much HTML experience, too) and I have a question. I have a file upload system which consists of two PHP scripts (see below). In the file upload form a user selects file, saving folder and then uploads. Saving location can be chosen from a drop-down menu which consists of folders in uploading directory. But there's another option in the drop-down menu. If the user chooses the option other then a new field comes up (it's done by JavaScript) and the user can insert location manually (for example, a directory doesn't exist and the user wants to make a new one).
But here's a problem: if the user chooses a folder which is predefined everything is OK, but if the user writes a directory name to the field then only folder called folder will be created. For example, if the user wants to upload a picture about a flower and no folder called flower exists then the user chooses other and writes flower into the box. Then upload button is clicked and basically PHP should make a new folder called flower and upload the picture there. But at the moment, PHP makes a folder called folder and for some reason the picture is not uploaded there (it's uploaded nowhere).
My problems with the script:
A new folder won't be created. I think it's because I have two values called "folder" but I don't know how to get it work that if "other" is selected then PHP only looks the last value.
Even if the folder is created then a file won't be uploaded there for some reason.
I would be really grateful if anyone finds the solution for my problem and helps me to fix it. And don't hesitate to ask for extra information because my English isn't the best and because of this some things can't be understood.
Thanks in advance!
1st file: file-upload.php:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title></title>
<script language="JavaScript" type="text/javascript">
<!--
function Toggle(obj){
var val=obj.value;
if (!obj.m){ obj.m=''; }
if (!obj.m.match(val)){ obj.m+=','+val+','; }
var hide=obj.m.split(',');
for (var zxc0=0;zxc0<hide.length;zxc0++){
if (document.getElementById(hide[zxc0])){
document.getElementById(hide[zxc0]).style.display='none';
}
}
var show=val.split(',');
for (var zxc1=0;zxc1<show.length;zxc1++){
if (document.getElementById(show[zxc1])){
document.getElementById(show[zxc1]).style.display='';
}
}
}
//-->
</script>
</head>
<body>
<h1>Upload</h1>
<form action="upload.php" method="post"
enctype="multipart/form-data"><br>
<label for="file">File:</label>
<input type="file" name="file" id="file" />
<br>
Tüüp: <select name="folder" value="folder" onchange="Toggle(this);">
<?php
foreach(glob('/uploadfolder/*', GLOB_ONLYDIR) as $dir)
{
$dir = basename($dir);
echo '<option value="', $dir, '">', $dir, '</option>';
}
?>
<option value="folder">other</option>
</select><br>
<input id="folder" value="Create a new folder" style="display:none;">
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>
2nd file: upload.php:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title></title>
</head>
<body>
<h1>Upload</h1>
<br>
<?php
$dirname = $folder = $_POST["folder"];
$filename = "/uploadfolder/" . "$dirname" . "/";
if (!file_exists($filename)) {
mkdir("/uploadfolder/" . "$dirname", 0777);
}
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "application/vnd.openxmlformats- officedocument.spreadsheetml.sheet"))
&& ($_FILES["file"]["size"] < 5120000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Name: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Tmp. file: " . $_FILES["file"]["tmp_name"] . "<br />";
echo "Folder: " . $folder . "<br />";
if (file_exists("/uploadfolder/$folder/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"/uploadfolder/$folder/" . $_FILES["file"]["name"]);
echo "Saved: " . "" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Upload failed";
}
?>
</body>
</html>
Do the Following Steps
In file-upload.php, add a name attribute to the text field for the new folder name . Let it be like this,
<input id="folder" value="Create a new folder" name="newfolder" style="display:none;">
Now in the upload.php file make changes as below,
$dirname = $_POST["folder"];
$filename = ("./uploadfolder/" . "$dirname" . "/");
if($dirname=="folder"){$dirname=$_POST["newfolder"];}
if (!file_exists($filename)) {
mkdir("./uploadfolder/" . "$dirname", 0777);
}
Use $dirname as the folder name through out. So replace $folder with $dirname
Another thing is, if upload is still not working fine, just use "./uploadfolder/$folder/" as base path. Also Give 777 permissions to your workspace. You may use the following command,
chmod -R 777 <path_to_uploadfolder>
As mentioned by other SOF users, remove exit; from the file exist check in the beginning.
Hope you have the answer ! :)
at the moment PHP makes a folder called "folder" and for some reason the picture IS NOT even uploaded there
That's because you have an exit; in the following excerpt from the second file:
<?php
$dirname = $_POST["folder"];
$filename = ("/uploadfolder/" . "$dirname" . "/");
if (!file_exists($filename)) {
mkdir("/uploadfolder/" . "$dirname", 0777);
exit;
} else {
}
?>
As a result, the script quits as soon as the folder is created.
There are multiple security problems with your script but I won't bother getting into them because this is not the place for security lessons :)
The line exit after the mkdir will cause the script to stop executing. If you want to create the folder then continue on to the file upload, you need to remove the exit statement. You can also remove the else portion of that if, since it's empty ...
$dirname = $folder = $_POST["folder"];
$filename = "/uploadfolder/" . "$dirname" . "/";
if (!file_exists($filename)) {
mkdir("/uploadfolder/" . "$dirname", 0777);
}
if ((($_FILES["file"]["type"] == "image/gif")
...

How to store photo upload in a PHP session?

I've built this webform wizard, consisting of several PHP pages. In this several pages users can fill in the form and the data gets temporarily stored in a session and at the last page the sessions are used to store all the data in the MYSQL database. Everything works fine with the exception of the uploaded file. Here is my code:
HTML: wizard_page2
<form name="registratieformulier" method="post" enctype="multipart/form-data" action="sw3.php">
<tr><td>Foto winkel uploaden: </td><td><input type="file" name="uploadfoto"/></td></tr><br /><br />
<tr><td><strong>Omschrijving van winkel:</strong></td> </tr><br />
<tr><textarea cols="50" rows="7" name="omschrijvingwinkel"></textarea></tr>
<input name="pkbedrijven" value="<?php echo($pkbedrijven); ?>" type="hidden" />
<input type="submit" name="stuurfoto" value="Verzenden" />
</form>
PHP: wizard_last_page
$_FILES['uploadfoto']['name'] = $_SESSION["naamfoto"];
$_FILES['uploadfoto']['tmp_name'] = $_SESSION["tijdelijk"];
$bn = $_SESSION["wn"];
$target_path = "../../winkels/$bn/";
$target_path = $target_path . basename( $_FILES['uploadfoto']['name']);
move_uploaded_file($_FILES['uploadfoto']['tmp_name'], $target_path)or die("There was an error uploading the file, please try again!");
$foto_path = "http://mywebsite.nl/winkels/$bn/".basename($_FILES['uploadfoto']['name']);
$omschrijving = $_SESSION["omschrijving"];
$add = "UPDATE winkelprofiel SET winkelomschrijving='$omschrijving', winkelfoto='$foto_path' WHERE fkBedrijvenID=$pkbedrijven ";
$query_upload = mysql_query($add) or die("De winkelfoto en omschrijving konden niet worden opgeslagen");
The $_FILES array only holds information about the file that has been uploaded in this request. If you do not save that file elsewhere within the same request, it will be removed by PHP at the end of the request. You cannot simply save $_FILES['uploadfoto']['tmp_name'] into the session and expect the file to still be there later, because it won't be. There's also no point in assigning the values in $_SESSION back into $_FILES, it won't bring the file back.
What you need to do:
if the upload was successful, move $_FILES['uploadfoto']['tmp_name'] somewhere else immediately
save the location you have moved it to into $_SESSION
do something with that file in $_SESSION at the end of your multi-page process (no need for $_FILES anymore at all)
have some mechanism in place to remove old uploaded files, in case the user abandons the session and the file never gets used
I think that the problem is, the file located at $_FILES['uploadfoto']['tmp_name'] will only be available when it is uploaded. Even you store the value in session, the file won't be there when you come to wizard_last_page. You need to handle uploaded files right away in the POST request.
So you need to move the file to $target_path or any certain temporary place when it's uploaded, then store the $target_path in the session so you can access to the file later on wizard_last_page.
Well, you can upload the file in one temporary location first. Then on the last page, once you submit the form, you can transfer the file to the desired location and then delete the temporary one.
$_SESSION['file'] = $_FILES["file"]["name"];
if (file_exists("uploads/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],"uploads/temp/" . $_FILES["file"]["name"]);
};
//This for the last page.
$file = file_get_contents("uploads/temp/".$_SESSION['file']);
file_put_contents("uploads/".$_SESSION['file'], $file);
I disagree with the accepted answer. There is a way to store all the images in the session array variable. You can use the "file_get_contents" function for storing the image.
Have a look at this:
$_SESSION['imgArrayFile'][] = $_FILES['file']; //Your file informations
$_SESSION['imgArrayName'][] = $_POST["ImgNewNamePlacowki"]; //new name for img
$_SESSION['ImgArrayAlt'][] = $_POST["ImgAltPlacowki"]; // alt tags if you use them
$_SESSION['obj_image_session'][] = file_get_contents($_FILES['file']['tmp_name']);
//above "file_get_contents" function - store image as a long string.
Regardless of what other think about using it for this purpose it can do the job for you.
There are several issues with storing large amounts of data in a session but if you images are small enough and you are aware of your settings limitation, then you will be just fine.
Save your file with
$file= $destination."/".$filename; //images/new.jpg
$fp=fopen($file,"w");
fwrite($fp,$_SESSION['obj_image_session'][$index]);
EXAMPLE FROM MY (WORKING) PROJECT:
<?php
//$galery_img_folder = "your/new/image/destination";
foreach($_SESSION['imgArrayFile'] as $index => $name){
if($_SESSION['imgArrayName'][$index]!=""
&& $_SESSION['ImgArrayAlt'][$index]!=""
&& $_SESSION['obj_image_session'][$index]!=""
){
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_SESSION['imgArrayFile'][$index]["name"]);
$extension = end($temp);
if ((($_SESSION['imgArrayFile'][$index]["type"] == "image/gif")
|| ($_SESSION['imgArrayFile'][$index]["type"] == "image/jpeg")
|| ($_SESSION['imgArrayFile'][$index]["type"] == "image/jpg")
|| ($_SESSION['imgArrayFile'][$index]["type"] == "image/pjpeg")
|| ($_SESSION['imgArrayFile'][$index]["type"] == "image/x-png")
|| ($_SESSION['imgArrayFile'][$index]["type"] == "image/png"))
&& ($_SESSION['imgArrayFile'][$index]["size"] < 104857600)
&& in_array($extension, $allowedExts))
{
if(isset($_SESSION['imgArrayName'][$index]) && $_SESSION['imgArrayName'][$index]!=""){
$rename = $_SESSION['imgArrayName'][$index];
$rename = $rename.".".end($temp);
}
if ($_SESSION['imgArrayFile'][$index]["error"] > 0)
{
echo "Return Error Code: " . $_SESSION['imgArrayFile'][$index]["error"] . "<br>";
}
else
{
$size = display_filesize($_SESSION['imgArrayFile'][$index]["size"]);
echo "Upload: " . $_SESSION['imgArrayFile'][$index]["name"] . "<br>";
echo "Type: " . $_SESSION['imgArrayFile'][$index]["type"] . "<br>";
echo "Size: " . ($size) . "<br>";
echo "Temp file: " . $_SESSION['imgArrayFile'][$index]["tmp_name"] . "<br>";
if (file_exists($galery_img_folder."/".$rename))
{
$error[] = ''.$rename.' <span class="error" id="error"> this name exsists </span>';
}
else
{
$_FILES["file"]["tmp_name"]=$_SESSION['imgArrayFile'][$index]["tmp_name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $galery_img_folder."/".$rename);
//now make use of the file_get_content variables
$file= $galery_img_folder."/".$rename;
$fp=fopen($file,"w");
fwrite($fp,$_SESSION['obj_image_session'][$index]);
}
}
}
}
else
{
$error[] = '<span class="error" id="error"> Niewłaściwy plik </span>';
$maxsixe = display_filesize(104857600);
echo "Size: " . ($maxsixe) . "<br>";
}
}
}//end foreach ! ! !
}//end dodawanie zdjecia
?>
Of course you will have to make some small modifications to make it work with your project, but my point was to show you that it's possible.
Have a great day and happy coding !

Categories