php array_walk function calling multiple functions randomly in a loop - php

I am using array_walk in a script where I can call one specific function; now, I would like to call a function randomly from a pool of similar functions and manipulate the array values. It could be a loop construct. To be more specific, they are all image functions, generating images dynamically. Another requirement is that I need to save images in a particular order in a folder such as 001.jpg, 002.jpg, 003.jpg and so on. Currently, I am saving images using the code imagejpeg($im, "savedimages/" . time() . "-" . rand() . ".jpg", 90); As I call a function randomly, is it possible to maintain a similar order in saving images. I need an idea how to do that.
$fontFace = 'AmsiPro-Ultra.ttf';
$sentences = preg_split('/(?<=[.?!])\s+(?=[a-z])/i', $html);
array_walk($sentences, 'dynamicImage', $fontFace);
function dynamicImage($sentence, $key, $fontFace)
{
$img = 'green.jpg';
$client = new Client;
$image = $client->loadJpeg($img);
$palette = $image->extract();
imagickResize($img);
// create a transparent base image that we will merge the square image into.
$img = new Img();
$img->create(640, 720, true);
// first image; merge with base.
$img2 = new Img('small_square_img.jpg');
$img->merge($img2);
$img->save();
$color = 'D2F57D';
pngcolorizealpha('second_img.png', $color);
stringFunction($sentence, $palette[0], $fontFace);
$im = mergeImages(array(
'first.image.jpg',
'second.image.jpg'
));
# header('Content-type: image/jpg');
imagejpeg($im, "savedimages/" . time() . "-" . rand() . ".jpg", 90);
}

something like this
$func_1 = function(){
echo '1';
};
$func_2 = function(){
echo '2';
};
$functions = array(
$func_1,
$func_2,
..
);
array_shuffle( $functions );
$functions[1]( );
or
foreach( $functions as $index => $function ){
$function();
}
On the last one array_shuffle, if I remember right will reset the keys, if not you can do array_values($functions ) to reset them. Also note I've not tested this, but essentially that should work.

Related

PHP, need file to be overwritten or deleted after use

