I'm trying to rename each file before uploading to Amazon S3.
I am trying to use this exact method of which was answered by #Silvertiger: PHP - upload and overwrite a file (or upload and rename it)?
If exists, rename to a random name although somehow it doesn't work.
Here is the upload post Parameter from the Amazon S3 Class:
public static function getHttpUploadPostParams($bucket, $uriPrefix = '', $acl = self::ACL_PRIVATE, $lifetime = 3600,
$maxFileSize = 5242880, $successRedirect = "201", $amzHeaders = array(), $headers = array(), $flashVars = false)
{
// Create policy object
$policy = new stdClass;
$policy->expiration = gmdate('Y-m-d\TH:i:s\Z', (time() + $lifetime));
$policy->conditions = array();
$obj = new stdClass; $obj->bucket = $bucket; array_push($policy->conditions, $obj);
$obj = new stdClass; $obj->acl = $acl; array_push($policy->conditions, $obj);
$obj = new stdClass; // 200 for non-redirect uploads
if (is_numeric($successRedirect) && in_array((int)$successRedirect, array(200, 201)))
$obj->success_action_status = (string)$successRedirect;
else // URL
$obj->success_action_redirect = $successRedirect;
array_push($policy->conditions, $obj);
if ($acl !== self::ACL_PUBLIC_READ)
array_push($policy->conditions, array('eq', '$acl', $acl));
array_push($policy->conditions, array('starts-with', '$key', $uriPrefix));
if ($flashVars) array_push($policy->conditions, array('starts-with', '$Filename', ''));
foreach (array_keys($headers) as $headerKey)
array_push($policy->conditions, array('starts-with', '$'.$headerKey, ''));
foreach ($amzHeaders as $headerKey => $headerVal)
{
$obj = new stdClass;
$obj->{$headerKey} = (string)$headerVal;
array_push($policy->conditions, $obj);
}
array_push($policy->conditions, array('content-length-range', 0, $maxFileSize));
$policy = base64_encode(str_replace('\/', '/', json_encode($policy)));
// Create parameters
$params = new stdClass;
$params->AWSAccessKeyId = self::$__accessKey;
$params->key = $uriPrefix.'${filename}';
$params->acl = $acl;
$params->policy = $policy; unset($policy);
$params->signature = self::__getHash($params->policy);
if (is_numeric($successRedirect) && in_array((int)$successRedirect, array(200, 201)))
$params->success_action_status = (string)$successRedirect;
else
$params->success_action_redirect = $successRedirect;
foreach ($headers as $headerKey => $headerVal) $params->{$headerKey} = (string)$headerVal;
foreach ($amzHeaders as $headerKey => $headerVal) $params->{$headerKey} = (string)$headerVal;
return $params;
}
Here is #Silvertiger's method:
// this assumes that the upload form calls the form file field "myupload"
$name = $_FILES['myupload']['name'];
$type = $_FILES['myupload']['type'];
$size = $_FILES['myupload']['size'];
$tmp = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
// echo "The file $filename exists";
// This will overwrite even if the file exists
move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way
This is my upload form:
<form method="post" action="<?php echo $uploadURL; ?>" enctype="multipart/form-data">
<?php
foreach ($params as $p => $v)
echo " <input type=\"hidden\" name=\"{$p}\" value=\"{$v}\" />\n";
?>
<input type="file" name="file" /> <input type="submit" value="Upload" />
</form>
And this is the Input info:
public static function inputFile($file, $md5sum = true)
{
if (!file_exists($file) || !is_file($file) || !is_readable($file))
{
self::__triggerError('S3::inputFile(): Unable to open input file: '.$file, __FILE__, __LINE__);
return false;
}
return array('file' => $file, 'size' => filesize($file), 'md5sum' => $md5sum !== false ?
(is_string($md5sum) ? $md5sum : base64_encode(md5_file($file, true))) : '');
}
You can do your renaming at this point in your code:
move_uploaded_file($tmp, $filelocation);
The $filelocation can be changed to whatever you want and the uploaded file will be renamed to that path.
Edit: The S3::getHttpUploadPostParams method always uses the file name from the upload to create the S3 resource. To change that you have to copy the method but change this line:
$params->key = $uriPrefix.'${filename}';
The '${filename} must be changed to a path of your choosing.
Replace this:
// Create parameters
$params = new stdClass;
$params->AWSAccessKeyId = self::$__accessKey;
$params->key = $uriPrefix.'${filename}';
with this:
function rand_string( $length ) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ ) {
$str .= $chars[ rand( 0, $size - 1 ) ];
}
return $str;
}
// Create parameters
$params = new stdClass;
$params->AWSAccessKeyId = self::$__accessKey;
$params->key = $uriPrefix.rand_string(5).'${filename}';
You can easily put this code.. 100 percent working.
<?php
$file=$_FILES['file']['name'];
$path ="upload/".$file;
$ext=pathinfo($path,PATHINFO_EXTENSION);
$name=pathinfo($path,PATHINFO_FILENAME);
if(file_exists($path))
{
echo "File alredy exists .So name is changed automatically & moved";
$path1="upload/";
$new_name=$path1.$name.rand(1,500).".".$ext;
move_uploaded_file($_FILES['file']['tmp_name'],$new_name);
}
else
{
echo"uploaded Sucessfully without any change";
move_uploaded_file($_FILES['file']['tmp_name'],$path);
}
?>
Related
i am using laravel 5.6, i will try to make function multiple upload video, and get frame and duration with laravel-ffmpeg, but when i try to upload one video for example, always show error like "File not found at path:",
this is my function to store video and get duration & frame :
public function doCreate($lessonsid)
{
if (empty(Session::get('contribID'))) {
return redirect('contributor/login');
}
# code...
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
'judul' => 'required',
// 'video.*' => 'mimes:mp4,mov,ogg,webm |required|max:100000',
// 'image.*' => 'mimes:jpeg,jpg,png,gif|required|max:30000'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
} else {
$now = new DateTime();
$cid = Session::get('contribID');
$title = Input::get('judul');
$image_video = Input::file('image');
$lessons_video = Input::file('video');
// dd($lessons_video);
// $media = FFMpeg::open('https:/dev.cilsy.id/assets/source/lessons/lessons-74/video-8/1. Introduction (2).mp4');
// $frame = $media->getFrameFromString('00:00:13.37');
// dd($media);
$description = Input::get('desc');
$video=Video::where('lessons_id',$lessonsid)->get();
$count_video=count($video);
if (!is_dir("assets/source/lessons/lessons-$lessonsid")) {
$newforder=mkdir("assets/source/lessons/lessons-".$lessonsid);
}
$i=$count_video + 1;
foreach ($title as $key => $titles) {
$type_video =$lessons_video[$key]->getMimeType();
if (!is_dir("assets/source/lessons/lessons-".$lessonsid."/video-".$i)) {
$newforder=mkdir("assets/source/lessons/lessons-".$lessonsid."/video-".$i);
}
$DestinationPath= 'assets/source/lessons/lessons-'.$lessonsid.'/video-'.$i;
//insert image
if(!empty($image_video[$key])){
$imagefilename = $image_video[$key]->getClientOriginalName();
$image_video[$key]->move($DestinationPath, $imagefilename);
}else{
$imagefilename = '';
}
if($imagefilename ==''){
$url_image= $imagefilename;
}else{
$urls=url('');
$url_image= $urls.'/assets/source/lessons/video-'.$i.'/'.$imagefilename;
}
//insert video
if(!empty($lessons_video[$key])){
$lessonsfilename = $lessons_video[$key]->getClientOriginalName();
$lessons_video[$key]->storeAs($DestinationPath, $lessonsfilename);
}else{
$lessonsfilename = '';
}
if($lessonsfilename ==''){
$url_video= $lessonsfilename;
}else{
$urls=url('');
$url_video= $urls.'/assets/source/lessons/video-'.$i.'/'.$lessonsfilename;
}
$store = new Video;
$store->lessons_id = $lessonsid;
$store->title = $titles;
$store->image = $url_image;
$store->video = $url_video;
$store->description = $description[$key];
$store->type_video = $type_video;
$store->durasi = 0;
$store->created_at = $now;
$store->enable=1;
$store->save();
if($store){
$media = FFMpeg::open($url_video);
// $frame = FFMpeg::open($link)
// ->getFrameFromSeconds(10)
// ->export()
// ->toDisk('public')
// ->save($filename.'.png');
dd($media);
$durationInSeconds = $media->getDurationInSeconds();
// dd($media);
}
$i++;
}
// Session::set('lessons_title',$title);
// Session::set('lessons_category_id',$category_id);
// Session::set('lessons_image',$image);
// Session::set('lessons_description',$description);
return redirect('contributor/lessons/'.$lessonsid.'/view')->with('success','Penambahan video berhasil');
}
}
this is message error, when i try to upload my video
anyone can help me?
try with public_path()
$DestinationPath= public_path().'/'.'assets/source/lessons/lessons-'.$lessonsid.'/video-'.$i;
You files are not saving, you should use public_path helper for storing and retrieving files back.
$image_video[$key]->move(public_path('lessons/lessons-'.$lessonsid.'/video-'.$i), $imagefilename);
Or you can store them into storage folder
$image_video[$key]->move(storage_path('lessons/lessons-'.$lessonsid.'/video-'.$i), $imagefilename);
You can retrieve back files using these helpers.
Hope this helps.
I am currently doing an internship and I tried to make an activity module to show playlist, from video given by a filemanager. I succeed to send the video to the database but when I want to edit my module, it doesn't show any videos in the filemanager.
I read the moodle documentation about file API and I decided to use the following code (Load existing files into draft area)
:
if (empty($entry->id)) {
$entry = new stdClass;
$entry->id = null;
}
$draftitemid = file_get_submitted_draft_itemid('attachments');
file_prepare_draft_area($draftitemid, $context->id, 'mod_glossary','attachment', $entry->id,array('subdirs' => 0, 'maxbytes' => $maxbytes, 'maxfiles' => 50));
$entry->attachments = $draftitemid;
$mform->set_data($entry);
So I put the following lines in my mod_form.php :
$filemanager_options = array();
$filemanager_options['accepted_types'] = '*';
$filemanager_options['maxbytes'] = 0;
$filemanager_options['maxfiles'] = -1;
$filemanager_options['mainfile'] = true;
$mform->addElement('filemanager', 'files', get_string('selectfiles'), null, $filemanager_options);
if (empty($entry->id)) {
$entry = new stdClass;
$entry->id = null;
}
$draftitemid = file_get_submitted_draft_itemid('mymanager');
file_prepare_draft_area($draftitemid, $this->context->id, 'mod_playlist', 'content', 0,
array('subdirs'=>true));
$entry->attachments = $draftitemid;
$mform->set_data($entry);
The problem is that the file manager is still empty, and the line "$mform->set_data($entry); " makes the page to crash(blank).
Here is a template for uploading files.
In local/myplugin/upload.php
require_once(dirname(dirname(dirname(__FILE__))) . '/config.php');
require_once(dirname(__FILE__) . '/upload_form.php');
require_login();
$context = context_system::instance();
require_capability('local/myplugin:upload', $context);
$pageurl = new moodle_url('/local/myplugin/upload.php');
$heading = get_string('myupload', 'local_myplugin');
$PAGE->set_context($context);
$PAGE->set_heading(format_string($heading));
$PAGE->set_title(format_string($heading));
$PAGE->set_url('/local/myplugin/upload.php');
echo $OUTPUT->header();
echo $OUTPUT->heading($heading);
$fileoptions = array(
'maxbytes' => 0,
'maxfiles' => '1',
'subdirs' => 0,
'context' => context_system::instance()
);
$data = new stdClass();
$data = file_prepare_standard_filemanager($data, 'myfiles',
$fileoptions, context_system::instance(), 'local_myplugin', 'myfiles', 0); // 0 is the item id.
$mform = new upload_form(
null,
array(
'fileoptions' => $fileoptions,
)
);
if ($formdata = $mform->get_data()) {
// Save the file.
$data = file_postupdate_standard_filemanager($data, 'myfiles',
$fileoptions, context_system::instance(), 'local_myplugin', 'myfiles', 0);
} else {
// Display the form.
$mform->set_data($data);
$mform->display();
}
echo $OUTPUT->footer();
Then in local/myplugin/upload_form.php
defined('MOODLE_INTERNAL') || die;
require_once($CFG->libdir . '/formslib.php');
class upload_form extends moodleform {
public function definition() {
$mform =& $this->_form;
$fileoptions = $this->_customdata['fileoptions'];
$mform->addElement('filemanager', 'myfiles_filemanager',
get_string('myfiles', 'local_myplugin'), null, $fileoptions);
$this->add_action_buttons(false, get_string('save', 'local_myplugin'));
}
}
You will also need this in /local/myplugin/lib.php
function local_myplugin_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options = array()) {
if ($context->contextlevel != CONTEXT_SYSTEM) {
send_file_not_found();
}
$fs = get_file_storage();
$file = $fs->get_file($context->id, 'local_myplugin', $filearea, $args[0], '/', $args[1]);
send_stored_file($file);
}
I'm creating a form to upload a file, using yii and php 5.5.3. Here is my code in the controller:
foreach($_FILES['settings']['name'] as $settingName => $value) {
$setting = Setting::model()->find('setting_name=:name', array(':name' => $settingName));
$setting->image_file = CUploadedFile::getInstanceByName('settings['.$settingName.']');
if (!empty($setting->image_file)) {
$extension = "jpg";
$filename = "";
if (($pos = strrpos($setting->image_file, '.')) !== FALSE) {
$extension = substr($setting->image_file, $pos + 1);
$filename = substr($setting->image_file, 0, $pos)."_".strtotime("now");
}
if (!file_exists("uploads") and !is_dir("uploads"))
mkdir("uploads", 0777, TRUE);
$setting->image_file->saveAs("uploads/" . $filename.".".$extension, false);
$setting->setting_value = "uploads/" . $filename.".".$extension;
$setting->save();
}
}
image_file is an extra attribute in model:
array('image_file', 'file', 'types' => 'gif, jpg, jpeg, png', 'maxSize' => 1024 * 1024, 'tooLarge' => 'File upload must not exceed 1MB.'),
and here is the view:
<input type="file" name="settings[store_logo]" class="input-small">
$setting->image_file->saveAs can successfully upload the file, but it also generates
Error 500 Creating default object from empty value
What went wrong? Any help would be much appreciated.
i guess, the $_FILES['settings']['name'] has a empty value in the last Key.
If you upload a File(s), they will be process as expected. The last value in your POST-array cause a NULL-return here:
// $setting === null
$setting = Setting::model()->find('setting_name=:name', array(':name' => $settingName))
and this call throws the 500.
$setting->image_file = CUploadedFile::getInstanceByName('settings['.$settingName.']');
This is my Version of your code:
<?php
foreach($_FILES['settings']['name'] as $settingName => $value) {
$setting = Setting::model()->find('setting_name=:name', array(':name' => $settingName));
// catch null-return
if(!$setting) {
echo "can't find stuff at<pre>"; print_r($settingName); echo "</pre>";
continue;
}
$setting->image_file = CUploadedFile::getInstanceByName('settings['.$settingName.']');
if ($setting->image_file) {
$extension = "jpg";
$filename = "";
if (($pos = strrpos($setting->image_file, '.')) !== FALSE) {
$extension = substr($setting->image_file, $pos + 1);
$filename = substr($setting->image_file, 0, $pos)."_".strtotime("now");
}
if (!file_exists("uploads") and !is_dir("uploads"))
// dont 0777!
mkdir("uploads", 0740, TRUE);
$setting->image_file->saveAs("uploads/" . $filename.".".$extension, false);
$setting->setting_value = "uploads/" . $filename.".".$extension;
$setting->save();
}
}
?>
My codes multiple image upload and update mysql db but one problem if id=1 It's working multiple image uploading and update.else It's not working and white page.
tables 2
musteri_soru and musteri_cevap
is updating musteri_cevap in colon resim
controller code:
function duzenle($no)
{
if($_POST)
{
$arr1['baslik'] = $this->input->post('soru');
$this->form_duzenle_model->duzenle($no,$arr1);
if($_FILES){
$dizin= "../upload/form_cevap/";
$dosya_sayi=count($_FILES['cevap']['name']);
for($i=0;$i<=$dosya_sayi;$i++){
$isim= md5(uniqid(rand()));
if(!empty($_FILES['cevap']['name'][$i])){
move_uploaded_file($_FILES['cevap']['tmp_name'][$i],"./$dizin/$isim{$_FILES['cevap']['name'][$i]}");
$arr['resim']= $dizin.$isim.$_FILES['cevap']['name'][$i];
}
$approve[] = $arr['resim'];
$it = $approve;
print_r($approve);
foreach($it as $n => $c):
/* $deneme = $this->form_duzenle_model->cevapDuzenle($n,$c); */
endforeach;
}
}
redirect('form_duzenle/', 'refresh');
}else{
$this->bc->addCrumb('Düzenle');
$veri = $this->form_duzenle_model->form_duzenleGetir($no)->row();
$veri2 = $this->form_duzenle_model->cevapListe($no)->result();
$data = array(
'baslik'=>$veri->baslik,
'veri' =>$veri,
'cevap' =>$veri2
);
$this->bc->addCrumb($veri->baslik,'form_duzenle/duzenle/'.$veri->no);
$this->layout->view('form_duzenle/form_duzenle_duzenle',$data);
}
}
Models code :
function duzenle($no,$data)
{
$this->db->update($this->tablo,$data, array('no' => $no));
}
function cevapDuzenle($n,$dat)
{
$data = array('resim' => $dat);
$this->db->update($this->ctablo,$data, array('soru_no' => $n));
}
My Tables
enter link description here
To be honest, I'm not quite sure how your upload was working as the $_FILES array shouldn't be nesting the uploads in the way you've shown above.
I'm not saying this will definitely work but it should do:
function duzenle($no)
{
//I would possible look at using the Form_validation Library here
if (empty($_POST)) {
$arr1['baslik'] = $this->input->post('soru');
$this->form_duzenle_model->duzenle($no, $arr1);
if (!empty($_FILES)) {
$dizin = "../upload/form_cevap/";
foreach ($_FILES as $name => $file) {
//If there is an error there isn't any reason to try and upload this file
if ($file['error'] !== 0) {
continue;
}
$name = $file['name'];
$isim = md5(uniqid(rand()));
move_uploaded_file($file['tmp_name'], "./$dizin/$isim$name");
$arr['resim'] = $dizin . $isim . $name;
//Not sure what's going on here so I haven't changed it
$approve[] = $arr['resim'];
$it = $approve;
print_r($approve);
foreach ($it as $n => $c):
/* $deneme = $this->form_duzenle_model->cevapDuzenle($n,$c); */
endforeach;
}
}
redirect('form_duzenle/', 'refresh');
}else {
$this->bc->addCrumb('Düzenle');
$veri = $this->form_duzenle_model->form_duzenleGetir($no)->row();
$veri2 = $this->form_duzenle_model->cevapListe($no)->result();
$data = array(
'baslik' => $veri->baslik,
'veri' => $veri,
'cevap' => $veri2
);
$this->bc->addCrumb($veri->baslik, 'form_duzenle/duzenle/' . $veri->no);
$this->layout->view('form_duzenle/form_duzenle_duzenle', $data);
}
}
Hope this helps!
Check your for loop,
$dosya_sayi=count($_FILES['cevap']['name']);
for($i=0;$i<=$dosya_sayi;$i++)
for loop condition should be $i < $dosya_sayi as array index always starts from 0.
So correct for loop is
for($i=0;$i<$dosya_sayi;$i++)
I solved the problem.Duzenle codes on change the bottom code.
function duzenle($no)
{
if($_POST)
{
$arr1['baslik'] = $this->input->post('soru');
$this->form_duzenle_model->duzenle($no,$arr1);
$cevaplar = $this->form_duzenle_model->cevapListe($no)->result_array();
if($_FILES){
$dizin= "../upload/form_cevap/";
foreach($cevaplar AS $cevap){
$i = $cevap['no'];
$isim= md5(uniqid(rand()));
if(!empty($_FILES['cevap']['name'][$i])){
move_uploaded_file($_FILES['cevap']['tmp_name'][$i],"./$dizin/$isim{$_FILES['cevap']['name'][$i]}");
$arr['resim']= $dizin.$isim.$_FILES['cevap']['name'][$i];
}
$approve[] = $arr['resim'];
$it = $approve;
$this->form_duzenle_model->cevapDuzenle($i,$arr['resim']);
}
}
redirect('form_duzenle/', 'refresh');
}else{
$this->bc->addCrumb('Düzenle');
$veri = $this->form_duzenle_model->form_duzenleGetir($no)->row();
$veri2 = $this->form_duzenle_model->cevapListe($no)->result();
$data = array(
'baslik'=>$veri->baslik,
'veri' =>$veri,
'cevap' =>$veri2
);
$this->bc->addCrumb($veri->baslik,'form_duzenle/duzenle/'.$veri->no);
$this->layout->view('form_duzenle/form_duzenle_duzenle',$data);
}
}
I'm trying to set up a php that receives variables in the URL, and then creates a passbook pass using that information.
If I manually set up the variables, everything works, but if I use $_GET to get the data from the URL, it won't show up.
Here is my index, were we are loading the variables from the URL.
<?php
$ac = $_GET['ac'];
$af = $ac;
$log = print_r($_SERVER,1);
$log .= print_r($_POST,1);
$log .= print_r($_GET,1);
file_put_contents('./log/'.time().'.txt', $log);
if(($_POST['time'] != '')||($_GET['update'] != ''))
{
require('./passkit.php');
$Certificates = array('AppleWWDRCA' => './certs/AppleWWDRCA.pem',
'Certificate' => './certs/Certificate.p12',
'CertPassword' => 'password');
$ImageFiles = array('images/icon.png', 'images/icon#2x.png', 'images/logo.png');
$datostest = array( '1' => $af,
'2' => '5',
'3' => '6');
$data = array('./data/array.php',
'./data/json.php',
'./data/small.php',
'./data/coupon.json',
'./data/event.json',
'./data/small.json',
'./data/generic.json');
if($_GET['update'] != '')
{
$example_data = 4;
}
elseif(!is_numeric($_POST['aexample']))
{
$example_data = rand(0,6);
}
else
{
$example_data = $_POST['aexample'];
}
if($example_data < 3)
{
include($data[$example_data]);
}
else
{
$JSON = file_get_contents($data[$example_data]);
}
$TempPath = './temp/';
echoPass(createPass($Certificates, $ImageFiles, $JSON, 'passtest', $TempPath));
m_uwait(12500);
die();
}
?>
Here is the pass signing process
<?php
function PEM2DER($signature)
{
$signature = substr($signature, (strpos($signature, 'filename="smime.p7s"')+20));
return base64_decode(trim(substr($signature, 0, strpos($signature, '------'))));
}
function createPass($Certificates, $ImageFiles, $JSON, $PassName = 'pass', $TempPath = './temp/', $Debug = false)
{
//define pathes
$UniquePassId = time().hash("CRC32", $_SERVER["REMOTE_ADDR"].$_SERVER["HTTP_USER_AGENT"]);
$ManifestPath = $TempPath.$UniquePassId.'/manifest.json';
$SignaturePath = $TempPath.$UniquePassId.'/signature';
$PKPassPath = $TempPath.$UniquePassId.'/'.$PassName.'.pkpass';
//create temp dir
mkdir($TempPath.$UniquePassId, 0777, true);
//generate SHA1 hashes
$FileHashes['pass.json'] = hash("SHA1", $JSON);
foreach($ImageFiles as $ImagePath)
{
$ImageName = basename($ImagePath);
$FileHashes[strtolower($ImageName)] = hash("SHA1", file_get_contents($ImagePath));
}
//save hashes as json in temp file
$Manifest = json_encode($FileHashes);
file_put_contents($ManifestPath, $Manifest);
//load .p12 certificate
$PKCS12 = file_get_contents($Certificates['Certificate']);
$certs = array();
if(openssl_pkcs12_read($PKCS12, $certs, $Certificates['CertPassword']) == true)
{
$certdata = openssl_x509_read($certs['cert']);
$privkey = openssl_pkey_get_private($certs['pkey'], $Certificates['CertPassword']);
}
//sign file hashes with AppleWWDRCA certificate
openssl_pkcs7_sign($ManifestPath, $SignaturePath, $certdata, $privkey, array(), PKCS7_BINARY | PKCS7_DETACHED, $Certificates['AppleWWDRCA']);
$ManifestSignature = file_get_contents($SignaturePath);
$ManifestSignatureDER = PEM2DER($ManifestSignature);
//put files (and strings as files) in a zip archive
$ZIP = new ZipArchive();
$ZIP->open($PKPassPath, ZIPARCHIVE::CREATE);
$ZIP->addFromString('signature', $ManifestSignatureDER);
$ZIP->addFromString('manifest.json', $Manifest);
$ZIP->addFromString('pass.json', $JSON);
foreach($ImageFiles as $ImagePath)
{
$ImageName = basename($ImagePath);
$ZIP->addFile($ImagePath, $ImageName);
}
$ZIP->close();
//load pass data und delete temp files (if debug mode is off)
$Pass['data'] = file_get_contents($PKPassPath);
$Pass['size'] = filesize($PKPassPath);
$Pass['name'] = $PassName;
if(!$Debug)
{
unlink($TempPath.$UniquePassId.'/manifest.json');
unlink($TempPath.$UniquePassId.'/'.$PassName.'.pkpass');
unlink($TempPath.$UniquePassId.'/signature');
rmdir($TempPath.$UniquePassId);
}
return $Pass;
}
function echoPass($Pass)
{
//send http headers and zip archive content to client
header('Pragma: no-cache');
header('Content-type: application/vnd.apple.pkpass');
header('Content-length: '.$Pass['size']);
header('Content-Disposition: attachment; filename="'.$Pass['name'].'.pkpass"');
echo $Pass['data'];
}
?>
And finally, here I'm using those variables.
<?php
$PassStyle = "boardingPass";
$JSON = '{
"authenticationToken": "vxwxd7J8AlNNFPS8k0a0FfUFtq0ewzFdc",
"foregroundColor" : "rgb(255, 255, 255)",
"backgroundColor" : "rgb(27, 66, 152)",
"labelColor" : "rgb(108, 173, 223)",
"barcode": {
"format": "PKBarcodeFormatQR",
"message": "'.hash("SHA256", time().rand(0,2000000000)).'",
"messageEncoding": "iso-8859-1"
},
"description": "Random '.$PassStyle.' Demo Pass",
"foregroundColor": "rgb(251, 251, 251)",
"formatVersion": 1,
"'.$PassStyle.'": {
"primaryFields": [
{
"key": "number",
"value": "'.$datostest['1'].'"
}
]
},
"logoText": "passkit.php",
"organizationName": "Apple Inc",
"passTypeIdentifier": "pass.com.apple.demo",
"serialNumber": "8j23fm3",
"teamIdentifier": "123ABCDEFG"
}';
?>
Hope you can help. Can't understand why it works if the variable is manually assigned and it isn't if it is loaded from the URL.
Thanks
Look the code what you posted above is too much and i guess its difficult to check your problem...
According to the question i guess you are not able to access the Get values.
Let me tell you how get works...
<a href="filename.php?value='what_you_want_to_pass'">
and at your page...
$value = $_GET['value'];
this is the actual syntax, just check whether u have passed the value in your link...