How do I combine 2 .php file into one single function - php

I want to thank everyone for helping me get my sendmail.php and fileupload.php file working properly as individual function. Now I am trying to combine them into a single file so the form that will use them will perform both functions on SUBMIT.
This is what I have currently:
<?php
$project = $_REQUEST['project'] ;
$project_other = $_REQUEST['project_other'] ;
$quantity = $_REQUEST['quantity'] ;
$pages = $_REQUEST['pages'] ;
$color = $_REQUEST['color'] ;
$color_other = $_REQUEST['color_other'] ;
$size = $_REQUEST['size'] ;
$page_layout = $_REQUEST['page_layout'] ;
$stock = $_REQUEST['stock'] ;
$stock_other = $_REQUEST['stock_other'] ;
$paper_finish = $_REQUEST['paper_finish'] ;
$paper_finish_other = $_REQUEST['paper_finish_other'] ;
$typeset = $_REQUEST['typeset'] ;
$timeframe = $_REQUEST['timeframe'] ;
$budget = $_REQUEST['budget'] ;
$add_info = $_REQUEST['add_info'] ;
$name = $_REQUEST['name'] ;
$phone = $_REQUEST['phone'] ;
$email = $_REQUEST['email'] ;
$company = $_REQUEST['company'] ;
$proj_name = $_REQUEST['proj_name'] ;
$zip = $_REQUEST['zip'] ;
$upload = $_REQUEST['upload'] ;
if (!isset($_REQUEST['email'])) {
header( "Location: ../pages/quote/quote.html" );
}
if ( ereg( "[\r\n]", $name ) || ereg( "[\r\n]", $email ) ) {
header( "Location: ../pages/quote/quote_injection_error.html" );
}
elseif (empty($name) || empty($phone) || empty($email) || empty($company) || empty($proj_name) || empty($zip) || empty($project) || empty($quantity) || empty($color) || empty($size) || empty($timeframe) || empty($budget)) {
header( "Location: ../pages/quote/quote_content_error.html" );
}
else {
mail( "QUOTES#DOMAIN.com", "Request for Quote: $project",
"$add_info\n
What kind of project is this? $project\n
Name: $name\n
Name of Project: $proj_name\n
Company: $company\n
Telephone: $phone\n
E-mail Address: $email\n
ZIP code: $zip\n
Is there a file attachment/upload? $upload\n
What do you need a quote on? $project : $project_other\n
What quantity do you require? $quantity\n
If applicable, how many pages is each document? $pages\n
Full color or black and white? $color : $color_other\n
What size do you want your print project to be? $size\n
What type of page layout do you need for your project? $page_layout\n
What paper stock do you require? $stock : $stock_other\n
What paper finish do you require? $paper_finish : $paper_finish_other\n
Are your documents typeset? $typeset\n
When do you need this project completed by? $timeframe\n
What is your budget for this project? $budget\n
Additional information to help COMPANY prepare our quote for you? $add_info",
"From: $name <$email>" );
header( "Location: ../pages/quote/quote_thanks.html" );
}
if (isset($_POST['submit'])) {
// Configuration - Script Options
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension
$file_basename = substr($filename, 0, strripos($filename, '.')); // Get file name minus extension
$file_ext = substr($filename, strripos($filename, '.')); // Get file extension
$filesize = $_FILES['file']['size']; // Get file size
$allowed_file_types = array('.jpg','.jpeg','.gif','.bmp','.png','.pdf','.doc','.docx','.psd'); // These will be the types of files that are allowed to pass the upload validation
$file_counter = 1; // used to increment filename if name already exists
$company = $_REQUEST['company'];
$project = $_REQUEST['proj_name'];
// File renaming and upload functionality
if (in_array($file_ext,$allowed_file_types) && ($filesize < 10000001)) { // Checks to make sure uploaded file(s) is an allowed file type AND within the allowable file size (currently 10MB)
// Rename File
$newfilename = $company . '_' . $proj_name . '_' . $file_basename; // Rename file as (CompanyName_FileName_DateStamp)
// Loop until an available file name is found
while (file_exists( "file_uploads/" . $newfilename ))
$finalfilename = $newfilename . '_' . $file_counter++ . $file_ext; // This will be the File Name shown in the upload destination directory (currently the "file_uploads" directory)
if (file_exists("file_uploads/" . $finalfilename)) {
// file already exists error
echo "This file already exists. Please rename this file and upload again if necessary.";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "file_uploads/" . $finalfilename);
echo "File uploaded successfully.";
}
} elseif (empty($file_basename)) {
// file selection error
echo "Please select a file to upload.";
} elseif ($filesize > 10000000) {
//file size error
echo "The file you are trying to upload is too large. Files must be no larger than 10MB.";
} else {
// file type error
echo "The file you attempted to upload is not allowed. You can only upload the following types of files: .jpg, .jpeg, .gif, .bmp, .png, .pdf, .doc, .docx, and .psd.";
unlink($_FILES["file"]["tmp_name"]);
}
}
/*
must add page links for error and success messages:
// redirect to upload success url
header( "Location: http://www.example.com/thankyou.html" );
die();
*/
?>
The "sendmail" portion works and I get the answers to my form inputs emailed to me clearly and concisely. However, since I added the "file_upload" file into bottom of the sendmail.php with no changes to either (just cut and pasted in above the final closing php tag ?>), the file_upload and renaming functions do not work.
Can anyone point me in the right direction as to how to get this to work in a single file? I am less than new to php but any thoughts/assistance would be appreciated.

