How to set the destination folder when copying PHP - php

Hi guys pretty new to PHP been trying to put together an app using copy and paste of code (dont hate me) and tailoring it to suit my need but I have hit a wall. Problem with doing things this way is its hard to get full understanding. Here is the issue. I am copying a file from one directory to another renaming it in the process. However I want to actually copy a file from source (which is fine) and then put it in a folder called users. Tried a few different options and just getting errors. Any help appreciated.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>User registration</title>
</head>
<body>
<?php
require_once('config.php'); // include config file
require_once('function.php'); // include copy file that have copy function.
?>
<div class="center">
<h1>Please Enter the details shown below..</h1>
<form action="index.php?action=submit" method="post">
<table class="table" align="center">
<tr>
<td>User Name:</td>
<td><input type="text" name="uname" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="pwd" /></td>
</tr>
<tr>
<td>Click on Submit..</td>
<td><input type="submit" value="Submit" name="action"/></td>
</tr>
</table>
</form>
</div>
<?php
if($_POST["action"]=='') // check for parameter if action=submit or not if it is blank then show this message
{
echo "Please fill 'User Name' and 'Password' above!";
}
else{
if($_POST["uname"]==''){ // if username left then check for password field
if($_POST["pwd"]==''){ // if it also blank then show this message
echo "You leave both the fields blank. Please fill them and then click on submit to continue.";
}
else {echo "User Name field can not be left blank."; // else show user name left blank
}
}
elseif ($_POST["pwd"]==''){ // if username is there then check for a null password
echo "Password field can not be left blank.";
}
else{
// We will add User into database here..
$query="INSERT INTO $DBTable (username, password)
VALUES('$_POST[uname]','$_POST[pwd]')";
// We are doing it for an example. Please encrypt your password before using it on your website
if (!mysql_query($query,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added ";
// Now Create a directory as User Name.
$username=$_POST["uname"];
mkdir(dirname(__FILE__)."/users/"."$username"); // Create Directory
recurse_copy($SourceDir,$username); // Copy files from source directory to target directory
// Finally print the message shown below.?>
Welcome <?php echo $_POST["uname"]; ?>!
You are account folder with name <?php echo $_POST["uname"]; ?> has been created successfully.
<?}}?>
</body>
</html>
and this is the function code.
<?php
// This source code is copied from http://php.net/manual/en/function.copy.php
// Real author of this code is gimmicklessgpt at gmail dot com
function recurse_copy($src,$dst) { // recursive function that copy files from one directory to another
$dir = opendir($src);
#mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_copy($src . '/' . $file,$dst . '/' . $file);
}
else {
copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
//echo "$src";
}
?>
Dont reckon the config file contains anything that will change the destination of the copy so not including that.

I see 2 problems. The first is how you are calling your function:
mkdir(dirname(__FILE__)."/users/"."$username"); // Create Directory
recurse_copy($SourceDir,$username); // Copy files from source directory to target directory
Should be:
// Create Directory
mkdir(dirname(__FILE__)."/users/"."$username");
// Copy files from source directory to target directory; the one you just created
recurse_copy($SourceDir,dirname(__FILE__)."/users/"."$username");
The second is the #mkdir($dst); in your function. You should change your logic to only create subdirectories of the original destination.

Related

Making An HTML Directory List

I have a form on my site where users can enter links to articles
So far... when a link is submitted, I am able to get that link to post to a destination html page.
However... if another link is submitted, it deletes the first one.
I would like the links to 'stack' and make a list to the destination (directory) page (which is currently an html page).
I don't know how to achieve this. Any advice or examples would be greatly appreciated.
I have include a very stripped down version of all three pages....
1.) The Form
<!DOCTYPE html>
<html>
<head>
<title>FORM</title>
<style>
body{margin-top:20px; margin-left:20px;}
.fieldHeader{font-family:Arial, Helvetica, sans-serif; font-size:12pt;}
.articleURL{margin-top:10px; width:700px; height:25px;}
.btnWrap{margin-top:20px;}
.postButton{cursor:pointer;}
</style>
</head>
<body>
<form action="urlUpload.php" method="post" enctype="multipart/form-data">
<div class="fieldHeader">Enter Article Link:</div>
<input class="articleURL" id="articleURL" name="articleURL" autocomplete="off">
<div class="btnWrap"><input class="postButton" type="submit" name="submit" value="POST"></button></div>
</form>
</body>
</html>
The Upload PHP (buffer) Page
<?php ob_start(); ?>
<!DOCTYPE html>
<html>
<head>
<title>urlUpload</title>
<style>body{margin-top:20px; margin-left:20px;}</style>
</head>
<body>
<?php $articleURL = htmlspecialchars($_POST['articleURL']); echo $articleURL;?>
</body>
</html>
<?php echo ''; file_put_contents("urlDirectory.html", ob_get_contents()); ?>
3.) The Destination HTML 'Directory List' page
<!DOCTYPE html>
<html>
<head>
<title>urlDirectory</title>
<style>body{margin-top:20px; margin-left:20px;}</style>
</head>
<body>
Sumbitted URL's should be listed here:
</body>
</html>
PS: I may not even need the middle php 'buffer' page. My knowledge of this sort of thing is limited thus far. If I don't need that, and can skip that page to accomplish my needs, please advise as well.
You can do this by using PHP to write the file and using urlDirectory.html as a template. You will just need to change your php file:
urlUpload.php
<?php
function saveUrl($url, $template, $tag)
{
// If template is invalid, return
if (!file_exists($template)) {
return false;
}
// Remove whitespace from URL
$url = trim($url);
// Ignore invalid urls
if (!filter_var($url, FILTER_VALIDATE_URL)) {
return true;
}
// Read template into array
$html = file($template);
foreach ($html as &$line) {
// Look for the tag, we will add our new URL directly before this tag, use
// preg_match incase the tag is preceded or followed by some other text
if (preg_match("/(.*)?(" . preg_quote($tag, '/') . ")(.*)?/", $line, $matches)) {
// Create line for URL
$urlLine = '<p>' . htmlspecialchars($_POST['articleURL']) . '</p>' . PHP_EOL;
// Handle lines that just contain body and lines that have text before body
$line = $matches[1] == $tag ? $urlLine . $matches[1] : $matches[1] . $urlLine . $matches[2];
// If we have text after body add that too
if (isset($matches[3])) {
$line .= $matches[3];
}
// Don't process any more lines
break;
}
}
// Save file
return file_put_contents($template, implode('', $html));
}
$template = 'urlDirectory.html';
$result = saveUrl($_POST['articleURL'], $template, '</body>');
// Output to browser
echo $result ? file_get_contents($template) : 'Template error';

