I am fairly new to the php world and have been creating an inventory tracking system for one of my side businesses. Most of the basics are working, but I am having issues with my "upload pdf" function. Even though it works and uploads the pdf file to its target location, I cannot get the file name ($docid) to be an integer that auto increments every time there is a submission so that files never have the same name. Below is the code I have working:
$pdfPath = "/Documents/TEST/";
$maxSize = 102400000000;
$docid = TEST;
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['upload_pdf'])) {
if (is_uploaded_file($_FILES['filepdf']['tmp_name'])) {
if ($_FILES['filepdf']['type'] != "application/pdf") {
echo '<p>The file is not in PDF</p>';
} else if ($_FILES['filepdf']['size'] > $maxSize) {
echo '<p class="error">File is too big! Max size is =' . $maxSize . 'KB</p>';
} else {
$menuName = "Order_Receipt_".$docid.".pdf";
$result = move_uploaded_file($_FILES['filepdf']['tmp_name'], $pdfPath . $menuName);
if ($result == 1) {
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL=http://localhost/website/enter_new_order_success.html">';
} else {
echo '<p class="error">Error</p>';
}
}
}
I know I need some sort of loop to auto increment that $docid variable but I cannot seem to figure it out. I have read up on the topic, but auto increment with the if statement is throwing me off. Any help would be greatly appreciated.
Cheers
Well, unless you store the entries to keep track in a database or similar you could check what entries you have in your upload folder and increment it by one.
The glob function is useful for that:
http://php.net/manual/en/function.glob.php
$myFiles = sort(glob('/Documents/TEST/*.pdf')); // returns an array of pdf files in the target folder. Using sort to sort the array e.g. file_1_.pdf,file_2_.pdf,file_3_.pdf, etc
//last element
$lastFile = end($myFiles); //returns the last file in the array
//get the number and increment it by one
$number = explode('_',$lastFile);
$newNumber = $number[1] + 1; //add this to the name of your uploaded php file.
$pdfUploadedFile= "Order_Receipt_".$newNumber."_.pdf";
As pointed out in the comments... I find it a better idea to name it with a timestamp generated string. And also don't forget the quotes around your strings.
$docid = TEST;
should be:
$docid = 'TEST';
Edit
Even better would be naming it in a formatted date I suppose.
$pdfUploadedFile= "Order_Receipt_".date("Y-m-d-H-i-s").".pdf"; // will output something like Order_receipt_2014-09-24-11-14-44.pdf
Related
In PHP I am trying to have it so the user can insert an array of an index that they want removed and then it will echo out that array without the array that they didn't want. Right now the troublesome part of my code for the main file is
include("/opt/lampp/htdocs/upload/styles/styles.php");
if ($_SERVER['REQUEST_METHOD'] == "POST") {
//this is the content of the array that the user wants gone//
$want = $_POST['which'];
$file = fopen("/opt/lampp/htdocs/upload/styles/styles.php", "a");
if (in_array($want, $allStyles)) {
$index = array_search($want, $allStyles);
fwrite($file, " unset(\$allStyles[$index]);");
fclose($file);
echo implode(", ", $allStyles);
} else {
echo "error";
}
}
styles.php is
<?php
$allStyles[] = 'one';
$allStyles[] = 'all';
If I insert "all" for $want it will unset the array where it contains "all" and if I do
php styles.php
in my linux terminal it will only echo out "one" but if I do this on my page on my web browser it will echo out both strings. How can I make it so it will only echo the array that wasn't asked to be removed?
not sure if I understood your problem (or what you want to achieve) properly but, try this code:
$file='/opt/lampp/htdocs/upload/styles/styles.php';
include($file);
if(isset($_POST['which'])){
$want=$_POST['which'];
if(in_array($want,$allStyles)){
$index=array_search($want,$allStyles);
unset($allStyles[$index]);
file_put_contents($file,$allStyles);
}else{
echo "error";
}
}
You only want to change the file if $_POST['which'] is set, not on every POST action, I guess.
You just search the index (like you already did the right way) then unset it (what was wrong in your code, I guess) then you write it (file_put_contents() makes the code a bit more readable).
Last thing: I've moved the path to the file in $file in order to make it more maintainable
I'm working on a php file where I want to create one or more directories with names ranging from 1 to 999 or more. I'm creating the first of all directories using the following code:
<?php
$id = '001';
mkdir($id)
?>
What I want to succeed is to automatically create a new directory using as a name the next available number (i.e. 002, 003, 004, 005 etc) either as a string or an integer. However, I really stuck and I try to use:
<?php
$id = 001;
if (file_exists($id)) {
$id = $id + 1;
mkdir($id);
}
?>
..but it doesn't work. Any ideas?
I forgot to mention that the above code is part of the if statement inside the same php code.
Several ways to do this, depending on your use case. This function may work for you:
<?PHP
function makedir($id){
if(file_exists($id)){
$id++;
makedir($id);
}else{
mkdir($id);
return true;
}
}
makedir(1);
This solution of incremented directory names is going to become ugly after a while though; you should probably find a better solution to your problem.
You could do something like this:
// Loop through all numbers.
for ($i = 1; $i <= 999; $i++) {
// Get the formatted dir name (prepending 0s)
$dir = sprintf('%03d', $i);
// If the dir doesn't exist, create it.
if (!file_exists($dir)) {
mkdir($dir);
}
}
Edit: the above was assuming you wanted to make all 999 directories. You could do the following to just append the next available number:
function createDir($dir) {
$newDir = $dir;
$num = 1;
while (file_exists($newDir)) {
$newDir = $dir.sprintf('%03d', $num++);
}
return $newDir;
}
I am fairly new to the php world and have been creating an inventory tracking system for one of my side businesses. Most of the basics are working, but I am having issues with my "upload pdf" function. Even though it works and uploads the pdf file to its target location, I cannot get the file name ($docid) to be an integer that auto increments every time there is a submission so that files never have the same name. Below is the code I have working:
$pdfPath = "/Documents/TEST/";
$maxSize = 102400000000;
$docid = TEST;
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['upload_pdf'])) {
if (is_uploaded_file($_FILES['filepdf']['tmp_name'])) {
if ($_FILES['filepdf']['type'] != "application/pdf") {
echo '<p>The file is not in PDF</p>';
} else if ($_FILES['filepdf']['size'] > $maxSize) {
echo '<p class="error">File is too big! Max size is =' . $maxSize . 'KB</p>';
} else {
$menuName = "Order_Receipt_".$docid.".pdf";
$result = move_uploaded_file($_FILES['filepdf']['tmp_name'], $pdfPath . $menuName);
if ($result == 1) {
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL=http://localhost/website/enter_new_order_success.html">';
} else {
echo '<p class="error">Error</p>';
}
}
}
I know I need some sort of loop to auto increment that $docid variable but I cannot seem to figure it out. I have read up on the topic, but auto increment with the if statement is throwing me off. Any help would be greatly appreciated.
Cheers
Well, unless you store the entries to keep track in a database or similar you could check what entries you have in your upload folder and increment it by one.
The glob function is useful for that:
http://php.net/manual/en/function.glob.php
$myFiles = sort(glob('/Documents/TEST/*.pdf')); // returns an array of pdf files in the target folder. Using sort to sort the array e.g. file_1_.pdf,file_2_.pdf,file_3_.pdf, etc
//last element
$lastFile = end($myFiles); //returns the last file in the array
//get the number and increment it by one
$number = explode('_',$lastFile);
$newNumber = $number[1] + 1; //add this to the name of your uploaded php file.
$pdfUploadedFile= "Order_Receipt_".$newNumber."_.pdf";
As pointed out in the comments... I find it a better idea to name it with a timestamp generated string. And also don't forget the quotes around your strings.
$docid = TEST;
should be:
$docid = 'TEST';
Edit
Even better would be naming it in a formatted date I suppose.
$pdfUploadedFile= "Order_Receipt_".date("Y-m-d-H-i-s").".pdf"; // will output something like Order_receipt_2014-09-24-11-14-44.pdf
I'm using TCPDF along with FPDI to create documents in PDF based on a template using a PHP form.
I need a way to ID them. The problem is - most of these documents were already created manually, thus having ID format already specified.
It's basically Name-DD.MM.YYYY-X.pdf and it can't change.
For example, Document-01.01.2014-2, where 2 means it's a second document issued that day.
Is there a way to do that automatically? I'm using a traditional <form> with action set to the PHP TCPDF script and it works flawlessly, but how to specify that if something was already generated today then do $var = $var + 1 and then reset it at midnight?
You could try using the function file_exists(), in order to test if the base name is already generated or not.
If it is, simply create a loop and increment your $var to test iteratively your documents.
Example:
$baseName = "Name-DD.MM.YYYY";
$extension = ".pdf";
$i = 0;
while(1)
{
if($i > 0)
$testName = $baseName."-".$i.$extension;
else
$testName = $baseName.$extension;
if(!file_exists($testName))
break;
$i++;
}
if($i > 0)
$validName = $baseName."-".$i.$extension;
else
$validName = $baseName.$extension;
Hoping my answer would help you,
Venom
My website has an image in a certain place and when a user reloads the page he should see a different image on the same place. I have 30 images and I want to change them randomly on every reload. How do I do that?
Make an array with the "picture information" (filename or path) you have, like
$pictures = array("pony.jpg", "cat.png", "dog.gif");
and randomly call an element of that array via
echo '<img src="'.$pictures[array_rand($pictures)].'" />';
Looks weird, but works.
The actual act of selecting a random image is going to require a random number. There are a couple of methods that can help with this:
rand() is used to generate a random number.
array_rand() is used to select a random element's index from an array.
You can think of the second function as a shortcut for using the first if you're specifically dealing with an array. So, for example, if you have an array of image paths from which to select the one you want to display, you can select a random one like this:
$randomImagePath = $imagePaths[array_rand($imagePaths)];
If you're storing/retrieving the images in some other way, which you didn't specify, then you may not be able to use array_rand() as easily. But, ultimately, you need to generate a random number. So some use of rand() would work for this.
If you store the information in your database, you can also SELECT a random image:
MySQL:
SELECT column FROM table
ORDER BY RAND()
LIMIT 1
PgSQL:
SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1
Best,
Philipp
An easy way to create random images on popup is this method below.
(Note: You have to rename the images to "1.png", "2.png", etc.)
<?php
//This generates a random number between 1 & 30 (30 is the
//amount of images you have)
$random = rand(1,30);
//Generate image tag (feel free to change src path)
$image = <<<HERE
<img src="{$random}.png" alt="{$random}" />
HERE;
?>
* Content Here *
<!-- Print image tag -->
<?php print $image; ?>
This method is simple and I use this every time when I need a random image.
Hope this helps! ;)
I've recently written this which loads a different background on every pageload. Just replace the constant with the path to your images.
What it does is loop through your imagedirectory and randomly picks a file from it. This way you don't need to keep track of your images in an array or db or whatever. Just upload images to your imagedirectory and they will get picked (randomly).
Call like:
$oImg = new Backgrounds ;
echo $oImg -> successBg() ;
<?php
class Backgrounds
{
public function __construct()
{
}
public function succesBg()
{
$aImages = $this->_imageArrays( \constants\IMAGESTRUE, "images/true/") ;
if(count($aImages)>1)
{
$iImage = (int) array_rand( $aImages, 1 ) ;
return $aImages[$iImage] ;
}
else
{
throw new Exception("Image array " . $aImages . " is empty");
}
}
private function _imageArrays( $sDir='', $sImgpath='' )
{
if ($handle = #opendir($sDir))
{
$aReturn = (array) array() ;
while (false !== ($entry = readdir($handle)))
{
if(file_exists($sDir . $entry) && $entry!="." && $entry !="..")
{
$aReturn[] = $sImgpath . $entry ;
}
}
return $aReturn ;
}
else
{
throw new Exception("Could not open directory" . $sDir . "'" );
}
}
}
?>