Difficulty in moving temp files with php after uploading them and renaming - php

I have a form for uploading files to a web server and then saving the filepath along with the email address it's connected to and a serial code to a sql table. The problem is, what if someone uploads a file with the same name as a previous person or upload? To fix this, I want to name the file "insert serial code here".mp4 or .pdf. When I do this it comes up with the following error:
Warning: move_uploaded_file() [function.move-uploaded-file]: The second argument to copy() function cannot be a directory in /home/content/98/10339998/html/scripts/upload.php on line 57
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/php7UzcdG' to '../story_files/' in /home/content/98/10339998/html/scripts/upload.php on line 57
Stored in: ../story_files/
Here is a full echo example:
Customer's unique serial code: d0d74-ef227
Upload:
Type: application/pdf
Size: 14.4287109375 kB
Temp file: /tmp/php7UzcdG
Warning: move_uploaded_file() [function.move-uploaded-file]: The second argument to copy() function cannot be a directory in /home/content/98/10339998/html/scripts/upload.php on line 57
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/php7UzcdG' to '../story_files/' in /home/content/98/10339998/html/scripts/upload.php on line 57
Stored in: ../story_files/
../story_files/
Upload: file.mp4
Type: video/mp4
Size: 374.6396484375 kB
Temp file: /tmp/phpQczVLm
file.mp4 already exists.
Serial Code Emailed to Customer Michael
Here is the code, note the difference between the video and story part of it, I didn't convert the video part yet it is the fully-working original code. Also, PHP thinks that the serial code is a filepath, why is that? The code is simply a 10 digit series of letters and numbers two sets of 5 digits with a dash between to simplify reading it.
<title>Uploading Files and Sending Serial Code To Customer</title>
<!--Favicon Code-->
<link rel="shortcut icon" type="image/x-icon" href="../images/favicon.ico" />
<!--Favicon Code-->
<link href="/CSS/CSS.css" rel="stylesheet" type="text/css" />
<div align="center">
<p><span class="linkText">Home Contact Us Products</span> </p>
<p> </p>
<h2 class="headingText"><img src="/images/banner.jpg" alt="legendmaker - makes legends: banner" width="297" height="473"></h2>
<h2 class="headingText"> </h2>
<h2 class="headingText">Upload Story Files</h2>
</div>
<?php
// before we do anything make sure there is a correct password (we don't want unauthorized usage)
$password = trim($_POST['password']);
if ("*****" == $password)// not going to post my pass on the forums :P
{
///// generate unique serial code ///////////////////////////////////////////////////////////////
$string1 = substr(md5(uniqid(rand(), true)), -5, 5);
$string2 = substr(md5(uniqid(rand(), true)), -5, 5);
$serial = sprintf('%s-%s', $string1, $string2);
echo "Customer's unique serial code: ";
echo $serial;
echo " ";
/////end of generate unique serial code ///////////////////////////////////////////////////////////////
///story file upload///////////////////////////////////////////////////////////////////////////////////
if ($_FILES["file"]["size"])
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "<br>" . "<br>" . "<br>" . "Upload: " . $_FILES["file"]["$code"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("stories/" . $_FILES["file"]["$code"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"../story_files/" . $_FILES["file"]["code"]);
echo "Stored in: " . "../story_files/" . $_FILES["file"]["$code"] . "<br>";
$storyPath = sprintf("../story_files/" . $_FILES["file"]["$code"]);
echo $storyPath;
}
}
}
else
{
echo "No story file was chosen, this is not an error just a notification. Any other files selected will still upload correctly. ";
}
///video file upload////////////////////////////////////////////////////////////////////////////////
if ($_FILES["videoFile"]["size"])
{
if ($_FILES["videoFile"]["error"] > 0)
{
echo "Return Code: " . $_FILES["videoFile"]["error"] . "<br>";
}
else
{
echo "<br>" . "<br>" ."Upload: " . $_FILES["videoFile"]["name"] . "<br>";
echo "Type: " . $_FILES["videoFile"]["type"] . "<br>";
echo "Size: " . ($_FILES["videoFile"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["videoFile"]["tmp_name"] . "<br>";
if (file_exists("../video_files/" . $_FILES["videoFile"]["name"]))
{
echo $_FILES["videoFile"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["videoFile"]["tmp_name"],
"../video_files/" . $_FILES["videoFile"]["name"]);
echo "Stored in: " . "../video_files/" . $_FILES["videoFile"]["name"] . "<br>";
$videoPath = sprintf("../video_files/" . $_FILES["file"]["name"]);
echo $videoPath;
}
}
}
else
{
echo "No video file was chosen, this is not an error just a notification. Any other files selected will still upload correctly. ";
}
/// submit information to database/////////////////////////////////////////////////////////////////////
$username="storycodes";
$password="Legendmaker1!";
$con = mysqli_connect("storycodes.db.10339998.hostedresource.com",$username,$password);
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
$email = $_POST['email'] ;
$submitInformation = "INSERT INTO `storycodes`.`storycodes` (`code`, `email`, `video`, `story`) VALUES ('$serial', '$email', '$videoPath', '$storyPath');";
mysqli_query($con, $submitInformation); // submits information to database for later recollection
////////////////////end of submit to database///////////////////////////////////////////////////////////
/////////////////// email the code to customer//////////////////////////////////////////////////////////
require_once '../PHPMailer_5.2.2/class.phpmailer.php';
$name = $_POST['name'] ;
$body = "Thank you for using legendmaker $name! Your story has been completed and will now be accesible at www.thelegendmaker.net/stories.html On that page you will be required to enter a serial code in order to access your files. We require a serial code in order to access files because we care about our customers and security is a concern. Your serial code is: $serial";
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
try
{
$mail->AddAddress($email, $name);
$mail->SetFrom('fakeemail1#gmail.com', 'Sender Name');
$mail->AddReplyTo('fakeperson#yahoo.com', 'Fake Name');
$mail->Subject = "Message From Legendmaker: $name your story is now complete.";
$mail->Body = $body;
$mail->Send();
echo "<br>" . "<br>" . "Serial Code Emailed to Customer $name</p>\n";
echo "<img src='/images/knight-success.png' alt='success' width='429' height='791' />";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
/////////////////// end of email code///////////////////////////////////////////////////////////////////
}
else
{
echo "incorrect password";
}
/// end of file uploads//////////////////////////////////////////////////////////////////////////
?>
<link href="/CSS/CSS.css" rel="stylesheet" type="text/css" />
<p>
<!--google cart code ------------------------------------>
<script id='googlecart-script' type='text/javascript' src='https://checkout.google.com/seller/gsc/v2_2/cart.js?mid=215313740482542' integration='jscart-wizard' post-cart-to-sandbox='false' currency='USD' productWeightUnits='LB'></script>
</p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p align="center">Contact Us Site Owner Upload Service Agreement</p>

You use $_FILES["file"]["code"] instead of $_FILES["file"]["name"] for the file name which doesn't exist so the result is that you're passing a directory as the second argument.
move_uploaded_file($_FILES["file"]["tmp_name"],
"../story_files/" . basename($_FILES["file"]["name"]));
EDIT
if you want to use the serial code that is generated to be the file name just concatenate it to the directory string in move_uploaded_file
move_uploaded_file($_FILES["file"]["tmp_name"],
"../story_files/" . $serial);

Related

How do you display the stream name? [ICECAST]

I took a part of PHP code from a different Stackoverflow question, and it works perfectly.
<?php header>
//Display IceCast Server Stats
$server = "***********"; //IP (x.x.x.x or domain name)
$iceport = "8070"; //Port
$iceurl = "live"; //Mountpoint
$online = "<font color=green><b>ONLINE</b> </font><br />";
$offline = "<font color=red><b>OFFLINE</b></font><br />";
if($fp = #fsockopen($server, $iceport, $errno, $errstr, '1')) {
fclose($fp);
$ice_status=$online;
echo "<p><b>DJ:</b> $ice_status";
$stats = file("http://" . $server . ":" . $iceport . "/status2.xsl");
$status = explode(",", $stats[5]);
$artist = explode("-", $status[5]);
echo " " . $artist[1];
echo " - ";
echo " " . $artist[2];
echo "<br />";
// echo "<b>Listeners:</b> <b> " . $status[3] . "</b>";
echo "</p>";
//echo "<br />";
//echo "<p><a href=http://" . $server . ":" . $iceport . "/" . $iceurl . " target=new><b>Listen!</b></a></p>";
} else {
$ice_status=$offline;
echo "<p><b>DJ:</b> $ice_status";
}
?>
<hr />
</center>
I'm trying to add the stream name, which is currently:
echo "DJ: $ice_status";
This displays DJ: ONLINE, but I want it to say DJ: (DJ Name/Stream Name)
I do believe its variables from status2.xsl, but I'm a complete noob at this, and can't seem to figure out how to use it. Could anyone tell me what streamname variable would be?
I was also wondering, is it possible to make it so the "nowplaying.php" refreshes, but my whole web page doesn't? I've tried an iframe, but it makes it look really bad, and has errors.
What my website looks like at the moment: https://i.stack.imgur.com/luc4O.jpg
I'd suggest having a look at TheFineManualâ„¢:
http://icecast.org/docs/icecast-2.4.1/server-stats.html#xslt
Especially the part about status-json.xsl. Make sure you are running an up to date version of Icecast. Icecast is available from all major Linux distributions in up to date packaging. Xiph provides independent packaging, which is useful if there are no up to date packages for a distribution, e.g. shortly after an Icecast release.
status2.xsl was an example file, and a bad one at that. It was removed from newer Icecast versions.

How to carry POST variables to another file?

I am working on a form, and want to save a copy of every form submitted. The problem is the form's action is a counting file, that makes each file saved count up once. For example, the third form submitted is named "3.php", and the tenth form submitted is named "10.php". When I try to write the POST variable top the new file, it is gone. Anyway I could write their responses to a new document with my counting files code?
Form code on main file:
<form action="count.php" method="post">
<input type="text" name="formItem1">
<input type="text" name="formItem2" required>
<input type="text" name="formItem4" required>
<input type="text" name="formItem5" required>
<input type="text" name="formItem6" required>
<input type="submit" name="Click" value="Submit">
</form>
Count.php code:
<body>
<?php
define('countlog.txt', __DIR__ . "./");
if (file_exists('countlog.txt')) {
# If File exists - read its content
$start = (int) file_get_contents('countlog.txt');
} else {
# If No File Found - Create new File
$start = 1;
#file_put_contents('countlog.txt', "$start");
}
# When Form Submitted
if (isset($_POST) and isset($_POST['Click']) and $_POST['Click'] == "Submit") {
$file_name = "{$start}.php";
$template = file_get_contents('template.php');
#file_put_contents("./submissions/" . $file_name, "$template");
# Update Counter too
$start = $start + 1;
#file_put_contents('countlog.txt', "$start", 1);
echo "Generated Filename - $file_name";
}
?>
</body>
Template.php code:
echo "<h1>Answer1: " . $formItem1 . "</h1>";
echo "<h1>Answer2: " . $formItem2 . "</h1>";
echo "<h1>Answer3: " . $formItem3 . "</h1>";
echo "<h1>Answer4: " . $formItem4 . "</h1>";
echo "<h1>Answer5: " . $formItem5 . "</h1>";
echo "<h1>Answer: " . $formItem6 . "</h1>";
Use sessions. Create a session on each page with session_start(); Store the post value using the session global array. eg. $_SESSION['yourValue'] = POST['yourValue'];. Now on the rest of the pages you should be able to access the value. e.g
$yourValue = $_SESSION['yourValue'];
IF you use $template = file_get_contents('template.php'); it will make the content of template.php a string, and the variables will not be evaluated.
You could use eval() http://php.net/manual/en/function.eval.php to evaluate a string as PHP code. I would not recommend this method, but if you want to use it you will need to return, rather than echo the template otherwise the template will be echoed to the browser rather than the string you want to save to file.
template.php
return "<h1>Answer1: " . $formItem1 . "</h1>".
"<h1>Answer2: " . $formItem2 . "</h1>".
"<h1>Answer3: " . $formItem3 . "</h1>".
"<h1>Answer4: " . $formItem4 . "</h1>".
"<h1>Answer5: " . $formItem5 . "</h1>".
"<h1>Answer: " . $formItem6 . "</h1>";
count.php
$template = file_get_contents('template.php');
$template = eval($template);
It would be much easier/better to include the template, and the code will execute, thus populating the $template variable.
template.php
<?php
$template = "<h1>Answer1: " . $formItem1 . "</h1>".
"<h1>Answer2: " . $formItem2 . "</h1>".
"<h1>Answer3: " . $formItem3 . "</h1>".
"<h1>Answer4: " . $formItem4 . "</h1>".
"<h1>Answer5: " . $formItem5 . "</h1>".
"<h1>Answer: " . $formItem6 . "</h1>";
?>
count.php
include('template.php');
Both methods assume you have used extract($_POST); to import variables from an array into the current symbol table.

can't get loop in mysql_fetch_array to print on separate lines

I am trying to loop through my mysql query result and print out some of the data. What I expected was when I added "\n" to the end of the print message, it would print each message on a separate line. But for some reason its all on one line. Why is this and how can I make each message be on a separate line?
while($row = mysql_fetch_array($result))
{
$message = $row['action_type'] . " " . $row['identifier'] . " # " . " placeholder ";
if($row['location'] !== NULL)
{
$message += " on " . $row['location'] . "\n";
}
echo $message . "\n";
}
Your $message variable is ending with a /n when it should be \n. Try updating it to fix (unless of course, in that section of the code it's on purpose):
$message += " on " . $row['location'] . "\n";
The actual echo statement ends with a real newline, so this should work properly in a command-line, but not in a browser.
To get it to display on a new line in a browser, change the \n instances to <br />:
echo $message . "<br />";

Pass command line arguments from Form

I have a PHP script which contains the following line in the beginning of its script:
$file=$argv[$argc-1];
In the above line, $file is supposed to represent the file path chosen by the user. I should also point out that in this same PHP page is a Form. The form is a basic one, just has a submit button named "submit" and a text box named "fpath". The Form's layout is as follows:
<form method=post action='page1.php' enctype="multipart/form-data">
</form>
So, basically what I need to accomplish is to pass a command line argument to the current page (page1.php).
How would I go about doing this in PHP?
Thank you,
Evan
You need to use $_POST['key'] to get parameter from a POST form.
For the file, use $_FILES
For example:
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
?>

Errors code and wont work in PHP

I did post something earlier put this time I am going to post all of it.I am getting error message and it will not show up when i try to pull it up on local host.
Here's the code:
This one is includeindex.php
if ($_POST['submit'] != "") {
if ($_POST['name'] != "") {
session_start();
$_SESSION['name'] = $_POST['name'];
TopNavigation("PHP Includes Example - ECA236", "PHP Includes", $_SESSION['name']);
} else {
header("Location:includindex.php");
exit;
}
} else {
TopNavigation("PHP Includes Example - ECA236", "PHP Includes");
echo "<div class=\"formtable\">\n";
echo "<br>";
echo "<form action=\"" . $PHP_SELF . "\" method=\"post\">\n";
echo "Please enter your name:<input type=\"text\" name=\"name\">\n";
echo "<input type=\"submit\" class=\"btnSubmit\" value=\"Enter\" name=\"submit\">\n";
echo "</form>\n";
echo "<br>";
echo "</div>\n";
Footer();
}
?>
This one is header
<?php
function TopNavigation($pagetitle, $pageheading, $username = '') {
echo "<html>\n";
echo " <head>\n";
echo " <title>" . $pagetitle . "</title>\n";
echo " <link href=\"../style.css\" type=\"text/css\" rel=\"stylesheet\">";
echo " </head>\n";
echo " <body>";
echo " <h1>" . $pageheading . "</h1>\n";
echo " <hr>\n";
echo " <p class=\"tiny\">" . date("F j,Y") . "</p>";
if ($username != '') {
echo "<div align=\"center\">\n";
echo "Use a different name | About | Signout\n";
echo "</div>\n";
echo "<p>Welcome. " . $username . "!";
}
}
function Footer() {
echo "</body>\n";
echo "</html>\n";
}
?>
This one is about.php
<?php
session_start();
include("include/header.php");
if (!isset($_SESSION['name'])) {;
header("Location:includeindex.php");
exit;
} else {
TopNavigation("About Me -ECA236", "About Me", $_SESSION['name']);
echo "<p>Here is a little about me. I am a mother of twin girls who are 9 </p>\"n;
echo " < p>I been married for 5 years but been with my husband for 11 years </p > \"n;
echo "<p > I am attending college for Computer Programming and Database Mangament </p > \"n;
echo "<p > After I get done with this degree I am want to go back for Web Design </p > \"n;
echo "<p > since half my classes are web design now . I enjoy camping,bon fires and </p > \"n;
echo "<p > playing video games, hanging out with friends and family .</p > \"n;
Footer();
}
?>
This one is signout.php
<?php
session_start();
if (isset($_SESSION['name'])) {
session_destroy();
session_start();
}
header("Location:includeindex.php");
exit;
?>
I can not get it to show up and work at all. I have no clue why it is not doing it. Can someone please help me.
I keep getting errors no matter what I fixed and it doesnt show up when you look at it online..
here the errors i get:
Notice: Undefined variable: PHP_SELF in C:\wamp\www\includeindex.php on line 19
Undefined index: submit in C:\wamp\www\includeindex.php on line 4
Warning: include(include/header.php) [function.include]: failed to open stream: No such file or directory in C:\wamp\www\about.php on line 3
Warning: include() [function.include]: Failed opening 'include/header.php' for inclusion (include_path='.;C:\php\pear') in C:\wamp\www\about.php on line 3
Fatal error: Call to undefined function TopNavigation() in C:\wamp\www\about.php on line 9
All of your echo statements in the TopNavigation() function are still incorrectly quoted. Instead of \"n;, they should end with \n";
// Wrong
echo "<p>Here is a little about me. I am a mother of twin girls who are 9 </p>\"n;
// Should be:
echo "<p>Here is a little about me. I am a mother of twin girls who are 9 </p>\n";
---^^^^
in your php.ini change display_errors=Off to display_errors=On

Categories