Try/Catch seems to work with $_POST but not with session variables, PHP

I'm working on a php tutorial where a thumbnail generation page allows me to select from a dropdown list of photos in a directory on my server and upon hitting the submit button, a thumbnail of given size is created using a custom thumbnail class (the thumbnail overwrites the original image, which is fine for what I'm doing now). It's basic stuff and works as expected.
The page code:
<?php
$folder = '../images/';
use ClassFiles\Image\Thumbnail;
if (isset($_POST['create'])) {
require_once('ClassFiles/Image/Thumbnail.php');
try {
$thumb = new Thumbnail($_POST['pix']);
$thumb->setDestination('../images/');
$thumb->setMaxSize(400);
$thumb->create();
$messages = $thumb->getMessages();
} catch (Exception $e) {
echo $e->getMessage();
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Thumb</title>
</head>
<body>
<?php
if (isset($messages) && !empty($messages)) {
echo '<ul>';
foreach ($messages as $message) {
echo "<li>$message</li>";
}
echo '</ul>';
}
?>
<form method="post" action="">
<p>
<select name="pix" id="pix">
<option value="">Select an image</option>
<?php
$files = new FilesystemIterator('../images/');
$images = new RegexIterator($files, '/\.(?:jpg|png|gif)$/i');
foreach ($images as $image) {
$filename = $image->getFilename();
?>
<option value="<?= $folder . $filename; ?>"><?= $filename; ?></option>
<?php } ?>
</select>
</p>
<p>
<input type="submit" name="create" value="Create Thumbnail">
</p>
</form>
</body>
</html>
The custom thumbnail class is lengthy and for the sake of brevity I'm not posting it here unless requested, as it works fine.
So here's the problem:
I decided to take the image path and image filename information from an upload page I've been working on and store them in session variables that could be taken to the thumbnail generation page. The code in the thumbnail generation page was modified as shown:
<?php
require_once('includes/session_admin.php');
$folder = $_SESSION['image_path'];
use ClassFiles\Image\Thumbnail;
$getSize = getimagesize($_SESSION['image_path'] . $_SESSION['image_filename']);
$imagePath = $_SESSION['image_path'];
$imageFilename = $_SESSION['image_filename'];
if ($getSize[0] > 400) {
require_once('ClassFiles/Image/Thumbnail.php');
try {
$thumb = new Thumbnail($imageFilename);
$thumb->setDestination($imagePath);
$thumb->setMaxSize(400);
$thumb->create();
$messages = $thumb->getMessages();
} catch (Exception $e) {
echo $e->getMessage();
}
} else {
echo "Image is " . $getSize[0] . "px wide and is OK!";
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Thumb</title>
</head>
<body>
<?php
if (isset($messages) && !empty($messages)) {
echo '<ul>';
foreach ($messages as $message) {
echo "<li>$message</li>";
}
echo '</ul>';
}
// this was just to test that the session variables were correct
echo $_SESSION['image_path'] . $_SESSION['image_filename'];
echo '<br>';
print_r(getimagesize($_SESSION['image_path'] . $_SESSION['image_filename']));
?>
<!--
Removed the form...
-->
</body>
</html>
Now, instead of the conditional statement checking to see if $_POST was submitted, the code (I thought) would automatically check to see if the image, given the full path and filename, is wider than 400px, and if so, resize the image using the custom thumbnail class.
But, this throws errors from the thumbnail class, the same class that works just fine with the original thumbnail generation page code from the tutorial.
This works in the original tutorial code:
$thumb = new Thumbnail($_POST['pix']);
but not when modified to take a session variable instead:
$thumb = new Thumbnail($imageFilename);
I've looked and looked for any suggestion that $_POST was required here, I checked that the session variables were passing along the proper information, and they are. But making the switch from $_POST to using a session variable prevents this from working.
As you'll see, I'm still learning php and this is one of those hurdles that has held me up all day. Perhaps the answer is glaringly obvious, but I'm certainly at a standstill.
All input is appreciated, thanks!
Try this before set the object of your class
$_POST['pix']=$_SESSION['image_filename'];
So you set the POST variable manually and use it a The thumbnail class suppose it

Variable for file directory path not being recognized

so far I've successfully moved an uploaded image to its designated directory and stored the file path of the moved image into a database I have.
Problem is, however, is that the img src I have echoed fails to read the variable containing the file path of the image. I've been spending time verifying the validity of my variables, the code syntax in echoing the img src, and the successful execution of the move/storing code, but I still get <img src='' when I refer to the view source of the page that is supposed to display the file path contained in the variable.
I believe the file path is stored within the variable because the variable was able to be recognized by the functions that both moved the image to a directory and the query to database.
My coding and troubleshooting experience is still very adolescent, thus pardon me if the nature of my question is bothersomely trivial.
Before asking this question, I've searched for questions within SOF but none of the answers directly addressed my issue (of the questions I've searched at least).
Main PHP Block
//assigning post values to simple variables
$location = $_POST['avatar'];
.
.
.
//re-new session variables to show most recent entries
$_SESSION["avatar"] = $location;
.
.
.
if (is_uploaded_file($_FILES["avatar"]["tmp_name"])) {
//define variables relevant to image uploading
$type = explode('.', $_FILES["avatar"]["name"]);
$type = $type[count($type)-1];
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$rdn = substr(str_shuffle($chars), 0, 15);
//check image size
if($_FILES["avatar"]["size"] > 6500000) {
echo"Image must be below 6.5 MB.";
unlink($_FILES["avatar"]["tmp_name"]);
exit();
}
//if image passes size check continue
else {
$location = "user_data/user_avatars/$rdn/".uniqid(rand()).'.'.$type;
mkdir("user_data/user_avatars/$rdn/");
move_uploaded_file( $_FILES["avatar"]["tmp_name"], $location);
}
}
else {
$location = "img/default_pic.jpg";
}
HTML Block
<div class="profileImage">
<?php
echo "<img src='".$location."' class='profilePic' id='profilePic'/>";
?><br />
<input type="file" name="avatar" id="avatar" accept=".jpg,.png,.jpeg"/>
.
.
.
View Source
<div class="profileImage">
<img src='' class='profilePic' id='profilePic'/><br />
<input type="file" name="avatar" id="avatar" accept=".jpg,.png,.jpeg"/>
.
.
.
Alright, I've finally found the error and was able to successfully solve it!
Simply declare a avatar session variable to the $location variable after updating the table, update the html insert by replacing all $location variables with $_SESSION["avatar_column"] and you are set!
PHP:
$updateCD = "UPDATE users SET languages=?, interests=?, hobbies=?, bio=?, personal_link=?, country=?, avatar=? WHERE email=?";
$updateST = $con->prepare($updateCD);
$updateST->bind_param('ssssssss', $lg, $it, $hb, $bio, $pl, $ct, $location, $_SESSION["email_login"]);
$updateST->execute();
$_SESSION["avatar"] = $location; //Important!
if ($updateST->errno) {
echo "FAILURE!!! " . $updateST->error;
}
HTML:
<div class="profileImage">
<?php
$_SESSION["avatar"] = (empty($_SESSION["avatar"])) ? "img/default_pic.jpg" : $_SESSION["avatar"] ;
echo "<img src='".$_SESSION["avatar"]."' class= 'profilePic' id='profilePic'> ";
?>
.
.
.
Thank you!
try this code
<?php
error_reporting(E_ALL);
ini_set('display_errors','on');
$location = ""; //path
if($_POST && $_FILES)
{
if(is_uploaded_file())
{
// your code
if(<your condition >)
{
}
else
{
$location = "./user_data/user_avatars/".$rdn."/".uniqid(rand()).'.'.$type;
if(!is_dir("./user_data/user_avatars/".$rdn."/"))
{
mkdir("./user_data/user_avatars/".$rdn."/",0777,true);
}
move_uploaded_file( $_FILES["avatar"]["tmp_name"], $location);
}
}
else
{
$location = "img/default_pic.jpg";
}
}
?>
Html Code :-
<div>
<?php
$location = (empty($location)) ? "img/default_pic.jpg" : $location ;
echo "<img src='".location."' alt='".."'> ";
?>
</div>
If it helpful don't forget to marked as answer so another can get correct answer easily.
Good Luck..

How can I set the value of a variable passed into a function?

I am working on a page that allows the user to "upload" multiple files at once (they are stored locally in folders relative to their type).
My problem is that when I try to pass $upFile1 and $fileInfo1 to writeResults() to update $fileInfo1 with information about $upFile1, the echoed result is empty.
I did some research and this appears to be a scoping issue, but I'm not sure about the best way to get around this having just started learning PHP last month.
Any help would be greatly appreciated.
foo.html
<!DOCTYPE HTML>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form method="post" action="foo.php" enctype="multipart/form-data">
<p>
<b>File 1:</b><br>
<input type="file" name="upFile1"><br/>
<br/>
<b>File 2:</b><br>
<input type="file" name="upFile2"><br/>
<br/>
</p>
<p>
<input type="submit" name="submit" value="Upload Files">
</p>
</form>
</body>
</html>
foo.php
<?php
$upFile1 = $_FILES['upFile1'];
$upFile2 = $_FILES['upFile2'];
$fileInfo1 = "";
$fileInfo2 = "";
// Check if directories exist before uploading files to them
if (!file_exists('./files/images')) mkdir('./files/images', 0777, true);
if (!file_exists('./files/text')) mkdir('./files/text', 0777, true);
// Copies the file from the source input to its corresponding folder
function copyTo($source) {
if (($source['type'] == 'image/jpg') || ($source['type'] == 'image/png')) {
#copy($source['tmp_name'], "./files/images/".$source['name']);
}
if ($source['type'] == 'text/plain') {
#copy($source['tmp_name'], "./files/text/".$source['name']);
}
}
// Outputs file data for input file to destination
function writeResults($source, $destination) {
$destination .= "You sent: ";
$destination .= $source['name'];
$destination .= ", a ";
$destination .= $source['size'];
$destination .= "byte file with a mime type of ";
$destination .= $source['type'];
$destination .= ".";
// echoing $destination outputs the correct information, however
// $fileInfo1 and $fileInfo2 aren't affected at all.
}
// Check if both of the file uploads are not empty
if ((!empty($upFile1['name'])) || (!empty($upFile2['name']))) {
// Check if the first file upload is not empty
if (!empty($upFile1['name'])) {
copyTo($upFile1);
writeResults($upFile1, $fileInfo1);
}
// Check if the second file upload is not empty
if (!empty($upFile2['name'])) {
copyTo($upFile2);
writeResults($upFile2, $fileInfo2);
}
} else {
die("No input files specified.");
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<p>
<!-- This is empty -->
<?php echo "$fileInfo1"; ?>
</p>
<p>
<!-- This is empty -->
<?php echo "$fileInfo2"; ?>
</p>
</body>
</html>
you are passing the values of $fileInfo1 and $fileInfo2 but they are empty. After that there is no relation between the $destination value and the fileininfo values.
Change your function to return the $destination value.
Change your writeResults command to $fileInfo1 = writeResults($upFile1);
Use the & sign to pass variables by reference
function addOne(&$x) {
$x = $x+1;
}
$a = 1;
addOne($a);
echo $a;//2
function writeResults($source, &$destination) {
$destination .= "You sent: ";
$destination .= $source['name'];
$destination .= ", a ";
$destination .= $source['size'];
$destination .= "byte file with a mime type of ";
$destination .= $source['type'];
$destination .= ".";
// echoing $destination outputs the correct information, however
// $fileInfo1 and $fileInfo2 aren't affected at all.
}
Adding & in front of $destination will pass the variable by reference, instead of by value. So modifications made in the function will apply to the variable passed, instead of a copy inside the function.

Simultaneous file upload to the same directory

For part of my web app, I'm attempting to upload 1 file under 2 different names. The first name is the original file name that the user specified. This is to be used for reference later on in my app. The second name is an altered name (simply adding in a counter variable). For uploading a single file using move_uploaded_file($name, $path), it works like a charm. When I attempted to call one move_uploaded_file(...) after the other, only the first function would upload a file. The second function would not return an error message.
After looking online, it seemed that this could be accomplished with a loop. I placed the names and the paths in an array, loop through it with a foreach loop but only the first file is uploaded.
Below are the files and their relevant portions as some are lengthy.
mainPage.php applies a header across all of my pages.
verifyFile.php is the file that does the uploading as well as verifying the bulk processing to check that the file is valid.
workPage.php
<?php
session_start();
require("mainPage.php");
?>
<link rel = "stylesheet" type = "text/css" href = "CSS/workpageCSS.css" />
<div id = "pageContainer">
<form enctype = "multipart/form-data" action = "verifyFile.php" method = "post">
<table border = "0" cellpadding = "2" cellspacing = "5">
<tr>
<td>
<label for = "fileName">Select file to upload</label>
</td>
<td>
<input type = "file" name = "file" id = "fileName" placeholder = "Choose file path" autofocus = "autofocus" required = "required" />
</td>
</tr>
<tr>
<td></td>
<td><input type = "submit" value = "Load file" /></td>
</tr>
</table>
</form>
</div>
Portion of verifyFile.php that uploads the file.
Attempt 1:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');
$dupFile = appendFileName(basename($_FILES['file']['name']));
$origToUpload = basename($_FILES['file']['name']);
$targetPath = ("uploads/".$dupFile);
$origTargetPath = "uploads/".$origToUpload;
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)) {
#echo("Successfully uploaded ".basename($_FILES['file']['name']));
} else {
echo("Failed 1<br />");
}
/*move_uploaded_file($_FILES['file']['tmp_name'], $origTargetPath); Does not upload but no errors are generated */
?>
Attempt 2
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1')
$filesToUpload = array($targetPath, $origTargetPath);
foreach($filesToUpload as $toUpload) {
if(move_uploaded_file($_FILES['file']['tmp_name'], $toUpload)) {
echo("worked!"); /* first time is successful and $targetPath is loaded onto my server */
} else {
echo("neg"); /* nothing is uploaded and returns neg */
}
}
?>
$origTargetPath and $targetPath are both valid since if I reverse them in my array, only the first file is correctly uploaded.
For additional information, I'm using Apache via XAMPP.
When you call move_upload_file, php will move the file from the file temporary location, to the one you specified. So you can't move the file twice.
What you are looking for is the copy function. In your case (first attempt):
copy($targetPath, $origTargetPath);
You could also consider symlink

Categories