PHP OOP mt_rand() function do it twice by calling method
I write a class for doing FTP stuff When i calling a method from my class to make an directory on FTP, it creates the folder two times if i'm using the mt_rand() function. I use mt_rand() to create unique id/name for my folder to prevent duplicates.
I'm trying also uniqid() function but have the same result. What i'm doing wrong?
Here is my class:
class Ftp
{
private $host;
private $username;
private $password;
private $port;
private $mode;
private $stream;
private $connected;
private $Createdir;
private $subdir;
private $files;
// make FTP connection
function __construct( $host, $username, $password, $port = 21, $mode){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->port = $port;
$this->mode = $mode;
}
// FTP connect
protected function connect(){
return ftp_connect($this->host, $port);
}
// FTP login and create connection
public function open(){
$connect = $this->connect();
if ( $connect == false ){
// give a error if connection failed
die( "Kan niet verbinden met " . $this->host );
}
if( ftp_login($connect, $this->username, $this->password) ){
$this->stream = $connect;
$this->connected = true;
}
}
// create folder
public function create_folder( $temp_dir ){
$this->Createdir = $temp_dir;
/* if( ftp_mkdir( $this->stream, $this->Createdir ) ){
return true;
} */
/* if( $this->folder_exists() === false ) {
} */
//return false;
}
// create subfolder
public function create_subfolder( $dir ){
$this->subdir = $dir;
if ( ftp_chdir( $this->stream, $this->Createdir ) ){
if ( ftp_mkdir( $this->stream, $this->subdir ) ){
return $this->subdir;
}
}
}
// check if folder exists
protected function folder_exists(){
if ( ftp_chdir( $this->stream, $this->Createdir ) ){
return true;
}
return false;
}
// upload files
public function upload( $files ){
$this->files = $files;
if ( ftp_put( $this->stream, $this->Createdir, $this->files) ){
return true;
}
}
// close FTP connection
public function __destruct(){
if( $this->connected ){
ftp_close($this->stream);
}
}
}
$unique_id = date("Y-m-d",time()) ."_". $_POST["prod_id"] ."_".uniqid(); // creating unique dir into temp_files
$ftp = new Ftp( get_option("ftp_host"), get_option("ftp_user"), get_option("ftp_pass") , 21, get_option("ftp_mode"));
$ftp->open();
$ftp->create_folder('temp_files');
$ftp->create_subfolder($unique_id);
See also questions close to this topic
-
WooCommerce Dynamic Product Category Slug based on Country Code
Is there a way to write a custom code to create different versions of the product category URL, based on the user visited country, handling what is the country code is an easy part however I want to have a dynamic URL based on detected country code.
for example
https://website.com/uk/category1
https://website.com/us/category1
https://website.com/fr/category1
this will be for the same product category, all I need is to have a dynamic product category prefix based on this dynamic variable from the visitor session (country code)
-
bref.sh php container for AWS Lambda with Neos CMS
I'm struggling to get Neos (a php based cms) to run in a docker container for AWS Lambda. I guess I have somewhere a misunderstanding and hope anyone can help.
What I did so far:
- I adjusted Neos so that all cache files will be written to the tmp folder
- I added the bref and extra-php-extensions package to composer.json
- I created a docker file, quite simple as shown by Mattheu Naploli's blog article: https://mnapoli.fr/aws-lambda-php-docker-containers/
- I have created a cloudformation template to use
sam local start-api
Dockerfile:
FROM bref/php-74-fpm COPY . /var/task # Start Bref's runtime client CMD _HANDLER=Web/index.php /opt/bootstrap
template.yml
AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: > neos-demo-lambda Sample SAM Template for neos-demo-lambda # More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst Globals: Function: Timeout: 3 Resources: Neos: Type: AWS::Serverless::Function Properties: Description: Show neos demo PackageType: Image ImageUri: neos7.demo.lambda.php74:latest #Handler: "Web/index.php /opt/bootstrap" #Handler: "Web/index.php" MemorySize: 1024 Timeout: 360 Environment: Variables: FLOW_CONTEXT: 'Production' FLOW_PATH_TEMPORARY_BASE: '/tmp/neos' FLOW_PATH_DATA_BASE: '/tmp/Data' BREF_AUTOLOAD_PATH: '/var/task/Packages/Libraries/autoload.php' AWS_S3_BUCKET_STORAGE: 'neos-lambda-demo-private' AWS_S3_BUCKET_TARGET: 'neos-lambda-demo-public' AWS_CLOUDFRONT_BASE_URI: '' AWS_REDIS_HOST: '' Events: htmlHttpApi: Type: HttpApi TimeoutInMillis: 28000 Metadata: DockerTag: neos7.lambda.demo DockerContext: ./Web/index.php Dockerfile: Dockerfile
Response of
sam local start-api
:entrypoint requires the handler name to be the first argument time="2021-04-14T22:11:48.093" level=error msg="Init failed" InvokeID= error="Runtime exited with error: exit status 142" time="2021-04-14T22:11:48.093" level=error msg="INIT DONE failed: Runtime.ExitError" Invalid lambda response received: Lambda response must be valid json 2021-04-15 00:11:48 127.0.0.1 - - [15/Apr/2021 00:11:48] "GET / HTTP/1.1" 502 -
What I don't understand, I'd expect that there is always a valid json returned, even though the php delivers a 5xx error. I'm lost ... even though this wouldn't be the case, how can I debug the issue?
In the end, I have to create my own docker image as Neos is too big to use the bref layers and I need quite some php extensions. If I could understand the current issue, I can work through this and provide a working container for everyone.
I have a few more questions, in this scenario, were I have a web application and use a container, do I have to install the bref packages with composer? That wasn't clear in the blog post. Also do I have to set the Handler in serverless/sam and if so, which would be the correct string, given that
Web/index.php
is the path in Neos?In general, Neos would work awesome in AWS. My setup would be:
- CloudFront with behaviors for static files from S3 and everything else to lambda
- Redis to store cache files from Neos
- ElasticSearch for website search and improved performance on huge sites
As soon as this is working, I'll publish all information for free for the Neos community to get this working.
Hope someone can help...
Thank you!
-
laravel 7 nothing happens when i click sign up button it seems like event is not triggering
hello and sorry for my bad English , can any one help me ? when i try to sign up nothing happens . i use laravel 7. every time I click the sign up button, nothing happens and also no errors are showing.
UserController.php
namespace App\Http\Controllers\Web\User; use Reminder; use Exception; use Modules\User\Http\Controllers\AuthController; class UserController extends AuthController { public $routes = [ 'home' => 'web.home.index', 'forgot_password' => 'frontend.forgot.password', 'reset_password' => 'web.user.reset-password', ]; public function getLogin() { $return_url = ''; if ( request()->has('return-url') ) $return_url .= request()->input('return-url'); $data = [ 'authenticate_url' => route('web.user.authenticate', ['return-url' => strip_tags(trim($return_url))]) ]; return view('web.user.login', $data); } /** * getNewAccount * * @return view */ public function getNewAccount() { return view('web.user.new-account')->with(['url' => route('web.user.post-new-account')]); } /** * Logout current user. * * @return void */ public function getForgotPassword() { return view('web.user.forgot-password')->with(['url' => route('web.user.post-forgot-password')]); } /** * * getResetPassword() * * @return template * @access public **/ public function getResetPassword($userHashId,$reminderCode) { try { $hashId = hasher($userHashId, true); if ( !$hashId ) throw new Exception('Wrong user hash key, please check the url carefully.'); $user = $this->auth->findById($hashId); $isReminderCodeExist = Reminder::exists($user); if(!$isReminderCodeExist) throw new Exception("Reset code is not exists, please retry."); return view('web.user.reset-password')->with(['url' => route('web.user.post-reset-password'), 'code' => $reminderCode, 'hash_code' => $userHashId ]); } catch (Exception $e) { return redirect()->back()->withInput()->withErrors($e->getMessage()); } } }
new-account.blade.php
@extends( "layouts.master-login") @section('content') <div class="row no-gutters justify-content-center "> <div class="hero-static col-sm-8 col-md-8 col-xl-8 d-flex align-items-center px-sm-0"> <div class="col-md-12 col-xl-10" style="margin: 0 auto;"> <div class="row no-gutters"> <div class="col-md-6 order-md-1 bg-white"> <div class="block-content block-content-full px-lg-5 py-md-5 py-lg-6"> <!-- Header --> <div class="mb-2 text-center"> <p> @include('common.logo')</p> <p class="text-uppercase font-w700 font-size-sm text-muted"> {{ __('dcm.new_account')}} </p> </div> <!-- END Header --> <!-- Sign In Form --> <form action="{{ $url }}" method="POST"> @if(session('error.message') ) <div class="form-group"> <span class="text-danger">{{ session('error.message') }}</span> </div> @endif @csrf <div class="form-group"> <input type="text" class="form-control form-control-alt {{ $errors->has('username') ? ' is-invalid' : '' }}" id="username-username" name="username" placeholder="{{ __('dcm.username_placeholder')}}"> {!! $errors->first('username', '<span class="text-danger">:message</span>') !!} </div> <div class="form-group"> <input type="text" class="form-control form-control-alt {{ $errors->has('email') ? ' is-invalid' : '' }}" id="email-email" name="email" placeholder="{{ __('dcm.email_placeholder')}}"> {!! $errors->first('email', '<span class="text-danger">:message</span>') !!} </div> <div class="form-group"> <input type="text" class="form-control form-control-alt {{ $errors->has('first_name') ? ' is-invalid' : '' }}" id="first_name-first_name" name="first_name" placeholder="{{ __('dcm.firstname_placeholder')}}"> {!! $errors->first('first_name', '<span class="text-danger">:message</span>') !!} </div> <div class="form-group"> <input type="text" class="form-control form-control-alt {{ $errors->has('last_name') ? ' is-invalid' : '' }}" id="last_name-last_name" name="last_name" placeholder="{{ __('dcm.lastname_placeholder')}}"> {!! $errors->first('last_name', '<span class="text-danger">:message</span>') !!} </div> <div class="form-group"> <input type="password" class="form-control form-control-alt {{ $errors->has('password') ? ' is-invalid' : '' }}" id="password" name="password" placeholder="{{ __('dcm.password_placeholder')}}"> {!! $errors->first('password', '<span class="text-danger">:message</span>') !!} </div> <div class="form-group"> <button type="submit" class="btn btn-block btn-hero-primary"> <i class="fas fa-plus mr-1"></i> {{ __('dcm.sign_up')}} </button> </div> <hr/> <div class="form-group"> <p class="mt-3 mb-0 d-lg-flex justify-content-lg-between"> <a class="btn btn-secondary btn-block d-block d-lg-inline-block mb-1" href="{{ route('web.user.index') }}" title="{{ __('dcm.sign_in')}}"> <i class="fa fa-fw fa-sign-in-alt mr-1"></i> {{ __('dcm.sign_in')}} </a> </p> </div> </form> <!-- END Sign In Form -->
routes/web/user.php
<?php // using this pattern to used php artisan route:cache, // instead of using router closure/grouping. $userRouteNameSpace = 'Web\User'; $middlewareName = 'dcm.logged.in'; // UserController $userController = "{$userRouteNameSpace}\UserController"; // authenticate user Route::get('user/login', "{$userController}@getLogin")->name('web.user.index'); Route::post('user/authenticate', "{$userController}@postAuthenticate") ->name('web.user.authenticate'); // logout user Route::get('user/logout', "{$userController}@logout") ->name('web.user.logout'); // forgot password Route::get('user/forgot-password', "{$userController}@getForgotPassword") ->name('web.user.forgot-password'); Route::post('user/forgot-password', "{$userController}@postForgotPassword") ->name('web.user.post-forgot-password'); // reset password Route::get('user/reset-password/{hashId}/{resetcode}', "{$userController}@getResetPassword") ->name('web.user.reset-password'); Route::post('user/reset-password', "{$userController}@postResetPassword") ->name('web.user.post-reset-password'); // create new user account Route::get('user/new-account', "{$userController}@getNewAccount") ->name('web.user.new-account'); Route::post('user/new-account', "{$userController}@postNewAccount") ->name('web.user.post-new-account'); // ProfileController $profileController = "{$userRouteNameSpace}\ProfileController"; Route::get('user/profile', "{$profileController}@getProfile") ->name('web.user.profile') ->middleware($middlewareName); Route::post('user/update-profile', "{$profileController}@postUpdateProfile") ->name('web.user.update.profile') ->middleware($middlewareName); // update user avatar Route::post('user/update-avatar/{hashId}', "{$profileController}@postUpdateAvatar") ->name('web.user.update.avatar') ->middleware($middlewareName); // Verify User Route::get('/verify','Auth\RegisterController@verifyUser')->name('verify.user');
When I click on sign up, nothing happens, it seems like event is not triggering
-
Change base URL of Yoast Sitemap
We're using wordpress for our headless CMS and the Yoast plugin to generate sitemaps. However Yoast uses the domain of the site i.e
content.domain.com
as the base url to generate the links on the sitemap. How can we change this to be the front end website? -
Wordpress Theme Editor file permissions
At some point I lost the ability to edit my theme files through the WP theme editor because the file is supposedly not writeable (
is_writable()
returns false). When accessing it, the following message is displayed:You need to make this file writable before you can save your changes. See Changing File Permissions for more information.
My site is running on my own CentOS 7 server, and I have made sure all the recommended settings for file permissions are in place:
httpd is running under the apache user
Files and folders under /var/www/ are owned by apache:apache
All files permissions are set to 644, and folders to 755
DISALLOW_FILE_EDIT is not defined
httpd.conf:
<Directory “/var/www/html”> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory>
/var/www/html/.htaccess:
# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ – [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress
Deactivated all plugins
Tested manually modifying files as apache and that worked as expected (
su -s /bin/bash apache
)
There is something else in my system I can't identify that is stopping me to be able to manage my site appropriately.
System Info:
- CentOS 7
- Apache 2.4.6
- PHP 7.4.16
- MariaDB 10.3.28
- WordPress 5.7
-
c++ how does copy constructor works
So I have following code:
struct obj { static int c; int myc; obj() : myc(c++) { std::cout << "ctor of " << myc << '\n'; } obj(const obj&) : myc(c++){ std::cout << "copy ctor of " << myc << '\n'; } ~obj() { std::cout << "dtor of " << myc << '\n'; } }; int obj::c = 1; int main(int argc, char** argv) { obj x = obj(); }
The output is:
ctor of 1 dtor of 1
However when I set the copy constructor to private my code fails. Can You explain me please why I never see the std::cout from copy constructor?
-
Why is a (final) local variable declared when using an instance variable in Java?
Consider this code I found from the LinkedList class in the JDK.
public E getLast() { final Node<E> l = last; if (l == null) throw new NoSuchElementException(); return l.item; }
First question: Why is this seemingly redundant local variable
l
declared in this code? From what I see, we could've simply usedlast
instead.
In the next code from the HashMap class, the same thing is done. The local variable
tab
is declared to be to equal to the instance variabletable
.Second question: Why is
final
not used here withtab
like it was used in the previous code?final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; }
-
Reference to Player::player without declare?
I'm using a framework, I read another questions similar to this one but I don't find the solution. I did the Player class in world.cpp and world.h
#define WORLD_H #include <iostream> #include "image.h" #include "framework.h" #include "includes.h" #include "utils.h" class Player{ public: Vector2 pos; Image sprite; bool isControlled; Player(); Player(Vector2 pos, Image sprite); Image getSprite(){ return sprite; } }; #endif
and world.cpp
#include "image.h" Player::Player(){ this->pos = Vector2(); this->sprite = NULL; this->isControlled = false; } Player::Player(vector2 pos, Image sprite){ this->pos = pos; this->sprite = sprite; this->isControlled = true; }
And I trying to pass it in to Game.cpp
#include "utils.h" #include "input.h" #include "image.h" #include "world.h" #include <cmath> Game* Game::instance = NULL; Image font; Image minifont; Image player_sprite; Player hezurdur; Color bgcolor(130, 80, 100);
But then I get this error saying that Player::player() is not defined which I don't understand.
/usr/bin/ld: CMakeFiles/TJE.dir/src/game.cpp.o: en la función `__static_initialization_and_destruction_0(int, int)': game.cpp:(.text+0x851): referencia a `Player::Player()' sin definir
(this translates as reference to Player::player() without define.