Your form obviously posts a submit value right? If not it will skip the file upload function.
<input type="hidden" name="submit" value="TRUE" />
Because you put this at the top of the file_upload portion of the script.
if (isset($_POST['submit']))
The other thing could be you moved the file_upload.php file from one directory to another and now when you call
file_exists( "file_uploads/" . $newfilename)
The directory can not be found and skips the function.
Last, are you missing a {} for the while loop? You said you copied 100% from another file. So im assuming it worked like this when it was on it's own?
while (file_exists( "file_uploads/" . $newfilename ))

Related

How To Get Video File Size?

I need to get this script to check if the uploaded file is a video file or not and whether the file size is too big or not over the limit. Therefore, need to replace the getimagesize with something else that gets the video file size. How can I accomplish this? Which function to use here? getvideosize function does not exist.
This is where I am stuck.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check whether the file was uploaded or not without any errors.
if(!isset($_FILES["id_verification_video_file"]) &&
$_FILES["id_verification_video_file"]["Error"] == 0)
{
$Errors = Array();
$Errors[] = "Error: " . $_FILES["id_verification_video_file"]
["ERROR"];
print_r($_FILES); ?><br><?php
print_r($_ERRORS);
exit();
}
else
{
//Feed Id Verification Video File Upload Directory path.
$directory_path = "uploads/videos/id_verifications/";
//Make Directory under $user in 'uploads/videos/id_verifications'
Folder.
if(!is_dir($directory_path . $user)) //IS THIS LINE CORRECT ?
{
$mode = "0777";
mkdir($directory_path . $user, "$mode", TRUE); //IS THIS LINE
CORRECT ?
}
//Grab Uploading File details.
$Errors = Array(); //SHOULD I KEEP THIS LINE OR NOT ?
$file_name = $_FILES["id_verification_video_file"]["name"];
$file_tmp = $_FILES["id_verification_video_file"]["tmp_name"];
$file_type = $_FILES["id_verification_video_file"]["type"];
$file_size = $_FILES["id_verification_video_file"]["size"];
$file_error = $_FILES['id_verification_video_file']['error'];
$file = $_FILES["id_verification_video_file"]["name"];
// in PHP 4, we can do:
$fhandle = finfo_open(FILEINFO_MIME);
$mime_type = finfo_file($fhandle,$file); // e.g. gives "video/mp4"
// in PHP 5, we can do:
$file_info = new finfo(FILEINFO_MIME); // object oriented approach!
$mime_type = $file_info->buffer(file_get_contents($file)); // e.g. gives
"video/mp4"
switch($mime_type) {
case "video/mp4":
// my actions go here...
}
// Let's assume that the name attribute of the file input field I have
used is "id_verification_video_file"
$tempFile = $_FILES['id_verification_video_file']['tmp_name']; // path of
the temp file created by PHP during upload. I MOST LIKELY GOT THIS LINE
WRONG AT THE END PART. HOW TO CORRECT THIS ?
$videoinfo_array = getimagesize($tempFile); // returns a false if not a
valid image file
if ($videoinfo_array !== false) {
$mime_type = $videoinfo_array['mime'];
switch($mime_type) {
case "video/mp4":
// your actions go here...
move_uploaded_file("$file_tmp", "$directory_path" . "$user/" .
"$file_name"); //IS THIS LINE CORRECT ?
//Notify user their Id Verification Video File was uploaded successfully.
echo "Your Video File \"$file_name\" has been uploaded successfully!";
exit();
}
}
else {
echo "This is not a valid video file";
}
}
}
?>
<form METHOD="POST" ACTION="" enctype="multipart/form-data">
<fieldset>
<p align="left"><h3><?php $site_name ?> ID Video Verification Form</h3></p>
<div class="form-group">
<p align="left"<label>Video File: </label>
<input type="file" name="id_verification_video_file"
id="id_verification_video_file" value="uploaded 'Id Verification Video
File.'"></p>
</div>
</fieldset>
<p align="left"><button type="submit" class="btn btn-default"
name="id_verification_video_file_submit">Submit!</button></p>
</form>
</body>
</html>
<?php
include 'footer_account.php'; //Required on all webpages of the Site.
?>
Best I done so far is above. I'd appreciate if you guys can add the correct lines where they should be and add comments so I can easily spot your changes and learn from the corrections.
EDIT:
Folks, I managed to fix a lot of things on my current update. But, one new problem. The move_uploaded_file() is failing. Why is that ? Do have a look. I actually wrote my questions to you in my code's comments in CAPITAL. If you could kindly answer these questions then I'd be grateful and hopefully we could close this thread as SOLVED asap.
<?php
//Required PHP Files.
include 'header_account.php'; //Required on all webpages of the Site.
?>
<?php
if (!$conn)
{
$error = mysqli_connect_error();
$errno = mysqli_connect_errno();
print "$errno: $error\n";
exit();
}
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check whether the file was uploaded or not without any errors.
if(!isset($_FILES["id_verification_video_file"]) &&
$_FILES["id_verification_video_file"]["Error"] == 0)
{
$Errors = Array();
$Errors[] = "Error: " . $_FILES["id_verification_video_file"]
["ERROR"];
print_r($_FILES); ?><br><?php
print_r($_ERRORS);
exit();
}
else
{
//Feed Id Verification Video File Upload Directory path.
$directory_path = "uploads/videos/id_verifications";
//Make Directory under $user in
'uploads/videos/id_verifications' Folder if it doesn't exist.
if(!is_dir("$directory_path/$user")) //IS THIS LINE CORRECT ?
{
$mode = "0777";
mkdir("$directory_path/$user", $mode, TRUE); //IS THIS
LINE CORRECT ?
}
//Grab Uploading File details.
$Errors = Array(); //SHOULD I KEEP THIS LINE OR NOT ?
$file_name = $_FILES["id_verification_video_file"]["name"];
$file_tmp = $_FILES["id_verification_video_file"]
["tmp_name"];
$file_type = $_FILES["id_verification_video_file"]["type"];
echo "File Type: $file_type<br>"; //Outputs: "". WHY $file_type SHOWS
BLANK VALUE WHEN UPLOADING VIDEO FILES ? WORKS WITH OTHER FILES, LIKE
JPEG.
$file_size = $_FILES["id_verification_video_file"]["size"];
$file_error = $_FILES['id_verification_video_file']['error'];
echo "File Name: $file_name<br>"; //Outputs: "id_check.mp4"
//Grab Uploading File Extension details.
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
echo "File Extension: $file_extension<br>"; //Outputs: "mp4"
if(file_exists($directory_path . "$user/" . $file_name))
//WHICH LINE IS CORRECT ? THIS ONE OR THE NEXT ONE ?
//if(file_exists($directory_path . $user . '/' . $file_name))
//WHICH LINE IS CORRECT ? THIS ONE OR THE PREVIOUS ONE ?
{
$Errors[] = "Error: You have already uploaded a video
file to verify your ID!";
exit();
}
else
{
//Feed allowed File Extensions List.
$allowed_file_extensions = array("video/mp4");
//Feed allowed File Size.
$max_file_size_allowed_in_bytes = 1024*1024*1; //Allowed
limit: 100MB.
$max_file_size_allowed_in_kilobytes = 1024*1;
$max_file_size_allowed_in_megabytes = 1;
$max_file_size_allowed =
"$max_file_size_allowed_in_bytes";
//Create a fileinfo respource.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
//Apply the fileinfo resource and the finfo_file()
function to the uploading given file.
$mime = finfo_file($finfo,$file_name);
//Close the fileinfo resource.
finfo_close($finfo); echo "Mime: $mime<br>"; //exit;
//Outputs: video/mp4
//Verify File Extension.
//if(!in_array($file_extension, $allowed_file_extensions))
die("Error 1: Select a valid video file format. Select an Mp4 file.");
//Verify MIME Type of the File.
if(!in_array($mime, $allowed_file_extensions)) die("Error 2:
Select a valid video file format. Select an Mp4 file.");
elseif(!in_array($file_type, $allowed_file_extensions))
die("Error 3: There was a problem uploading your file $file_name! Make
sure your file is an MP4 video file. You may try again."); //IS THIS LINE
CORRECT ?
//Verify File Size. Allowed Max Limit: 1MB.
if($file_size>$max_file_size_allowed) die("Error 4: Your
Video File Size is larger than the allowed limit of:
$max_file_size_allowed_in_megabytes.");
//Move uploaded File to newly created directory on the
server.
if(!move_uploaded_file($file_tmp,
"$directory_path/$user/$file_name")) die("Error 5: Your file failed to
upload! Try some other time.");
else
{
move_uploaded_file($file_tmp,
"$directory_path/$user/$file_name"); //WHY IS NOT THIS LINE OF CODE
MOVING THE FILE TO DESTINATION ?
//Notify user their Id Verification Video File was
uploaded successfully.
echo "Your Video File \"$file_name\" has been uploaded
successfully!";
exit();
}
}
}
}
?>
<form METHOD="POST" ACTION="" enctype="multipart/form-data">
<fieldset>
<p align="left"><h3><?php $site_name ?> ID Video Verification Form</h3>
</p>
<div class="form-group">
<p align="left"<label>Video File: </label>
<input type="file" name="id_verification_video_file"
id="id_verification_video_file" value="uploaded 'Id Verification Video
File.'"></p>
</div>
</fieldset>
<p align="left"><button type="submit" class="btn btn-default"
name="id_verification_video_file_submit">Submit!</button></p>
</form>
</body>
</html>
<?php
include 'footer_account.php'; //Required on all webpages of the Site.
?>
I get echoed when trying to upload an mp4 file:
Error 3: There was a problem uploading your file id_check.mp4! Make sure your file is an MP4 video file. You may try again.
Should I set the folder permissions to 0644 from 0777 ? I am being told I should not allow any files to be executable in the folder by users (file uploaders) and so I should set it to readable & writeable only to "0644". I need your expert opinion on this.

simple upload form & double extension

I made a simple upload form, but when I try to upload something, the name of the file changes (ex : photo.jpg >> photo.jpg.jpg - double extension).
My code:
$place = realpath($_SERVER["PHP_SELF"]);
$name = $place.$_FILES['file']['name'];
$f1 = strchr($name,'.');
$f2 = strtolower($f1);
$name = $place.$name.$f2;
if ($_POST['up']) {
if (file_exists($name)) {
echo '[-] The File Already Exist ! ';
} else {
$upload = move_uploaded_file($_FILES['file']['tmp_name'],$name);
}
if (isset($upload)) {
echo '[+] The File "'.$_FILES['file']['name'].'" uploaded succsessfully';
}
}
This is because how you create the $name variable.
You first create $name = $place.$_FILES['file']['name']; Where $_FILES['file']['name'] is the full name of the file. With the extension.
After that you say that $name is the path (which makes no logic) and you add the full name of the file and the extension again. Just remove the second $name = $place.$name.$f2;

Make all uploaded files force download in php

I found a simple script on internet on how to upload files in php.
<?php
require 'config.php';
if (isset ( $_SERVER ['REQUEST_METHOD'] ) == 'POST') {
// when submit button is clicked
if (isset ( $_POST ['submit'] )) {
// get user's data
$name = $_POST ['name'];
$email = $_POST ['email'];
$images = "";
// check if user has added images
if(strlen(($_FILES ['upload'] ['tmp_name'] [0])) != 0){
$upload_dir = "images/";
// move all uploaded images in directory
for ($i = 0; $i < count($_FILES['upload']['name']); $i++) {
$ext = substr(strrchr($_FILES['upload']['name'][$i], "."), 1);
// generate a random new file name to avoid name conflict
$fPath = md5(rand() * time()) . ".$ext";
$images .= $fPath.";";
$result = move_uploaded_file($_FILES['upload']['tmp_name'][$i], $upload_dir . $fPath);
}
}else {
// if user doesn't have any images, add default value
$images .= "no images";
}
// write the user's data in database
// prepare the query
$query = "INSERT INTO users(name, email,images) VALUES
('$name', '$email','$images')";
// TODO check if the user's informations are successfully added
// in the database
$result = mysql_query ( $query );
}
}
?>
This script does a really good job overall but the only problem is that when I upload image files or pdf they open up in a new tab, they do not download. How do I make the uploaded image files automatically download when the download link is clicked on? Thanks in advance.
Add the download link as follows
<a href="link/to/your/download/image" download>Download link</a>
Add the following code in apache config
<Location "/images">
<Files *.*>
ForceType application/octet-stream
Header set Content-Disposition attachment
</Files>
</Location>

My uploadform page is not redirecting to the thank-you.php page after upload

Hi My uploadform page is not redirecting to the thank-you.php page after upload. Everything is perfect i dont want to change the code, its just that the header is not directing the paege to go to thank-you.php.
Here is the code that posts the data.
<?php
$target = "Carpics";
//$target = $target . basename( $_FILES['photo']['name']);
ini_set('display_errors',1);
error_reporting(0);
$conn = mysql_connect("localhost","admin","");
if(!$conn)
{
echo mysql_error();
}
$db = mysql_select_db("upload",$conn);
if($db)
{ echo mysql_error();
}
$name = $_POST['name'];
$address = $_POST['address'];
$from_date = $_POST['from_date'];
$to_date = $_POST['to_date'];
$full_name = $_POST['full_name'];
$email = $_POST['email'];
$city = $_POST['city'];
$tel = $_POST['tel'];
$town = $_POST['town'];
$country = $_POST['country'];
$model = $_POST['model'];
$displacement = $_POST['displacement'];
$trans = $_POST['trans'];
$driver = $_POST['driver'];
$photopath1 = $target . basename( $_FILES['photo1']['name']);
$photopath2 = $target . basename( $_FILES['photo2']['name']);
$photopath3 = $target . basename( $_FILES['photo3']['name']);
$photopath4 = $target . basename( $_FILES['photo4']['name']);
for($i=1;$i<5;$i++){
if($i==1){
$target = $photopath1;
}elseif($i==2){
$target = $photopath2;
}elseif($i==3){
$target = $photopath3;
}elseif($i==4){
$target = $photopath4;
}
$photo = addslashes(file_get_contents($_FILES['photo'.$i]['tmp_name']));
$image = getimagesize($_FILES['photo'.$i]['tmp_name']);
$imgtype = $image['mime'];
if(move_uploaded_file($_FILES['photo'.$i]['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['photo'.$i]['name']);
}
else {
echo "Sorry, there was a problem uploading your file.";
}
}
if(!$insert = mysql_query("INSERT INTO data VALUES('','$name','$address','$from_date','$to_date','$full_name','$email','$city','$tel','$town','$country','$model','$displacement','$trans','$driver','$photo', '$photopath1', '$photopath2', '$photopath3', '$photopath4','$imgtype')"));
echo header('Location: thank-you.php');
?>
it instead displays this
The file img5.jpgThe file img7.jpgThe file Pontiac sports car.jpgThe file volkswagen-polo.jpg
Help please
I've noted the following while looking at your sample.
if(move_uploaded_file($_FILES['photo'.$i]['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['photo'.$i]['name']);
}
else {
echo "Sorry, there was a problem uploading your file.";
}
This happens before you attempt to perform a redirection, and Php.net states the following :
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called.
So that would be a possible cause, except that you also use the header function in the wrong way. You do not have to put an echo in front of it.
So instead of
echo header('Location: thank-you.php');
use
header('Location: thank-you.php');
That is the cause of it printing out the filenames, but not performing the redirection. Upon any output before the redirection, it cannot complete. As far as I recall, if you put error handling at 8191 you should be able to view it. (E_ALL)
Also, you're not escaping anything in the filename, username, etc, which gives the user room to either corrupt your database using funky characters, or even an SQL injection.
Take a look at mysql_real_escape_string and at the last note. This function doesn't escape certain wildcard characters, so take you might want to check on that as well when you're ready for that.
And read up at : Sanitizing user input

PHP dynamic zip file creation crashes with non-image filetypes. (wp)

I have a function that takes uploaded files (WORDPRESS) and adds them to a (newly created) zip file.
every new file is added to the zip (if is not yet created - the first file will create one ) and also to a comment with the list of the files.
function Ob99_generate_zip_file($meta) {
// we always need post_id , right ?
if( isset($_GET['post_id']) ) {
$post_id = $_GET['post_id'];
} elseif( isset($_POST['post_id']) ) {
$post_id = $_POST['post_id'];
}
//setting some more variables.
$file = wp_upload_dir();// take array
$file2 = wp_upload_dir();//debug
$zipname = $file['path'].'file.zip'; // set zip file name
$file = trailingslashit($file['basedir']).$meta['file'];// construct real path
// Without this next condition the function dies. WHY ??
list($orig_w, $orig_h, $orig_type) = #getimagesize($file); // not help to comment
if (!$orig_type == IMAGETYPE_GIF || !$orig_type == IMAGETYPE_PNG|| !$orig_type == IMAGETYPE_JPEG) {
//why other filetypes not working ??
return ;
}
$zip = new ZipArchive; // initiatte class
$zip->open($zipname , ZipArchive::CREATE); // open buffer
$new_filename = substr($file,strrpos($file,'/') + 1); //we do not need nested folders
$zip->addFile($file,$sitename.'/'.$new_filename); // we add the file to the zip
if (file_exists($zipname)){
$comment = $zip->getArchiveComment(); // if the file already exist read the comment
}
else { // if not - let´s give it a cool retro header
$comment_head = '*********************************'. PHP_EOL ;
$comment_head .= '****** <<< FILE CONTENT >>> *****'. PHP_EOL ;
$comment_head .= '*********************************'. PHP_EOL ;
}
$comment = $comment_head . $comment ;// add header before comment
$comment = $comment . PHP_EOL . PHP_EOL . $meta['file'] ; // add new file name
$zip->setArchiveComment($comment); // and comment
$zip->addFromString('filelist.txt', $comment); // create txt file with the same list
$zip->close()or die('can not create zip file'.$file.print_r($meta).'---- DEBUG SEPERATOR ---- '.print_r($file2)); // FINISHED or DIE with debug
}
My problem : if I try to upload any file other than an image - the function will DIE .
I have added a condition for checking imagetype - but I would like to know why it is crashing and how to make it work without said condition ...
Does the zip function have any problems with PDF , doc or anyother ? is that a wordpress problem ?
The problem section seems to be where you're asking PDFs, etc. their image size. Why don't you try:
$image_size = getimagesize($file);
if($image_size===false)
{
// This is not an image
// Do what you want to PDFs, etc.
}
else
{
// This is an image
// Find out image type, dimensions, etc.
}

Categories