404 cehck status for current page - wordpress

i want to check current page's 404 status in a plugin file
i tried this but page only spinning and never finish loading
public static function check_404_status($my_url)
{
$result = false;
$my_url = self::tc_trim_slash($my_url);
$ch = curl_init($my_url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($retcode != 200) {
$result=true;
return $result;
}
else {
// echo "Specified URL exists";
}
curl_close($ch);
}
i have also tried this but it gives error
is_404 was called incorrectly. Conditional query tags do not work before the query is run. Before then, they always return false. Please see Debugging in WordPress for more information. (This message was added in version 3.1.)
public static function check_404_status($my_url)
{
$result = false;
$my_url = self::tc_trim_slash($my_url);
if(is_404())
{
$result=true;
return $result;
}
}
I am new to wordpress, can someone please help me to solve this??

is_404() conditional is set in the WP_Query class and checks is the query returns a 404 (returns no results)
So, you can try to modify your function like that
public static function check_404_status()
{
global $wp_query;
if (isset($wp_query)) {
return $wp_query->is_404();
}
return false;
}

Related

How can I fail wp_action_scheduler cron job without site break?

Wp action-scheduler job is running successfully but I want it to fail when any exception comes in the code.
try {
$records = some records in array;
foreach ($records as $r) {
$sku = $r["SKU"] ?? null;
if (!isset($sku)) {
throw new \Exception("SKU is missing");
return;
}
$product_id = Wp::wc_get_product_id_by_sku($sku);
Wp::update_post_meta($product_id, "_regular_price", 500);
}
} catch (\Exception $e) {
echo($e);
**//Here I want to fail the action scheduler job**
return false;
}
In my case, everything works correctly but it should be failed schedule job if comes into catch (\Exception $e){---} without site break.

Symfony getRootDir() + /../folder/file.ext (file_get_contents) not found

I am virtually at a brick wall with Symfony, I have a folder at /../compiled/ with some minified files, and the controller is configured to get files from getRootDir() + /../compiled/file.min.css
However, it just throws out an exception 'file not found' when call file_get_contents(file) even when the file actually exists.
I just don't know what is wrong, it is such a cryptic problem.
Code as requested:
public function atpInitAction(Request $request) // Validates the origin.
{
$content = null; $_file = $request->query->get('file');
if ($_SERVER["SERVER_NAME"] == atpHandler::getDomain())
{
// I AM FROM THE ORIGIN...
$webfolder = $this->get('kernel')->getRootDir() . '/../compiled';
$_file = $webfolder."/".$_file;
}
// What's my mime?
$_mime = 'text/plain';
if ($_file[strlen($_file)-2] == 'j') { $_mime = 'text/javascript'; }
else { $_mime = 'text/css'; }
$response = new Response();
$response->headers->set('Content-Type', $_mime);
$response->headers->set('Content-Disposition', 'filename="'.basename($_file) . '";');
$response->headers->set('Content-Length', filesize($_file));
$response->setContent(file_get_contents($_file));
$response->sendHeaders();
return $response;
}

Symfony - Setting Cookie onKernelRequest

i want to be able to set a Cookie onKernelRequest Method, but the cookie is not beeing set,
Everything else is working fine, what am missing here?
What i want to achieve is that if the user is not logged in and doesnt have the cookie he should see the http basic auth headers.
If the user is logged in or does have the cookie he has access to the preview domains without having to enter their user credentials in http basic auth.
const AUTH_USER = 'myuser';
const AUTH_PW = 'mypass';
public function sendAuthorizationHeader()
{
header('WWW-Authenticate: Basic realm="Preview Domain"');
header('HTTP/1.0 401 Unauthorized');
die();
}
public function onKernelRequest(GetResponseEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}
$request = $event->getRequest();
$host = $request->getHost();
$loginSuccessful = false;
// check if we are on a preview domain
if (preg_match('/^preview-\d+/', $host)) {
$user = $request->getUser();
$cookie = $request->cookies->get('preview_user');
$phpAuthUser = $request->server->get('PHP_AUTH_USER');
$phpAuthPw = $request->server->get('PHP_AUTH_PW');
if (isset($phpAuthUser) && isset($phpAuthPw)) {
if ($phpAuthUser == self::AUTH_USER && $phpAuthPw == self::AUTH_PW) {
$loginSuccessful = true;
}
} else if ($user === null && $cookie === null) {
$this->sendAuthorizationHeader();
}
if (!$loginSuccessful) {
$this->sendAuthorizationHeader();
} else {
$cookie = new Cookie('preview_user', true, 86400, '/', null, false, false);
$response = new Response();
$response->headers->setCookie($cookie);
$response->sendHeaders();
}
}
}
Setting a cookie on a response object doesn't do anything but adding a cookie to that request. You need to return the same response object, so Symfony renders it back to the client. Rendering it yourself is not a good idea, as there might be contents send later and it's not really testable.
It's easier done in a kernel.response event listener, since you already have a response there. Remember to use the response that your application creates. Do not create it yourself.
If you set the cookie based on logic that should also be available during the request, you can split it into two event listener methods. One will set a request attribute on kernel.request, and the other one will set the cookie on the response on kernel.response:
public function onKernelRequest(GetResponseEvent $event)
{
// your logic goes here. calculate the $result
// ...
$event->getRequest()->attributes->set('my_result', $result);
}
public function onKernelResponse(FilterResponseEvent $event)
{
$response = $event->getResponse();
$request = $event->getRequest();
$myResult = $request->attributes->get('my_result');
$cookie = new Cookie(/* ... */);
$response->headers->setCookie($cookie);
}

