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"];
}
?>
Related
I'm making a social media website for a project. I have a PHP function that allows the user to upload an image to a post and inside the function is an html form to allow them to select a form.
echo "<form method='post' enctype='multipart/form-data'>";
echo "<input type='file' name='myFile'/>";
echo "<label for='myFile' id='fileLabel'>File input</label>";
echo "<input type='submit' name='submitFileForm' value='Upload' />";
echo "</form>";
When I process the form with this code and print_r($_FILES) is empty but if I echo $_POST['myFile'] it displays the correct file name.
if (isset($_POST['submitFileForm'])) {
print_r($_FILES);
$my_folder = "img/";
if (move_uploaded_file($_FILES['myFile']['tmp_name'], $my_folder . $_FILES['myFile']['name'])) {
echo 'Received file' . $_FILES['myFile']['name'] . ' with size ' . $_FILES['myFile']['size'];
} else {
echo 'Upload failed!';
var_dump($_FILES['myFile']['error']);
}
}
Thank you for the help , I have been trying to debug this for the last 2 hours. Also I forgot to mention, I already tried increasing upload_max_filesize = 100M and input_max_size = 100M and that is not the problem.
You have to change the if condition as following
if (isset($_POST['submitFileForm'])) {
It will be working
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.
How can I handle comments in the middle of an echo command?
This syntax is getting me a syntax error but why is not compliant?
<?
echo "Print this " . /*but not this*/ . " and this\n";
?>
Am I forced to write 3 separate statements?
<?
echo "Print this "
/*but not this*/
echo " and this\n";
?>
Its because it resolves to:
echo "Print this " . . " and this\n";
Which is a syntax error, so is this:
echo "Print this " echo " and this\n";
With the exception of inside string literals, comments effectively don't exist in the code upon execution.
Include the second (or the first) . in the comment:
echo "Print this " . /*but not this .*/ " and this\n";
That will make it resolve to:
echo "Print this " . " and this\n";
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);
I have a huge list of stuff for a glossary ( about 17 pages worth ) that I have to put into an XML file. So I decided I'd use php to make it. My code works, except where ALL the XML code is, it doesn't show because it's trying to render it. Help?
$arg=explode("\n", $strang);
echo count($arg);
for ($i=0;$i<=count($arg);$i=$i+3)
{
echo "<word id='" . $arg[$i+1] . "'>";
echo "<desc>" . $arg[$i] . " - " . $arg[$i+2] . "</desc>";
echo "<pic></pic>";
echo "<audio></audio>";
}
I assume by render it you mean in your browser? If so, you'll need to escape the characters so they will be interpreted literally rather than as markup.
Check out htmlspecialchars and htmlentities
use CDATA construction:
echo "<desc><![CDATA[" . $arg[$i] . " - " . $arg[$i+2] . "]]></desc>";
If this is your entire script, fastest way would probably be to swap all of the <'s with <
$arg=explode("\n", $strang);
echo count($arg);
for ($i=0;$i<=count($arg);$i=$i+3)
{
echo "<word id='" . $arg[$i+1] . "'>";
echo "<desc>" . $arg[$i] . " - " . $arg[$i+2] . "</desc>";
echo "<pic></pic>";
echo "<audio></audio>";
}