I have written a function to get a file from S3 and get the number of pages from it. (It's a PDF.) Everything works fine until I try and do the same for multiple files. Now it is just returning the number of pages of the last file. I think that the problem is that local.pdf needs to be deleted or overwritten, but I'm not sure how. I thought it would automatically overwrite it.
I tried using $pdf->cleanUp(); but that doesn't seem to do anything. It is still returning the page count of the last file.
This is the function that gets called for each child job:
public function getPageCountPDF($jobid) {
$this->load->library('Awss3', null, 'S3');
$PdfTranscriptInfo = $this->MJob->getDOCCSPdfTranscript($jobid);
$filename = $PdfTranscriptInfo['origfilename'];
$PdfFilename = 'uploads/' . $jobid . '/' . $filename;
$localfilename = FCPATH . 'tmp\local.pdf';
$this->S3->readfile($PdfFilename, false, 'bucket');
require_once 'application/libraries/fpdi/fpdf.php';
require_once 'application/libraries/fpdi/fpdi.php';
$pdf = new FPDI();
$pageCount = $pdf->setSourceFile($localfilename);
$pdf->cleanUp();
return $pageCount;
}
I am not getting any error messages, but the $pageCount should be 8 and then 6. The return I am getting from the function is 6 and 6.
I also tried adding
ob_clean();
flush();
But that clears the whole page, which I don't want.
I also tried using a generated name instead of local.pdf, but that doesn't work (I get a "cannot open file" message).
EDIT: This is the part that calls the function getPageCountPDF($jobid):
foreach ($copies as $copy) {
.
.
$CI = &get_instance();
$pageCount = $CI->getPageCountPDF($copy['jobid']);
.
.
}
What happens to $pageCount after
$pageCount = $CI->getPageCountPDF($copy['jobid']); ?
This gets overwritten after each iteration. Maybe you want something like $pageCount[$copy['jobid']] = $CI->getPageCountPDF($copy['jobid']); so you actually keep an array of $pageCounts to be processed further down the line.
function get_all_directory_files($directory_path) {
$scanned_directory = array_diff(scandir($directory_path), array(
'..',
'.'
));
return custom_shuffle($scanned_directory);
}
function custom_shuffle($my_array = array()) {
$copy = array();
while (count($my_array)) {
// takes a rand array elements by its key
$element = array_rand($my_array);
// assign the array and its value to an another array
$copy [$element] = $my_array [$element];
// delete the element from source array
unset($my_array [$element]);
}
return $copy;
}
So you can call get_all_directory_files which calls custom_shuffle
Then you can loop through while reading them. In case you want to delete the files
You can proceed with :
$arrayfiles = get_all_directory_files('mypath');
foreach ($arrayfiles as $filename) {
echo 'mypath/'.$filename; //You can do as you please with each file here
// unlink($filename); if you want to delete
}

get random background image using php

I want to get a random background image using php. Thats done easy (Source):
<?php
$bg = array('bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg', 'bg-05.jpg', 'bg-06.jpg', 'bg-07.jpg' );
$i = rand(0, count($bg)-1);
$selectedBg = "$bg[$i]";
?>
Lets optimize it to choose all background-images possible inside a folder:
function randImage($path)
{
if (is_dir($path))
{
$folder = glob($path); // will grab every files in the current directory
$arrayImage = array(); // create an empty array
// read throught all files
foreach ($folder as $img)
{
// check file mime type like (jpeg,jpg,gif,png), you can limit or allow certain file type
if (preg_match('/[.](jpeg|jpg|gif|png)$/i', basename($img))) { $arrayImage[] = $img; }
}
return($arrayImage); // return every images back as an array
}
else
{
return('Undefine folder.');
}
}
$bkgd = randImage('image/');
$i = rand(0, count($bkgd)-1); // while generate a random array
$myRandBkgd = "$bkgd[$i]"; // set variable equal to which random filename was chosen
As I am using this inside a wordpress theme, I need to set the $bkgd = randImage('image/'); relative to my theme folder. I thought, I could do that using:
$bgfolder = get_template_directory_uri() . '/images/backgrounds/';
bkgd = randImage($bgfolder);
When I test $bgfolder, which seems to be the most important part, using var_dump() I receive a not working path:
http://yw.hiamovi-client.com/wp-content/themes/youthwork string(19) "/images/backgrounds"
Somehow there is a space before the /images/backgrounds/. I have no idea where this comes from! …?
You'll want to change
$myRandBkgd = "$bkgd[$i]";
to
$myRandBkgd = $bkgd[$i];
If that doesn't help, use var_dump() instead of echo() to dump some of your variables along the way and check if the output corresponds to your expectations.

How to add/set images on PHPOffice/PHPWord Template?

I have an instance of a template on PHPWord. Is it possible to replace or add an image? Something like a setImageValue?
$phpWord = new \PhpOffice\PhpWord\Template('a.docx');
$phpWord->setImageValue('IMAGE_PLACEHOLDER', 'a.jpg');
$phpWord->saveAs('b.docx');
Is something like this possible?
Following code is the updated version of the one from TotPeRo (thanks again for your code!), for last phpOffice (0.11) that has evolved a little
/**
* Set a new image
*
* #param string $search
* #param string $replace
*/
public function setImageValue($search, $replace)
{
// Sanity check
if (!file_exists($replace))
{
return;
}
// Delete current image
$this->zipClass->deleteName('word/media/' . $search);
// Add a new one
$this->zipClass->addFile($replace, 'word/media/' . $search);
}
Can be called with:
$document->setImageValue('image1.jpg', 'my_image.jpg');
If you want to add, remove or replace image in template.docx you can add this to your TemplateProcessor.php file, (it works for me with PhpWord 0.14.0 version):
1.
// add this in the class
protected $_rels;
protected $_types;
public function __construct($documentTemplate){
// add this line to this function
$this->_countRels=100;
}
2.
public function save()
{
//add this snippet to this function after $this->zipClass->addFromString('word/document.xml', $this->tempDocumentMainPart);
if($this->_rels!=""){
$this->zipClass->addFromString('word/_rels/document.xml.rels', $this->_rels);
}
if($this->_types!=""){
$this->zipClass->addFromString('[Content_Types].xml', $this->_types);
}
}
3. Add this function too:
public function setImg( $strKey, $img){
$strKey = '${'.$strKey.'}';
$relationTmpl = '<Relationship Id="RID" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/IMG"/>';
$imgTmpl = '<w:pict><v:shape type="#_x0000_t75" style="width:WIDpx;height:HEIpx"><v:imagedata r:id="RID" o:title=""/></v:shape></w:pict>';
$toAdd = $toAddImg = $toAddType = '';
$aSearch = array('RID', 'IMG');
$aSearchType = array('IMG', 'EXT');
$countrels=$this->_countRels++;
//I'm work for jpg files, if you are working with other images types -> Write conditions here
$imgExt = 'jpg';
$imgName = 'img' . $countrels . '.' . $imgExt;
$this->zipClass->deleteName('word/media/' . $imgName);
$this->zipClass->addFile($img['src'], 'word/media/' . $imgName);
$typeTmpl = '<Override PartName="/word/media/'.$imgName.'" ContentType="image/EXT"/>';
$rid = 'rId' . $countrels;
$countrels++;
list($w,$h) = getimagesize($img['src']);
if(isset($img['swh'])) //Image proportionally larger side
{
if($w<=$h)
{
$ht=(int)$img['swh'];
$ot=$w/$h;
$wh=(int)$img['swh']*$ot;
$wh=round($wh);
}
if($w>=$h)
{
$wh=(int)$img['swh'];
$ot=$h/$w;
$ht=(int)$img['swh']*$ot;
$ht=round($ht);
}
$w=$wh;
$h=$ht;
}
if(isset($img['size']))
{
$w = $img['size'][0];
$h = $img['size'][1];
}
$toAddImg .= str_replace(array('RID', 'WID', 'HEI'), array($rid, $w, $h), $imgTmpl) ;
if(isset($img['dataImg']))
{
$toAddImg.='<w:br/><w:t>'.$this->limpiarString($img['dataImg']).'</w:t><w:br/>';
}
$aReplace = array($imgName, $imgExt);
$toAddType .= str_replace($aSearchType, $aReplace, $typeTmpl) ;
$aReplace = array($rid, $imgName);
$toAdd .= str_replace($aSearch, $aReplace, $relationTmpl);
$this->tempDocumentMainPart=str_replace('<w:t>' . $strKey . '</w:t>', $toAddImg, $this->tempDocumentMainPart);
//print $this->tempDocumentMainPart;
if($this->_rels=="")
{
$this->_rels=$this->zipClass->getFromName('word/_rels/document.xml.rels');
$this->_types=$this->zipClass->getFromName('[Content_Types].xml');
}
$this->_types = str_replace('</Types>', $toAddType, $this->_types) . '</Types>';
$this->_rels = str_replace('</Relationships>', $toAdd, $this->_rels) . '</Relationships>';
}
4. And this:
function limpiarString($str) {
return str_replace(
array('&', '<', '>', "\n"),
array('&', '<', '>', "\n" . '<w:br/>'),
$str
);
}
5. How to use:
//open your template
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('files/template.docx');
//add image to selector
$templateProcessor->setImg('selector',array('src' => 'image.jpg','swh'=>'200', 'size'=>array(0=>$width, 1=>$height));
// You can also clone row if you need
//$templateProcessor->cloneRow('NAME_IN_TEMPLATE', NUMBER_OF_TABLE_RECORDS);
$templateProcessor->cloneRow('SELECTOR', 4);
//save
header("Content-Disposition: attachment; filename='helloWord.docx'");
$templateProcessor->saveAs('php://output');
his is pretty much untested. but this is working for me (although mine is slightly different):
add the following function to PHPWord/Template.php :
public function save_image($id,$filepath,&$document=null) {
if(file_exists($filepath))
{
$this->_objZip->deleteName('word/media/'.$id);
$this->_objZip->addFile ($filepath,'word/media/'.$id);
//$document->setValue($id.'::width', "300px");
//$document->setValue($id.'::height', "300px");
}
}
create a document with an actual image to be used as a place holder (this solution don't allow setting the with & height of the image or multiple extensions).
unzip the the documnt and check for the file name in word/media folder. use this file name as the $id for the save_image function.
you can now use:
$document->save_image('image1',$image_path,$document);
I created some functions to extend Jerome's solution. The problem was that in order to change the picture we had to know it's reference name in the docx file. This could be difficult to find out for an average user (you have to "unZip" the docx, and find your picture manually).
My solution makes it possible to reference pictures by alt text (it needs to be in usual format: ${abc} )
so one doesn't have to know how word names the placeholder picture, the variable is enough.
Here's a link about how to add alt texts: http://accessproject.colostate.edu/udl/modules/word/tut_alt_text.php?display=pg_2
I only modified TemplateProcessor.php
First add this to the class:
/**
* Content of document rels (in XML format) of the temporary document.
*
* #var string
*/
private $temporaryDocumentRels;
The constructor function (public function __construct($documentTemplate)) needs to be extended at the end. Add this:
$this->temporaryDocumentRels = $this->zipClass->getFromName('word/_rels/document.xml.rels');
Now you can read stuff from document.xml.rels by using $this->temporaryDocumentRels
Keep Jerome's code:
/**
* Set a new image
*
* #param string $search
* #param string $replace
*/
public function setImageValue($search, $replace){
// Sanity check
if (!file_exists($replace))
{
return;
}
// Delete current image
$this->zipClass->deleteName('word/media/' . $search);
// Add a new one
$this->zipClass->addFile($replace, 'word/media/' . $search);
}
This function returns with the rId of the image you labeled:
/**
* Search for the labeled image's rId
*
* #param string $search
*/
public function seachImagerId($search){
if (substr($search, 0, 2) !== '${' && substr($search, -1) !== '}') {
$search = '${' . $search . '}';
}
$tagPos = strpos($this->temporaryDocumentMainPart, $search);
$rIdStart = strpos($this->temporaryDocumentMainPart, 'r:embed="',$tagPos)+9;
$rId=strstr(substr($this->temporaryDocumentMainPart, $rIdStart),'"', true);
return $rId;
}
And this returns the images filename, if you know it's rId:
/**
* Get img filename with it's rId
*
* #param string $rId
*/
public function getImgFileName($rId){
$tagPos = strpos($this->temporaryDocumentRels, $rId);
$fileNameStart = strpos($this->temporaryDocumentRels, 'Target="media/',$tagPos)+14;
$fileName=strstr(substr($this->temporaryDocumentRels, $fileNameStart),'"', true);
return $fileName;
}
The modifications in TemplateProcessor.php are done.
Now you can replace the image by calling this:
$templateProcessor->setImageValue($templateProcessor->getImgFileName($templateProcessor->seachImagerId("abc")),$replace);
You can also create a functionin TemplateProcessor.php that calls it like:
public function setImageValueAlt($searchAlt, $replace){
$this->setImageValue($this->getImgFileName($this->seachImagerId($searchAlt)),$replace);
}
I was looking for a solution to add an image. I read a lot of articles, I only found suitable solutions for older versions. Changing and finalized the decision to get the code.
Let us proceed to change the file TemplateProcessor.php
public function __construct($documentTemplate)
{
//add to this function
$this->_countRels=100; //start id for relationship between image and document.xml
}
public function save()
{
//add to this function after $this->zipClass->addFromString('word/document.xml', $this->tempDocumentMainPart);
if($this->_rels!="")
{
$this->zipClass->addFromString('word/_rels/document.xml.rels', $this->_rels);
}
if($this->_types!="")
{
$this->zipClass->addFromString('[Content_Types].xml', $this->_types);
}
}
//add function
public function setImg( $strKey, $img){
$strKey = '${'.$strKey.'}';
$relationTmpl = '<Relationship Id="RID" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/IMG"/>';
$imgTmpl = '<w:pict><v:shape type="#_x0000_t75" style="width:WIDpx;height:HEIpx"><v:imagedata r:id="RID" o:title=""/></v:shape></w:pict>';
$toAdd = $toAddImg = $toAddType = '';
$aSearch = array('RID', 'IMG');
$aSearchType = array('IMG', 'EXT');
$countrels=$this->_countRels++;
//I'm work for jpg files, if you are working with other images types -> Write conditions here
$imgExt = 'jpg';
$imgName = 'img' . $countrels . '.' . $imgExt;
$this->zipClass->deleteName('word/media/' . $imgName);
$this->zipClass->addFile($img['src'], 'word/media/' . $imgName);
$typeTmpl = '<Override PartName="/word/media/'.$imgName.'" ContentType="image/EXT"/>';
$rid = 'rId' . $countrels;
$countrels++;
list($w,$h) = getimagesize($img['src']);
if(isset($img['swh'])) //Image proportionally larger side
{
if($w<=$h)
{
$ht=(int)$img['swh'];
$ot=$w/$h;
$wh=(int)$img['swh']*$ot;
$wh=round($wh);
}
if($w>=$h)
{
$wh=(int)$img['swh'];
$ot=$h/$w;
$ht=(int)$img['swh']*$ot;
$ht=round($ht);
}
$w=$wh;
$h=$ht;
}
if(isset($img['size']))
{
$w = $img['size'][0];
$h = $img['size'][1];
}
$toAddImg .= str_replace(array('RID', 'WID', 'HEI'), array($rid, $w, $h), $imgTmpl) ;
if(isset($img['dataImg']))
{
$toAddImg.='<w:br/><w:t>'.$this->limpiarString($img['dataImg']).'</w:t><w:br/>';
}
$aReplace = array($imgName, $imgExt);
$toAddType .= str_replace($aSearchType, $aReplace, $typeTmpl) ;
$aReplace = array($rid, $imgName);
$toAdd .= str_replace($aSearch, $aReplace, $relationTmpl);
$this->tempDocumentMainPart=str_replace('<w:t>' . $strKey . '</w:t>', $toAddImg, $this->tempDocumentMainPart);
//print $this->tempDocumentMainPart;
if($this->_rels=="")
{
$this->_rels=$this->zipClass->getFromName('word/_rels/document.xml.rels');
$this->_types=$this->zipClass->getFromName('[Content_Types].xml');
}
$this->_types = str_replace('</Types>', $toAddType, $this->_types) . '</Types>';
$this->_rels = str_replace('</Relationships>', $toAdd, $this->_rels) . '</Relationships>';
}
//add function
function limpiarString($str) {
return str_replace(
array('&', '<', '>', "\n"),
array('&', '<', '>', "\n" . '<w:br/>'),
$str
);
}
//HOW TO USE???
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('templ.docx');
//static zone
$templateProcessor->setValue('date', htmlspecialchars(date('d.m.Y G:i:s')));
//$templateProcessor->cloneRow('NAME_IN_TEMPLATE', NUMBER_OF_TABLE_RECORDS);
$templateProcessor->cloneRow('AVTOR', 3);
//variant 1
//dynamic zone
$templateProcessor->setValue('AVTOR#1', htmlspecialchars('Garry'));
$templateProcessor->setValue('NAME#1', htmlspecialchars('Black Horse'));
$templateProcessor->setValue('SIZES#1', htmlspecialchars('100x300'));
/*$img = array(
'src' => 'image.jpg',//path
'swh'=>'350',//Image proportionally larger side
'size'=>array(580, 280)
);*/
$templateProcessor->setImg('IMGD#1',array('src' => 'image.jpg','swh'=>'250'));
$templateProcessor->setValue('AVTOR#2', htmlspecialchars('Barry'));
$templateProcessor->setValue('NAME#2', htmlspecialchars('White Horse'));
$templateProcessor->setValue('SIZES#2', htmlspecialchars('200x500'));
$templateProcessor->setImg('IMGD#2',array('src' => 'image2.jpg','swh'=>'250'));
$templateProcessor->setValue('AVTOR#3', htmlspecialchars('Backer'));
$templateProcessor->setValue('NAME#3', htmlspecialchars('Another Side'));
$templateProcessor->setValue('SIZES#3', htmlspecialchars('120x430'));
$templateProcessor->setImg('IMGD#3',array('src' => 'image3.jpg','swh'=>'250'));
//variant 2
$templateProcessor->cloneRow('AVTOR', count($output['ID']));
for($i=0;$i<count($output['ID']);$i++)
{
$templateProcessor->setValue('AVTOR'.'#'.($i+1), htmlspecialchars($output['AVTOR'][$i]));
$templateProcessor->setValue('NAME'.'#'.($i+1), htmlspecialchars($output['PNAM'][$i]));
//GetImg($output['ID'][$i]) my function return image path
$templateProcessor->setImg('IMGD'.'#'.($i+1), array('src'=>GetImg($output['ID'][$i]),'swh'=>'250'));
}
//Save
$templateProcessor->saveAs('testTemplate.docx');
modify the name of the *.docx to *.zip
open the zip folder
view the "word/media/****" the imgage name is to replace name
for setImageValue($search, $replace)
$search must be equls $replace OR use $this->zipClass->renameName ($replace , $search);
Just a note for anyone reading this in 2020 and later, PhpWord now has setImageValue() method, docs can be found here: https://phpword.readthedocs.io/en/latest/templates-processing.html#setimagevalue
If you open your .docx template as a .zip archive, you will find all media files in the word/media/ folder, then you need to find your placeholder image and replace it. I did it in the following way:
$this->templateProcessor->zip()->pclzipAddFile($imageUrl, 'word/media/image1.png');
In this case, the image styles remain the same as in the template.
Thanks to all the marvellous answers in this post, finally I had came out with my solution of replacing image in phpword 1.0.0 version and would like to share my code here : (Most thanks goes to #csanády-bálint for the detail coding)
My issue,
how can I know the rId of the image?
how can I know image is jpg or png or others?
I found out the image will begin with naming pattern of image1, image2, image3, and so on, therefore, I modified the concept to instead of getting the image by rId, I switch to get the image by name and can just ignore the image extension as well at the same time.
I only modified TemplateProcessor.php
First add this to the class :
/**
* Content of document rels (in XML format) of the temporary document.
*
* #var string
*/
private $temporaryDocumentRels;
Next, add following to the end of the constructor function (public function __construct($documentTemplate))
$this->temporaryDocumentRels = $this->zipClass->getFromName($this->getRelationsName($this->getMainPartName()));
And finally, just add following new function to TemplaceProcessor.php
/**
* Replace image by name
*
* #param string $search
* #param mixed $replace
*/
public function replaceImage($search, $replace): void
{
$fileNameStart = strpos($this->temporaryDocumentRels, $search);
$fileName = strstr(substr($this->temporaryDocumentRels, $fileNameStart), '"', true);
$this->zipClass->addFromString("word/media/" . $fileName, $replace);
}
Last but not least, the usage:
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('files/template.docx');
// image in file, eg. image1, image2, and so on
$search = 'image1';
// replacement image, can be from global http as well,
// like https://legacy.gscdn.nl/archives/images/HassVivaCatFight.jpg
$replace = 'replacement_image.png';
$fileGetContents = file_get_contents($replace);
if ($fileGetContents !== false) {
$templateProcessor->replaceImage($search, $fileGetContents);
}
The image replace is done by following code :
$this->zipClass->addFromString("word/media/" . $fileName, $replace);
where I found the code in the description of the zip() class (public function zip())
To replace an image:
$templateProcessor->zip()->AddFromString("word/media/image1.jpg",
file_get_contents($file));
Hope it helps!

Replace default image with random image from same folder

I'm just learning php and am stuck on a basic problem. I'd like my site to display one of ten random images (1.png ... 10.png) if a user doesn't choose an image. Currently it just displays a single image by default. There is a thumbnail and full size version of this image.
I've found the file where this is controlled is:
<?php
class Sabai_Helper_NoImageUrl extends Sabai_Helper
{
public function help(Sabai $application, $small = false)
{
$file = $small ? 'no_image_small.png' : 'no_image.png';
return $application->getPlatform()->getAssetsUrl() . '/images/' . $file;
}
}
I've tried to replace 'no_image_small.png' with the names of my images typed out in quotes ('1.png', '2.png',...). Other answers I've seen on stackoverflow are a little too advanced for me to apply as I don't know where to add arrays for both the 'no_image_small.png' and 'no_image.png'.
Thanks very much
I'm not sure what framework you are using, what classes are extended, but try this:
class Sabai_Helper_NoImageUrl extends Sabai_Helper
{
public function help(Sabai $application, $small = false)
{
$random = rand(1, 10);
$file = $small ? $random.'_small.png' : $random.'.png';
return $application->getPlatform()->getAssetsUrl() . '/images/' . $file;
}
}
This assumes, that the images "1.png".."10.png" and "1_small.png".."10_small.png" are located in the same directory, where no_image_small.png and no_image.png are stored.
For example:
$random = rand(1, 10); // generating random number and saving to $random variable
echo $random.'.png'; // concatenating random number to .png extension
Outputs:
8.png
or any other from 1 to 10
This should set $file variable with the correct image.
Reference: rand
Try using php rand()
You can use rand(1,10) this means echo out a random numbers from 1 to 10.
like for example: echo rand(1,10)."jpg";

Jquery causes unintended DB row creation in cake

I have this jquery code in a view, relating to my uploads controller:
function screenshot(){
var dataUrl = renderer.domElement.toDataURL("image/png");
$.post("picturepicker", {dataUrl: dataUrl, uploadnumber: 2
}
}
It successfully sends data to this function:
public function picturepicker(){
...
if($this->request->is('post')){
define('UPLOAD_DIR', WWW_ROOT . 'img/'); // increase validation
$img = $_POST['dataUrl']; // Tried $this->request['dataURL'], retrieved 'dataURL' just fine
$upload = $_POST['uploadnumber']; // tried $this->request['uploadnumber'], did not retrieve 'uploadnumber'
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . $upload . '.png'; // UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
Which works fine, except that every time I ran the javascript, a new database row is created. Since I have no create function, I imagine that somehow jquery is inadvertently calling this function:
public function upload(){
if ($this->request->is('post')) {
//var_dump($this->request->data);
$this->Upload->create();
....
However, I doubt that since the rows are still added even when I delete all references to the create function.
So why might this happen, and how should I fix it? I am suspecting that somehow the jquery code is calling all of my functions, and that I need to put an if block around any of the others that take post data. I have been told that this should not be the case, and that perhaps cake's routing is to blame. Alternatively, I might have missed something in the cake documentation - perhaps cake is set up to make a new DB row for EVERY post request, and I need to tell it not to somehow.

Categories