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
Related
would any one know how to automatically create a file through PHP so when the tag is clicked it also have the file right now it's only a path which is displayed through a loop. but when you click it there is no file, of course, long story short how can I also create a file too with a loop so all links have files created through fopen or something, just like all of them have paths generated.
<?php
function display_user_docs($doc_array) {
// set global variable, to test later if this is on the page
global $doc_table;
$doc_table = true;
?>
<br>
<form name="doc_table" action="delete_doc.php" method="post">
<table width="300" cellpadding="2" cellspacing="0">
<?php
$color = "#cccccc";
echo "<tr bgcolor=\"".$color."\"><td><strong>Documentations</strong></td>";
echo "<td><strong>Delete?</strong></td></tr>";
if ((is_array($doc_array)) && (count($doc_array) > 0)) {
foreach ($doc_array as $doc) {
if ($color == "#cccccc") {
$color = "#ffffff";
} else {
$color = "#cccccc";
}
echo "<tr bgcolor=\"".$color."\"><td><a class=\"all-doc-link\" href=\"".$doc.".php\">".htmlspecialchars($doc)."</a></td>
<td><input type=\"checkbox\" name=\"del_me[]\"
value=\"".$doc."\"></td>
</tr>";
}
} else {
echo "<tr><td>No documentation on record</td></tr>";
}
?>
</table>
</form>
<?php
}
?>
You can use file_put_contents to create a file in PHP.
It takes two parameters, the first of which is the name of the file to create, and the second of which is the contents to put inside of the file.
For example, if I wanted to make a file called 123.txt which contains hello world, I would do the following:
file_put_contents("123.txt", "hello world");
The filename can contain slashes /, so that you can specify which folder to create the file in. Thus, if I wanted to make my 123.txt file in the folder abc, I can put abc/123.txt as the filename (as long as abc is in the same folder as the PHP script).
You can find more about file_put_contents in the PHP manual.
I am fairly new to PHP and am having trouble with an assignment. The assignment is to create a simple address book in PHP, and i would like my address book to display all addresses that are in it along with a submission box at the bottom to add more addresses. Currently, I can get the addresses to display, but the submission box gives me an error ") Notice: Undefined variable: addres_add in C:\wamp64\www\address_tmp\address.php on line 18"
This is my code thus far, I snagged the submission box code from another answer here on StackOverflow, but I don't know how to modify it to fit my needs.
<?php
//Open address book file and print to user
$fh = fopen("address_book.txt", "r+");
echo file_get_contents("address_book.txt");
//Perfom submit function
if(isset($_POST['Submit']))
fseek($fh, 0, SEEK_END);
fwrite($fh, "$addres_add") or die("Could not write to file");
fclose($fh);
print("Address added successfully. Updated book:<br /><br />");
echo file_get_contents("address_book.txt");
{
$var = $_POST['any_name'];
}
?>
<?php
//HTML for submission box?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="any_name">
<input type="submit" name="submit">
</form>
<p>
You never assigned the variable from the form input. You need:
$addres_add = $_POST['any_name'];
fwrite($fh, "$addres_add") or die("Could not write to file");
Also, if you're just adding to the file, you should open it in "a" mode, not "r+". Then you don't need to seek to the end, that happens automatically.
You probably should put a newline between each record of the file, so it should be:
fwrite($fh, "$addres_add\n") or die("Could not write to file");
Otherwise, all the addresses will be on the same line.
Here is a simpler version of your program.
<?php
$file_path ="address_book.txt";
// Extract the file contents as a string
$file_contents = file_get_contents($file_path);
if ($file_contents) // Check if the file opened correctly
echo($file_contents . " \n"); // Echo contents (added newline for readability)
else
echo("Error opening file. \n");
// Make sure both form fields are set
if(isset($_POST['submit']) && isset($_POST['any_name']))
{
// Append the new name (used the newline character to make it more readable)
$file_contents .= $_POST["any_name"] ."\n";
// Write the new content string to the file
file_put_contents($file_path, $file_contents);
print("Address added successfully. Updated book:<br /><br />");
echo($file_contents);
}
else
{
echo("Both form elements must be set. \n");
}
?>
//HTML for submission box?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="any_name">
<input type="submit" name="submit">
</form>
Even with no comments it should be self explanatory. I leave the proper error dealing to you.
To answer your question, the error was being caused because the $address_add variable wasn't previously declared. You also added quotes to it, making it a string.
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.
I am hoping to offer users a user submitted image gallery. I have written a upload script which saves the file above the www root. I know I can serve the file by specifying the page header and then using readfile, however I am planning to throw the images within a table to be displayed with other information and dont think the header/readfile is the best solution. I am thinking maybe symlinks but I am not sure.
What is the best method to achieve this?
You'll need a script like getimage.php which sends the image headers and echo's out its contents. Then in your HTML, you just utilize it as the <img src=''> in your HTML. The only purpose of getimage.php is to retrieve and output the image. It remains separate from whatever PHP you use to generate the HTML sent to the browser.
Additionally, you can check if the user has a valid session and permission to view the image in getimage.php and if not, send a some kind of access-denied image instead.
The contents of getimage.php are small and simple:
// Check user permissions if necessary...
// Retrieve your image from $_GET['imgId'] however appropriate to your file structure
// Whatever is necessary to determine the image file path from the imgId parameter.
// Output the image.
$img = file_get_contents("/path/to/image.jpg");
header("Content-type: image/jpeg");
echo($img);
exit();
In your HTML:
<!-- as many as you need -->
<img src='getimage.php?imgId=12345' />
<img src='getimage.php?imgId=23456' />
<img src='getimage.php?imgId=34567' />
It then becomes the browser's job to call getimage.php?imgId=12345 as the path to the image. The browser has no idea it is calling a PHP script, rather than an image in a web accessible directory.
If the script is running on a Unix server, you might try to create a symlink in your web root that links to the directory outside of your web root.
ln -s /webroot/pictures /outside-of-webroot/uploads
If you're using an Apache server you could also have a look at mod_alias.
I've heard that there are a few issues when using mod_alias and configuring it through .htaccess. Unfortunately I don't have any experience with mod_alias whatsoever.
Something that always has worked well for me is to have users upload their images directly into my mysql db. The PHP will encode into base64 and store into a blob. Then you do something similar to what michael said to retrieve and display the image. I've included some code from a project I was working on in 2008. I wouldn't copy it exactly if it's a method you're interested in using since it's old code.
This is the PHP to upload and store into a DB. Obviously replace your info and connect to your own DB.
<?php
include("auth.php");
// uploadimg.php
// By Tyler Biscoe
// 09 Mar 2008
// Test file for image uploads
include("connect.php");
include("include/header.php");
$max_file_size = 786432;
$max_kb = $max_file_size/1024;
if($_POST["imgsubmit"])
{
if($_FILES["file"]["size"] > $max_file_size)
{
$error = "Error: File size must be under ". $max_kb . " kb.";
}
if (!($_FILES["file"]["type"] == "image/gif") && !($_FILES["file"]["type"] == "image/jpeg") && !($_FILES["file"]["type"] == "image/pjpeg"))
{
$error .= "Error: Invalid file type. Use gif or jpg files only.";
}
if(!$error)
{
echo "<div id='alertBox'> Image has been successfully uploaded! </div>";
$handle = fopen($_FILES["file"]["tmp_name"],'r');
$file_content = fread($handle,$_FILES["file"]["size"]);
fclose($handle);
$encoded = chunk_split(base64_encode($file_content));
$id = $_POST["userid"];
echo $_FILES["file"]["tmp_name"];
$default_exist_sql = "SELECT * FROM members WHERE id='".$id."'";
$default_result = mysql_query($default_exist_sql);
$results = mysql_fetch_array($default_result);
if(!$results["default_image"])
{
$insert_sql = "UPDATE members SET default_image = '$encoded' WHERE id='". $id ."'";
mysql_query($insert_sql);
}
$sql = "INSERT INTO images (userid, sixfourdata) VALUES ('$id','$encoded')";
mysql_query($sql);
}
else
{
echo "<div id='alertBox'>". $error . "</div>";
}
}
?>
<br />
<font class="heading"> Upload images </font>
<br /><br />
<form enctype = "multipart/form-data" action = "<?php $_SERVER['PHP_SELF']; ?>" method = "post" name = "uploadImage">
<input type = "hidden" name="userid" value = "<?php echo $_GET["userid"]; ?>" >
<input id="stextBox" type="file" name="file" size="35"><br />
<input type="submit" name="imgsubmit" value="Upload">
</form>
<?php include("include/footer.php"); ?>
This next one displays the file:
<?php
// image.php
// By Tyler Biscoe
// 09 Mar 2008
// File used to display pictures
include("connect.php");
$imgid = $_GET["id"];
$result = mysql_query("SELECT * FROM images WHERE imgid=" . $imgid . "");
$image = mysql_fetch_array($result);
echo base64_decode($image["sixfourdata"]);
echo $image["sixfourdata"];
?>
Then:
<img src="image.php?id=your_img_id">
I am trying to upload an image to the server.
I hava a form with a couple of inputs...
INSIDE this form, I have an Iframe which contains another form for the upload, this because I dont want the original form to submit().
The original form basically:
<form> ...... bla bla bla alot of inputs....<iframe src="pic_upload.html"></iframe></form>
Here is pic_upload.html:
</head>
<body><form name="pic_form" id="pic_form" action="bincgi/imageUpload.php" method="post" target="pic_target"><input name="pic_file" type="file" id="pic_file" size="35" onchange="this.form.submit();"></form><div id="pic_target" name="pic_target" style="width:80px; height:80px;"></div></body>
</html>
Here is imageUpload.php:
<?php
$destination_path = getcwd().DIRECTORY_SEPARATOR;
//echo $destination_path;
$result = 0;
$target_path = $destination_path . basename($_FILES['pic_file']['name']);
if(#move_uploaded_file($_FILES['pic_file']['tmp_name'], $target_path)) {
$result = 1;
}
?>
I get this error: Undefined index: pic_file on line 5 in imageUpload.php
ALSO, if I get this to work, is there a good way to display the uploaded image inside the target of the form?
Thanks alot!
PS: I will add javascript to the tags because maybe thats what I need here!
Don't forget about form attribute
enctype="multipart/form-data"
The form needs to be like this
<form enctype="multipart/form-data" action="__URL__" method="POST">
Check out this PHP.net documentation for more information.
You first need to test if $_FILES has an item with the key pic_file. So use the isset function to do so:
$destination_path = getcwd().DIRECTORY_SEPARATOR;
//echo $destination_path;
$result = 0;
if (isset($_FILES['pic_file'])) {
$target_path = $destination_path . basename($_FILES['pic_file']['name']);
if (#move_uploaded_file($_FILES['pic_file']['tmp_name'], $target_path)) {
$result = 1;
}
}