Symfony2 form validation without createFormBuilder

I am trying to validate the form that I have made myself in .twig file.I am not creating form using createFormBuilder. This is my Controller Code that is call for both case 1) for view 2) after submitting the form.
public function cart_newAction(Request $request)
{
$entity = new Product();
$errors = '';
if ($request->getMethod() == 'POST')
{
$validator = $this->get('validator');
$errors = $validator->validate($entity);
if (count($errors) > 0) {
echo 'Error';
}
else {
echo 'Success';
}
}
return $this->render('CartCartBundle:Cart:Add.html.twig', array('errors' => $errors ));
}
this is view file and I am showing errors like this
Add.html.twig
{% for error in errors %}
{{error}}
{% endfor %}
I have set the error in validation.yml file for name that cannot be blank.
So now when I run the view page it every times show the error after I submit the form.
If no error it should not display me the error just show the blank error.
Note:Is there any better way that I can do this so please share it.Remember that I am doing it without createFormBuilder
UPDATE
It always show me Error.Even if my form is valid and don't missing any field.
If you want to make the form yourself then you can't validate it using the Syfmony form validator. You need to use a simple PHP validation Server-side. Something like this
if ($request->getMethod() == 'POST')
{
$username = $_POST['username'];
if ($username == '')
{
// set error message here
}
}
Ok let me be clear. I gonna give you tow solutions, the first is the best and the most proper way:
1) Generate your EntityForm Type: bin/console make:form or d:g:form command.
2) Then just add some few lines to submit and get the errors.
public function cart_newAction(Request $request)
{
$entity = new Product();
$form = $this->createForm(EntityType::class, $entity);
$form->submitForm($request->request->all(), false);
if ($request->getMethod()->isPost())
{
if ($form->isValid()) {
echo 'Error';
}
else {
echo 'Success';
}
}
return $this->render('CartCartBundle:Cart:Add.html.twig', [
'errors' => $form->getErrors(),
]);
}
The second solution is bind your data into your entity object because we need to set the data into our object.
1) First step create a private fonction in your current class to bind all the submited data:
private function bindEntityValues(Product $entity, array $data) {
foreach ($data as $key => $value){
$funcName = 'set'+ucwords($key);
if(method_exists($entity, $funcName)) $entity->$funcName($value);
}
}
Then your cart_newAction should be like this:
public function cart_newAction(Request $request)
{
$entity = new Product();
$this->bindEntityValues(entity, $request->request->all());
$errors= $this->get('validator')->validate($entity)
if (count($errors) > 0) {
echo 'Error';
}
else {
echo 'Success';
}
}
return $this->render('CartCartBundle:Cart:Add.html.twig', ['errors' => $errors]);
}
Wish this helped you to have a clear vision.
You must check if $errors is empty or not :
if (count($errors) > 0) {
return $this->render('CartCartBundle:Cart:Add.html.twig', array('errors' => $errors ));
} else {
return $this->render('CartCartBundle:Cart:Add.html.twig');
}
See the doc here.

phpexcel error when use include_once, require_once?

I use phpexcel in my project, if i call my class by my function, excel file cannot open
I call my class:
$Model = loadModel('cpm','cpm',$this->registry);
My function:
function loadModel($com='',$class_name='',$registry=null) {
if (empty($com)){
$com = 'admin';
}
$filename = strtolower($class_name) . '.class.php';
$file = PATH_MODEL.DS.$com.DS.$filename;
if (file_exists($file) == false){
return false;
}
require_once($file);
if($registry != NULL){
$model = new $class_name($registry);
}else{
$model = new $class_name;
}
return $model;
}
When i change to
/*require_once($file);
if($registry != NULL){
$model = new $class_name($registry);
}else{
$model = new $class_name;
}*/
$model=true;
return $model;
it work. In my project, I use autoload:
function __autoload($class_name) {
/*** get the component from the url ***/
$com = (empty($_GET['com'])) ? '' : $_GET['com'];
if (empty($com)){
$com = 'admin';
}
$filename = strtolower($class_name) . '.class.php';
$file = PATH_MODEL.DS.$com.DS.$filename;
if (file_exists($file) == false){
return false;
}
requine_once ($file);
}
I am not sure it is reason.
I don't found any error in log.
Any help, thank.
I found that if I require(once) or include(once) file in controler, excel file will be can not open.
class excelController extends baseController {
public function index(){
require('abc.class.php');
$this->registry->template->show('excel', false);
}
}
It's probable that your autoloader is clashing with PHPExcel's autoloader. See section 3.2 of the developer documentation (entitled "Lazy Loader") for advice on registering your own autoloader with spl_autoload_register() so that the two can co-exist

Resources